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 authenticate .NET CORE

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article focuses on "how to authenticate .NET CORE". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to authenticate .NET CORE.

Basic information 1. What is authentication authorization?

Authentication is to verify whether the user has the right to access the system, and authorization is to determine whether the user has the authority to do some other operations.

two。 Traditional Session and Cookie

It is mainly used for user identification under stateless requests, but Session stores the information on the server and Cookie stores the information on the client.

Session

When the client accesses for the first time, the server generates a Session id to return to the client

The client stores the Session id locally with this id for every subsequent request

The server identifies the client in its own stored information according to the Session id from the received request

Cookie

When the client accesses the server, the server issues a Cookie in the response

The client stores the cookie and submits the cookie and the request when revisiting the server

The server will check the cookie to identify the client, and can also modify the content of the cookie as needed

3. Existing problems

Using Session in distributed or clustered systems

Suppose that now the server has distributed and clustered the system for better hosting and disaster recovery, that is, with N servers, does each server have to have the ability to identify the Session or Cookie of each client?

This can be used to identify Session using Session sharing, but it does not solve the problem that still exists in distributed systems, because usually each distributed system is handled by different people or across networks, or even by different companies. It is impossible to share all of them with session, right? At this time, a new way was born, using Token.

4.Token

Token is a string generated by the server as a token for the client to request.

Execution steps

The user initiates the verification of user name and password to the unified authentication authorization system.

After the verification is passed, a Token will be issued, and the user will take the issued Token to visit other three-party systems.

The tripartite system can directly request the authentication authorization system to verify the validity of the current Token, or it can use the secret key to decrypt the Token according to the symmetric encryption to verify the validity.

Authentication in .NET Core

Authentication: authenticate identity information, such as whether the user is logged in or not, and the user's basic information

Authorization: determine whether a user has permissions or not

Basic concept of 1.NET Core Authentication Authorization

Authentication authorization in NETCORE is accomplished through the extension method of HttpContext implemented in the AuthenticationHttpContextExtensions extension class.

Public static class AuthenticationHttpContextExtensions {public static Task SignInAsync (this HttpContext context, string scheme, ClaimsPrincipal principal, AuthenticationProperties properties) {context.RequestServices.GetRequiredService () .SignInAsync (context, scheme, principal, properties);}}

Its real core is

Microsoft.AspNetCore.Authorization module, the whole process mainly consists of the following key classes

IAuthenticationHandlerProvider

Responsible for the verification of user credentials. Provide IAuthenticationHandler processor to IAuthenticationService to handle authentication request. Of course, you can customize the processor.

IAuthenticationSchemeProvider

Choose which authentication method is used for identification.

IAuthenticationService

Five core business interfaces that provide unified authentication

Public interface IAuthenticationService {/ / query authentication Task AuthenticateAsync (HttpContext context, string scheme); / / log in to write authentication credentials Task SignInAsync (HttpContext context, string scheme, ClaimsPrincipal principal, AuthenticationProperties properties); / / log out of login cleanup credentials Task SignOutAsync (HttpContext context, string scheme, AuthenticationProperties properties); Task ChallengeAsync (HttpContext context, string scheme, AuthenticationProperties properties); Task ForbidAsync (HttpContext context, string scheme, AuthenticationProperties properties);}

The SignInAsync method in its implementation class AuthenticationService

Cooperate with IAuthenticationHandlerProvider and IAuthenticationSchemeProvider to get an IAuthenticationHandler, which eventually completes the authentication writing and reading.

Public virtual async Task SignInAsync (HttpContext context, string scheme, ClaimsPrincipal principal, AuthenticationProperties properties) {if (scheme = = null) {/ / IAuthenticationSchemeProvider instance var defaultScheme = await Schemes.GetDefaultSignInSchemeAsync (); scheme = defaultScheme?.Name;} / / IAuthenticationHandlerProvider instance acquisition processor var handler = await Handlers.GetHandlerAsync (context, scheme); var signInHandler = handler as IAuthenticationSignInHandler / / respective processors handler / / for example, using Cookie will inject a CookieAuthenticationHandler / / using JWT will inject a JwtBearerHandler await signInHandler.SignInAsync (principal, properties);} 2. Use Cookie default process authentication

Use middleware to join the pipeline to find authentication HttpContext.AuthenticateAsync ()

/ / the core source code is AuthenticationMiddleware middleware app.UseAuthentication ()

Injecting the container with CookieAuthenticationHandler as the processing logic

Services.AddAuthentication (options = > {/ / CookieAuthenticationDefaults.AuthenticationScheme = = "Cookies" options.DefaultAuthenticateScheme = "Cookies"; options.DefaultSignInScheme = "Cookies";}) .AddCookie ()

Write credentials when logging in

Claims: an item of information, for example, the name of the ID card is a Claims, and the ID number is also a Claims

ClaimsIdentity: a set of Claims information, which is a user's identity information.

ClaimsPrincipal: a user has multiple identities

AuthenticationTicket: user ticket for wrapping ClaimsPrincipal

[AllowAnonymous] public async Task Login (string name, string password) {if (name = "Admin" & & passwordkeeper = "000000") {var result = new JsonResult (new {Result = false,Message = "login failure"}); return result;} / / Claims login ClaimsIdentity failure ClaimsPrincipal var claimIdentity = new ClaimsIdentity ("ClaimsIdentity"); claimIdentity.AddClaim (new Claim (ClaimTypes.Name, name)) ClaimIdentity.AddClaim (new Claim (ClaimTypes.Address, "address information"); AuthenticationProperties ap = new AuthenticationProperties (); ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal (claimIdentity); await base.HttpContext.SignInAsync ("Cookies", claimsPrincipal, ap) return new JsonResult (new {Result = false,Message = "login successful"});}

Mark the [Authorize] feature on other controllers, automatically authenticate in the provider framework and write identity information to the context

[AllowAnonymous]: anonymous and accessible

[Authorize]: you must log in to access

3. Custom IAuthenticationHandler

Implement three interfaces: IAuthenticationHandler, IAuthenticationSignInHandler and IAuthenticationSignOutHandler

Public class CoreAuthorizationHandler: IAuthenticationHandler,IAuthenticationSignInHandler, IAuthenticationSignOutHandler {public AuthenticationScheme Scheme {get; private set;} protected HttpContext Context {get; private set;} public Task InitializeAsync (AuthenticationScheme scheme, HttpContext context) {Scheme = scheme; Context = context; return Task.CompletedTask;} public async Task AuthenticateAsync () {var cookie = Context.Request.Cookies ["CustomCookie"] If (string.IsNullOrEmpty (cookie)) {return AuthenticateResult.NoResult ();} AuthenticateResult result = AuthenticateResult .success (Deserialize (cookie)); return await Task.FromResult (result);} public Task ChallengeAsync (AuthenticationProperties properties) {return Task.CompletedTask;} public Task ForbidAsync (AuthenticationProperties properties) {Context.Response.StatusCode = 403 Return Task.CompletedTask;} public Task SignInAsync (ClaimsPrincipal user, AuthenticationProperties properties) {var ticket = new AuthenticationTicket (user, properties, Scheme.Name); Context.Response.Cookies.Append ("CoreAuthorizationHandlerCookies", Serialize (ticket)); return Task.CompletedTask;} public Task SignOutAsync (AuthenticationProperties properties) {Context.Response.Cookies.Delete ("CoreAuthorizationHandlerCookies") Return Task.CompletedTask;} private AuthenticationTicket Deserialize (string content) {byte [] byteTicket = System.Text.Encoding.Default.GetBytes (content); return TicketSerializer.Default.Deserialize (byteTicket);} private string Serialize (AuthenticationTicket ticket) {/ / need to introduce Microsoft.AspNetCore.Authentication byte [] byteTicket = TicketSerializer.Default.Serialize (ticket); return Encoding.Default.GetString (byteTicket) }}

Register a custom Handler in the container

Services.AddAuthenticationCore (options = > {options.AddScheme ("AuthenticationScheme", "AuthenticationScheme");}). Now that you have a better understanding of "how to authenticate .NET CORE", you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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

Development

Wechat

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

12
Report