asp. net How to use cookie authentication in core

  • 2021-11-29 06:38:09
  • OfStack

Background

ASP. NET Core Identity is a full-featured authentication provider for creating and maintaining login names. However, cookie cannot use the based authentication provider ASP. NET Core Identity.

Configure

In the Startup. ConfigureServices method, create an authentication middleware service with AddAuthentication and AddCookie methods:


services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();

app.UseAuthentication();

AuthenticationScheme to AddAuthentication sets the default authentication scheme for the application. AuthenticationScheme is useful if you have multiple cookie authentication instances and you want to use a specific scheme for authorization. Set AuthenticationScheme to CookieAuthenticationDefaults. AuthenticationScheme provides the value "cookie" for the scenario. You can provide any string value that distinguishes scenarios.

The authentication scheme applied is different from the cookie authentication scheme applied. If cookie authentication scheme is not provided to AddCookie, CookieAuthenticationDefaults. AuthenticationScheme ("Cookie") is used.

By default, the IsEssential property of the authentication cookie is set to true. Authentication cookie is allowed when site visitors do not agree with data collection.

Login

To create an cookie that holds user information, construct an ClaimsPrincipal. The user information is serialized and stored in cookie.

Create an ClaimsIdentity with any required Claim and call SignInAsync to log in to the user:


 /// <summary>
 ///
 /// </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 = " Data validation failed " });
  }
  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 = " Login succeeded. ", returnUrl = RedirectToLocal(returnUrl) });
 }

SignInAsync creates an encrypted cookie and adds it to the current response. If AuthenticationScheme is not specified, the default scheme is used.

The data protection system of ASP. NET Core is used for encryption. For applications hosted on multiple computers, load balancing across applications, or using an web farm, configure data protection to use the same key ring and application identifier.

Logoff

To log off the current user and delete its cookie, call SignOutAsync:


 /// <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");
  }
 }

References

https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/?view=aspnetcore-5.0


Related articles: