services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(); app.UseAuthentication();
AuthenticationScheme 传递到 AddAuthentication 设置应用程序的默认身份验证方案。如果有多个 cookie 身份验证实例,并且你想要使用特定方案进行授权,AuthenticationScheme 会很有用。将 AuthenticationScheme 设置为CookieAuthenticationDefaults。AuthenticationScheme为方案提供值 "cookie"。可以提供任何用于区分方案的字符串值。
应用的身份验证方案不同于应用的 cookie 身份验证方案。如果未向 AddCookie提供 cookie 身份验证方案,则使用 CookieAuthenticationDefaults.AuthenticationScheme ("Cookie")。
/// <summary> /// 堆代码 duidaima.com /// </summary> /// <param name="model"></param> /// <param name="returnUrl"></param> /// <returns></returns> [HttpPost] [AllowAttribute] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginModel model, string returnUrl = null) { if (!ModelState.IsValid) { return Json(new { state = "error", message = "数据验证失败" }); } string ip = GetRemoteIpAddress(); var r = await UserApp.SaasLoginAsync(model.Account, model.Password, ip); if (!string.IsNullOrEmpty(r.Error)) { return Json(new { state = "error", message = r.Error }); } var claims = new List<Claim> { new Claim(ClaimTypes.UserData, getCurrentUser(r.User, ip).ToString()), }; var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { ExpiresUtc = DateTimeOffset.Now.AddMinutes(120) }; await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); return Json(new { state = "success", message = "登录成功。", returnUrl = RedirectToLocal(returnUrl) }); }SignInAsync 创建加密的 cookie,并将其添加到当前响应中。如果未指定 AuthenticationScheme,则使用默认方案。
/// <summary> /// /// </summary> /// <returns></returns> [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LogOff() { if (bool.Parse(Configuration.GetSection("IsIdentity").Value)) { return SignOut("Cookies", "oidc"); } else { if (User.Identity.IsAuthenticated) { string userdata = User.Claims.FirstOrDefault(o => o.Type == ClaimTypes.UserData)?.Value; await UserApp.LogOffAsync(CurrentUser.FromJson(userdata)); } await HttpContext.SignOutAsync( CookieAuthenticationDefaults.AuthenticationScheme); return RedirectToAction(actionName: nameof(Login), controllerName: "Account"); } }