asp.net core跨域访问ajax的验证访问

简介:


跨域需要服务端和客户端都作处理。

首先让asp.net core跨域,在nuget中添加Microsoft.AspNetCore.Cors的引用,然后在StartUp.cs中的ConfigureServices中添加如下代码:

1
2
3
4
     var  urls =  "http://localhost:5000/" ;
     services.AddCors(options =>
     options.AddPolicy( "MyDomain" ,
builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));

再在Configure中添加

1
app.UseCors( "AllowSameDomain" );
1
2
再添加验证,添加Microsoft.AspNetCore.Authentication.Cookies引用
在Configure中添加
1
2
3
4
5
6
7
8
9
app.UseCookieAuthentication( new  CookieAuthenticationOptions
{
     AuthenticationScheme =  "validates" ,
     LoginPath =  new  Microsoft.AspNetCore.Http.PathString( "/login" ),
     AccessDeniedPath =  new  Microsoft.AspNetCore.Http.PathString( "/Home/Error" ),
     AutomaticAuthenticate =  true ,
     AutomaticChallenge =  true ,
     SlidingExpiration =  true
});

Controller中添加允许跨域特性,然后再添验证特性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using  Microsoft.AspNetCore.Mvc;
using  Microsoft.AspNetCore.Cors;
using  Microsoft.AspNetCore.Authorization;
using  System.Security.Claims;
  
namespace  WebUI.Controllers
{
     [Authorize(Roles =  "Admin" )]
     [EnableCors( "MyDomain" )]
     public  class  HomeController : Controller
     {
         /// <summary>
         /// 测试方法
         /// </summary>
         /// <param name="item"></param>
         /// <returns></returns>
         [HttpPost( "additem" )]
         public  IActionResult AddItem(Item item)
         {
             return  new  JsonResult( new  { Result = 0, Message =  "添加成功" , Content = item.ToString(), UserName = User.Identity.Name },  new  Newtonsoft.Json.JsonSerializerSettings());
         }
         /// <summary>
         /// 登录
         /// </summary>
         /// <param name="username">用户名</param>
         /// <param name="password">密码</param>
         /// <returns></returns>
         [AllowAnonymous]
         [HttpPost( "login" )]
         public  IActionResult Login( string  username,  string  password)
         {
             if  (username ==  "aaa"  && password ==  "111" )
             {
  
                 var  user =  new  { RoleType = 1, Name =  "张三丰" , ID = 1 };
                 string  roleId = user.RoleType.ToString();
                 var  roleName =  "" ;
                 switch  (roleId)
                 {
                     case  "1" :
                         roleName =  "Admin" ; //管理员
                         break ;
                 }
                 var  id = user.ID.ToString();
                 var  claims =  new  Claim[] {
                       new  Claim(ClaimTypes.UserData,roleId),
                       new  Claim(ClaimTypes.Role,roleName),
                       new  Claim(ClaimTypes.Name,username)
                 };
                 HttpContext.Authentication.SignInAsync( "validates" new  ClaimsPrincipal( new  ClaimsIdentity(claims,  "Cookie" )));
                 HttpContext.User =  new  ClaimsPrincipal( new  ClaimsIdentity(claims));
  
                 return  new  JsonResult( new  { Message =  "登录成功"  },  new  Newtonsoft.Json.JsonSerializerSettings());
  
             }
             else
             {
  
                 return  new  JsonResult( new  { Message =  "用户名或密码错误"  },  new  Newtonsoft.Json.JsonSerializerSettings());
             }
         }
     }
}
在JQuery中,使用$.ajax登录后,才能执行保存,否则没有权限保存数据,重点时ajax请求时xhrFields: {withCredentials: true }这个属性,可以把登录后的cookie在后面的操作中带回服务端(关于原理不多说了)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html>
< html >
< head >
     < meta  http-equiv = "Content-Type"  content = "text/html; charset=utf-8"  />
     < title ></ title >
     < meta  charset = "utf-8"  />
     < script  src = "bower_components/jquery/dist/jquery.js" ></ script >
