Get the App
SLTechnology News&Howtos  ›  Network Security  › 

How to use cookie to verify identity in Asp.net core

Shulou Source: shulou.com Published: 2022-06-01 00:35:34 09月28日 Update

Today, I will talk to you about how to use cookie to verify identity in Asp.net core. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

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

Configuration

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

Services.AddAuthentication (CookieAuthenticationDefaults.AuthenticationScheme). AddCookie (); app.UseAuthentication ()

AuthenticationScheme is passed to AddAuthentication to set 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 a value of "cookie" for the scheme. You can provide any string value used to distinguish between scenarios.

The applied authentication scheme is different from the applied cookie authentication scheme. If no cookie authentication scheme is 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 to data collection.

Log in

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

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

/ [HttpPost] [AllowAttribute] [ValidateAntiForgeryToken] public async Task 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 {new Claim (ClaimTypes.UserData, getCurrentUser (r.User, ip). ToString ()),} Var claimsIdentity = new ClaimsIdentity (claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties {ExpiresUtc = DateTimeOffset.Now.AddMinutes}; 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 no AuthenticationScheme is specified, the default scheme is used.

ASP.NET Core's data protection system is used for encryption. For applications hosted on multiple computers, load balancing across applications, or using web farms, configure data protection to use the same keyring and application identifiers.

Write off

To log out of the current user and delete their cookie, call SignOutAsync:

/ / [HttpPost] [ValidateAntiForgeryToken] public async Task 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");}}

After reading the above, do you have any further understanding of how to use cookie authentication in Asp.net core? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Tags: Authentication identity scheme program application application data user login content information method and will protection encryption configuration same success middleware function Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux macOS MariaDB Xiaomi Shulou Information