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 write a custom authentication implementation in .net Core

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

Share

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

Today, I will talk to you about how to write a custom authentication implementation in .net Core, which may not be well understood by many people. 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.

I. cause

Recently, the project needs to support both JWT authentication and custom authentication verification. Through the understanding of the official documents, the authentication implementation is mainly achieved by inheriting IAuthenticationHandler or AuthenticationHandler to achieve custom authentication processing.

Then implement a custom authentication access.

Second, custom authentication implementation

1. According to the previous content, authentication is handled by IAuthenticationHandler instance. First, add a custom IAuthenticationHandler type:

/ method 1: custom authentication processor / public class CustomerAuthenticationHandler: IAuthenticationHandler {private IUserService _ userService; public CustomerAuthenticationHandler (IUserService userService) {_ userService = userService;} / public const string CustomerSchemeName = "cusAuth"; private AuthenticationScheme _ scheme; private HttpContext _ context / Authentication logic: authentication verification main logic / public Task AuthenticateAsync () {AuthenticateResult result; _ context.Request.Headers.TryGetValue ("Authorization", out StringValues values); string valStr = values.ToString () If (! string.IsNullOrWhiteSpace (valStr)) {/ / Authentication simulated basic authentication: cusAuth YWRtaW46YWRtaW4= string [] authVal = System.Text.Encoding.UTF8.GetString (Convert.FromBase64String (valStr.Substring (CustomerSchemeName.Length + 1) .Split (':'); var loginInfo = new Dto.LoginDto () {Username = authVal [0], Password = authVal [1]}; var validVale = _ userService.IsValid (loginInfo) If (! validVale) result = AuthenticateResult.Fail ("not logged in"); else {var ticket = GetAuthTicket (loginInfo.Username, "admin"); result = AuthenticateResult.Success (ticket);}} else {result = AuthenticateResult.Fail ("not logged in") } return Task.FromResult (result);} / public Task ChallengeAsync (AuthenticationProperties properties) {_ context.Response.StatusCode = (int) HttpStatusCode.Unauthorized; return Task.CompletedTask Deal with / public Task ForbidAsync (AuthenticationProperties properties) {_ context.Response.StatusCode = (int) HttpStatusCode.Forbidden; return Task.CompletedTask when insufficient permissions are available } / initialize authentication / public Task InitializeAsync (AuthenticationScheme scheme, HttpContext context) {_ scheme = scheme; _ context = context; return Task.CompletedTask } # region authentication verification logic / private AuthenticationTicket GetAuthTicket (string name, string role) {var claimsIdentity = new ClaimsIdentity (new Claim [] {new Claim (ClaimTypes.Name, name), new Claim (ClaimTypes.Role, role),}, CustomerSchemeName) Var principal = new ClaimsPrincipal (claimsIdentity); return new AuthenticationTicket (principal, _ scheme.Name);} # endregion} / method 2: inheriting the implemented base class / public class SubAuthenticationHandler: AuthenticationHandler {public SubAuthenticationHandler (IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock): base (options, logger, encoder, clock) {} protected override Task HandleAuthenticateAsync () {throw new NotImplementedException ();}}

2. Enable custom authentication in Startup.cs:

Public void ConfigureServices (IServiceCollection services) {/ / other code services.AddAuthentication (o = > {x.DefaultAuthenticateScheme = CustomerAuthenticationHandler.CustomerSchemeName; x.DefaultChallengeScheme = CustomerAuthenticationHandler.CustomerSchemeName; o.AddScheme (CustomerAuthenticationHandler.CustomerSchemeName, CustomerAuthenticationHandler.CustomerSchemeName);}); / / other code} public void Configure (IApplicationBuilder app) {/ / other code app.UseRouting (); / / after UseRouting Add the following code app.UseAuthentication (); app.UseAuthorization (); / / other code app.UseEndpoints ()} before UseEndpoints

3. Add the authentication mark on the controller, test and verify

/ / when specifying authentication, use customer Authentication Handler.CustomerSchemeName [authorize (AuthenticationSchemes = CustomerAuthenticationHandler.CustomerSchemeName)] [Route ("api/ [controller]")] [ApiController] public class AuditLogController: ControllerBase {/ / code}

Call

III. Multi-certification support

May exist in the actual project, for a controller to support a variety of authentication methods, such as: common Jwt authentication, custom authentication, etc., so how to achieve it?

1. Add the following logic to the ConfigureServices method of Startup:

Public void ConfigureServices (IServiceCollection services) {/ / other code services.Configure (Configuration.GetSection ("JWTSetting")); var token = Configuration.GetSection ("JWTSetting"). Get (); / / JWT authentication services.AddAuthentication (x = > {x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; / / add custom authentication processor x.AddScheme (CustomerAuthenticationHandler.CustomerSchemeName, CustomerAuthenticationHandler.CustomerSchemeName) ) .AddJwtBearer (x = > {x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters {ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey (Encoding.ASCII.GetBytes (token.SecretKey)), ValidIssuer = token.Issuer, ValidAudience = token.Audience, ValidateIssuer = false, ValidateAudience = false} }); / / other code}

2. Add tags to the controllers that need to support multiple authentication methods:

/ / when specifying authentication, use customer Authentication Handler.CustomerSchemeName [authorization (AuthenticationSchemes = CustomerAuthenticationHandler.CustomerSchemeName)] [Route ("api/ [controller]")] [ApiController] public class AuditLogController: ControllerBase {/ / code} / / specify authentication using JWT [Authorize (AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class WeatherForecastController: ControllerBase {/ / code}

This supports two authentication methods.

3. A controller supports multiple authentication types: inherit the Jwt authentication process and call the custom authentication processor according to Scheme:

/ method 2: multiple authentication methods are supported simultaneously / public class MultAuthenticationHandler: JwtBearerHandler {public const string MultAuthName = "MultAuth"; IUserService _ userService; public MultAuthenticationHandler (IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IUserService userService): base (options, logger, encoder, clock) {_ userService = userService;} protected override Task HandleAuthenticateAsync () {Context.Request.Headers.TryGetValue ("Authorization", out StringValues values) String valStr = values.ToString (); if (valStr.StartsWith (CustomerAuthenticationHandler.CustomerSchemeName)) {var result = Valid (); if (result! = null) return Task.FromResult (AuthenticateResult.Success (result)); else return Task.FromResult (AuthenticateResult.Fail ("uncertified")) } else return base.AuthenticateAsync ();} private AuthenticationTicket Valid () {Context.Request.Headers.TryGetValue ("Authorization", out StringValues values); string valStr = values.ToString () If (! string.IsNullOrWhiteSpace (valStr)) {/ / Authentication simulated basic authentication: cusAuth YWRtaW46YWRtaW4= string [] authVal = System.Text.Encoding.UTF8.GetString (Convert.FromBase64String (valStr.Substring (CustomerAuthenticationHandler.CustomerSchemeName.Length + 1) .Split (':'); var loginInfo = new Dto.LoginDto () {Username = authVal [0], Password = authVal [1]} If (_ userService.IsValid (loginInfo)) return GetAuthTicket (loginInfo.Username, "admin");} return null } / private AuthenticationTicket GetAuthTicket (string name, string role) {var claimsIdentity = new ClaimsIdentity (new Claim [] {new Claim (ClaimTypes.Name, name), new Claim (ClaimTypes.Role, role),}, CustomerAuthenticationHandler.CustomerSchemeName) Var principal = new ClaimsPrincipal (claimsIdentity); return new AuthenticationTicket (principal, CustomerAuthenticationHandler.CustomerSchemeName);}}

The custom authentication in .net Core is mainly realized through the implementation of IAuthenticationHandler interface. If you want to achieve multiple authentication, you can use the custom authentication processor implemented by AddScheme.

After reading the above, do you have any further understanding of how to write a custom authentication implementation in .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

Development

Wechat

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

12
Report