asp.netcore跨域访问ajax的验证访问-创新互联
跨域需要服务端和客户端都作处理。
创新互联公司-专业网站定制、快速模板网站建设、高性价比和田县网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式和田县网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖和田县地区。费用合理售后完善,10余年实体公司更值得信赖。首先让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在后面的操作中带回服务端(关于原理不多说了)来看一下测试结果:
当直接点保存时,系统会导航登录

登录

再次保存

创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。
分享标题:asp.netcore跨域访问ajax的验证访问-创新互联
当前URL:http://www.jxjierui.cn/article/cocedi.html


咨询
建站咨询
