Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report