</ head >
< body >
     < input  id = "login"  value = "登录"  type = "button"  />
     < input  id = "sava"  value = "保存"  type = "button"  />
     < span  id = "message" ></ span >
     < script >
         $("#login").click(function () {
             $.ajax({
                 type: 'POST',
                 url: "http://localhost:5000/login",
                 data: { username: "aaa", password: "111" },
                 dataType: "json",
                 xhrFields: {
                     withCredentials: true
                 },
                 success: function (result) {
                     $("#message").html(result.Message);
                 },
                 error: function () {
                     $("#message").html("登录失败!");
                 }
             });
         })
  
         $("#sava").click(function () {
             $.ajax({
                 type: 'POST',
                 url: "http://localhost:5000/additem",
                 data: { ID: 112, Name: "李四", Birthday: "2017-01-23" },
                 dataType: "json",
                 //必须有这项的配置,不然cookie无法发送至服务端
                 xhrFields: {
                     withCredentials: true
                 },
                 success: function (result) {
                     $("#message").html(result.Message + result.Content + result.UserName);
                 },
                 error: function (xhr,status) {
                     $("#message").html(status);
                 }
             });
         })
     </ script >
</ body >
</ html >

来看一下测试结果:

当直接点保存时,系统会导航登录

wKiom1iIfwSwKSFSAAnHrGpe21U192.png-wh_50


登录

wKiom1iIfx_hOmO4AAtih6b1vIU616.png-wh_50


再次保存

wKioL1iIf1_TzLaSAAvJ5_Qs9Ns751.png-wh_50














本文转自桂素伟51CTO博客,原文链接: http://blog.51cto.com/axzxs/1894227,如需转载请自行联系原作者



相关文章
|
1天前
|
开发框架 前端开发 JavaScript
ASP.NET AJAX使用方法概述(三)
ASP.NET AJAX使用方法概述(三)
|
2天前
|
开发框架 缓存 前端开发
安装ASP.NET AJAX (一安装)
安装ASP.NET AJAX (一安装)
|
2月前
|
XML 开发框架 .NET
C# .NET面试系列八:ADO.NET、XML、HTTP、AJAX、WebService
## 第二部分:ADO.NET、XML、HTTP、AJAX、WebService #### 1. .NET 和 C# 有什么区别? .NET(通用语言运行时): ```c# 定义:.NET 是一个软件开发框架,提供了一个通用的运行时环境,用于在不同的编程语言中执行代码。 作用:它为多语言支持提供了一个统一的平台,允许不同的语言共享类库和其他资源。.NET 包括 Common Language Runtime (CLR)、基础类库(BCL)和其他工具。 ``` C#(C Sharp): ```c# 定义: C# 是一种由微软设计的面向对象的编程语言,专门为.NET 平台开发而创建。 作
181 2
|
6月前
|
开发框架 前端开发 .NET
用ajax和asp.net实现智能搜索功能
用ajax和asp.net实现智能搜索功能
46 0
|
10月前
|
前端开发
解决.NET Core Ajax请求后台传送参数过大请求失败问题
解决.NET Core Ajax请求后台传送参数过大请求失败问题
|
10月前
|
开发框架 前端开发 JavaScript
ASP .Net Core 中间件的使用(一):搭建静态文件服务器/访问指定文件
ASP .Net Core 中间件的使用(一):搭建静态文件服务器/访问指定文件
|
11月前
|
开发框架 前端开发 JavaScript
【Asp.net】 Ajax小例子
【Asp.net】 Ajax小例子
69 0
|
前端开发 .NET Linux
|
前端开发 .NET Linux
【翻译】Asp.net Core介绍
ASP.NET Core is a significant redesign of ASP.NET. This topic introduces the new concepts in ASP.NET Core and explains how they help you develop modern web apps. Asp.net Core是重新设计过得新一代Asp.Net。
1155 0
|
4月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
46 0