跨域須要服務端和客戶端都做處理。html
首先讓asp.net core跨域,在nuget中添加Microsoft.AspNetCore.Cors的引用,而後在StartUp.cs中的ConfigureServices中添加以下代碼:jquery
var urls = "http://localhost:5000/"; services.AddCors(options => options.AddPolicy("MyDomain", builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));
再在Configure中添加ajax
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中添加容許跨域特性,而後再添驗證特性json
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在後面的操做中帶回服務端(關於原理很少說了)
<!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>
來看一下測試結果:c#
當直接點保存時,系統會導航登陸跨域
登陸cookie
再次保存app