Cookie认证 配置
- 在Startup中的ConfigureServices方法中注册服务
public void ConfigureServices(IServiceCollection services) { //注册Cookie认证服务 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(option => { option.Cookie.Name = "MyCookie";//Cookie名称 ,默认:.AspNetCore.Cookies //option.LoginPath = "/Account/Login";//验证失败 跳转到 登录地址 ,默认:/Account/Login?ReturnUrl=xx }); }
- 在Startup中的Configure方法中
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //路由中间件 app.UseRouting(); //需要在UseAuthentication之后再次UseAuthorization 否则,当你使用授权功能比如使用[Authorize]属性的时候系统就会报错 app.UseAuthentication(); //认证鉴权,判断有没有登录,登录的是a用户还是b用户,配置中间件,让所有请求都要解析凭证 app.UseAuthorization(); //授权,判断a用户有没有权限访问这个资源,按[Authorization]标记 }
-
登录接口(AuthController)
/// <summary> /// 登录服务 /// </summary> [Route("api/[controller]/[action]")] [ApiController] public class AuthController : ControllerBase { /// <summary> /// 登录 /// </summary> /// <returns></returns> [HttpGet] public async Task<IActionResult> Login_CookieAsync(string loginName = "demo", string loginPassword = "123456") { if (loginName == "demo" && loginPassword == "123456") { //下面的变量claims是Claim类型的数组,Claim是string类型的键值对,所以claims数组中可以存储任意个和用户有关的信息, //不过要注意这些信息都是加密后存储在客户端浏览器cookie中的,所以最好不要存储太多特别敏感的信息,这里我们只存储了用户名到claims数组, //表示当前登录的用户是谁 var claims = new[] { new Claim("loginName", loginName), new Claim("loginPassword", loginPassword), }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); ClaimsPrincipal user = new ClaimsPrincipal(claimsIdentity); //登录用户,相当于ASP.NET中的FormsAuthentication.SetAuthCookie await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, user, new AuthenticationProperties() { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddSeconds(3600),//有效期 60分钟 AllowRefresh = true//是否延长有效期 (超过50%的ExpiresUtc时间间隔内 才会延长) }); return new JsonResult(new { code = 200, msg = "登录成功" }); } else { return new JsonResult(new { code = 0, msg = "登录失败" }); } } /// <summary> /// 获取-Cookie /// </summary> /// <returns></returns> [HttpGet] [Authorize] public IActionResult GetCookie() { //如果HttpContext.User.Identity.IsAuthenticated为true, //或者HttpContext.User.Claims.Count()大于0表示用户已经登录 if (HttpContext.User.Identity.IsAuthenticated) { //这里通过 HttpContext.User.Claims 可以将我们在Login这个Action中存储到cookie中的所有 var claims = HttpContext.User.Claims; Dictionary<string, string> dic = new Dictionary<string, string>(); foreach (var claim in claims) { dic.Add(claim.Type, claim.Value); } return new JsonResult(new { code = 200, msg = "登录成功", data = dic }); } else { return new JsonResult(new { code = 0, msg = "登录失败" }); } } /// <summary> /// 注销用户 /// </summary> /// <returns></returns> [HttpGet] public async Task<IActionResult> Logout_CookieAsync() { //注销登录的用户,相当于ASP.NET中的FormsAuthentication.SignOut await HttpContext.SignOutAsync(); return new JsonResult(new { code = 200, msg = "注销成功" }); } }