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

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

首先让asp.net core跨域,在nuget中添加Microsoft.AspNetCore.Cors的引用,然后在StartUp.cs中的ConfigureServices中添加如下代码:var urls = "http://localhost:5000/";

services.AddCors(options =>

options.AddPolicy("MyDomain",

builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));

再在Configure中添加app.UseCors("AllowSameDomain");再添加验证,添加Microsoft.AspNetCore.Authentication.Cookies引用

在Configure中添加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中添加允许跨域特性,然后再添验证特性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

{

/// 

/// 测试方法

/// 

/// 

/// 

[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());

}

/// 

/// 登录

/// 

/// 用户名

/// 密码

/// 

[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在后面的操作中带回服务端(关于原理不多说了)html>

$("#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);

}

});

})

来看一下测试结果:

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

a1ba3a19a6f6d1bdf98c4b36747c6b62.png

登录

89412f123845bfee26997549bfd37bf6.png

再次保存

6b128a43f3a7ee62e2e8e64cd9570ab6.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值