当前位置:网站首页>[authentication / authorization] customize an authentication handler
[authentication / authorization] customize an authentication handler
2022-04-23 03:06:00 【Dotnet cross platform】
WeChat official account : Fun programming ACE
Focus on understanding .NET Daily development skills . For source code , Please leave a message for the official account [ Source code ];
Review above
【 authentication / to grant authorization 】 Step by step to achieve a simple JWT authenticationCustom authentication CustomerAuthenticationHandler Use
In the last article, I demonstrated how to use .net core The built-in verification scheme -Bearer Authentication , This article uses a simple example to realize the custom authentication process .
Super clear Watch ~
First create a login service
There are three steps
1//Step1: Login interface You need to inject dependency in the built-in container
2public interface ICustomerAuthentication
3{
4 ...
5}
6
7// An instance of an interface
8public class CustomerAuthentication : ICustomerAuthentication
9{
10 // Step2: Provide a login method
11 public string Login(string userName, string password)
12 {
13
14 }
15}
16
17// Step3: Container dependency injection
18builder.Services.AddSingleton<ICustomerAuthentication,CustomerAuthentication>();
Login interface implementation
1// It is equivalent to defining a set of user objects in memory Simulate getting user objects from database queries convenient check
2private readonly IDictionary<string,string> users = new Dictionary<string,string>
3{
4 {"p1","a1"},
5 {"p2","a2"},
6};
7// Deposit token aggregate
8private readonly IDictionary<string,string> tokens = new Dictionary<string,string>();
9public IDictionary<string,string> Tokens =>tokens; // Implementation interface And initialization
10
11public string Login(string userName, string password)
12{
13 // check The user really exists
14 if(!users.Any(u=>u.Key==userName && u.Value==password))
15 {
16 return null;
17 }
18 // create token Through one Guid Type of data instead of token Just for demonstration
19 var token = new Guid().ToString();
20 tokens.Add(token,userName);
21 return token ;
22}
Create a custom CustomerAuthenticationHandler class
1public class CustomerAuthenticationHandler :AuthenticationHandler<BasicAuthenticationOptions>
2{
3 ...
4}
among CustomerAuthenticationHandler Need to inherit AuthenticationHandler Interface , This interface requires a for authentication Options Configuration class , So you need to define BasicAuthenticationOptions Inherit AuthenticationSchemeOptions
1public class BasicAuthenticationOptions :AuthenticationSchemeOptions
2{
3
4}
Realization HandleAuthenticateAsync Method
1protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
2 {
3 // throw new NotImplementedException();
4 if(!Request.Headers.ContainsKey("Authorization"))
5 {
6 return AuthenticateResult.Fail("UnAuthorized");
7 }
8
9 // Get the request header Authorization Corresponding value
10 string authenticationHeader = Request.Headers["Authorization"];
11 if(string.IsNullOrEmpty(authenticationHeader))
12 {
13 return AuthenticateResult.Fail("UnAuthorized");
14 }
15 if(!authenticationHeader.StartsWith("Bearer",StringComparison.OrdinalIgnoreCase))
16 {
17 return AuthenticateResult.Fail("UnAuthorized");
18 }
19 // obtain token
20 string token = authenticationHeader.Substring("bearer".Length).Trim();
21 if(string.IsNullOrEmpty(token))
22 {
23 return AuthenticateResult.Fail("UnAuthorized");
24 }
25
26 try
27 {
28 // verification token Call the following ValidateToken() This method
29 return ValidateToken(token);
30 }
31 catch (System.Exception ex)
32 {
33 // Log
34 return AuthenticateResult.Fail("UnAuthorized");
35 }
36 }
37
38private AuthenticateResult ValidateToken(string token)
39 {
40 var validateToken = _customerAuthentication.Tokens.FirstOrDefault(t=>t.Key ==token);
41 if(validateToken.Key is null )
42 {
43 return AuthenticateResult.Fail("UnAuthorized");
44 }
45 var claims = new List<Claim>
46 {
47 new Claim(ClaimTypes.Name,validateToken.Value)
48 };
49
50 var identity = new ClaimsIdentity(claims,Scheme.Name);
51 var principle = new GenericPrincipal(identity,null);
52 var ticket = new AuthenticationTicket(principle,Scheme.Name);
53 return AuthenticateResult.Success(ticket);
54 }
This method returns a AuthenticateResult Type to indicate whether the authentication is successful , If it works , This bill needs to be returned to the user .
So why do you need bills ? Because we are Http Under the transmission protocol , You need to ensure the security of the content attached to the request header or request parameters , So we need to principal The object is wrapped in AuthenticationTicket object , In the latter, we can add some security configurations .
DI Registered certification services in
1// Custom validation Named a test Of Scheme programme
2builder.Services.AddAuthentication("test")
3 .AddScheme<BasicAuthenticationOptions,CustomerAuthenticationHandler>("test",null);
PS: This article is contributed by community fans ~
版权声明
本文为[Dotnet cross platform]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230301334072.html
边栏推荐
- Blazor University (11) component - replace attributes of subcomponents
- Xamarin效果第二十一篇之GIS中可扩展浮动操作按钮
- 如果通过 C# 实现对象的深复制 ?
- TP5 where query one field is not equal to multiple values
- Two methods are used to solve the "maximum palindrome product" problem
- Onenet connection process
- Source Generator实战
- 全网最全,接口自动化测试怎么做的?精通接口自动化测试详解
- It turns out that PID was born in the struggle between Lao wangtou and Lao sky
- Plug in for vscode
猜你喜欢
Passing object type parameters through openfeign
Blazor University (12)组件 — 组件生命周期
再战leetcode (290.单词规律)
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (8)
[new version release] componentone added Net 6 and blazor platform control support
Maui initial experience: Cool
AC & A2C & A3C
tf. keras. layers. Timedistributed function
Service avalanche effect
MYSQL03_ SQL overview, rules and specifications, basic select statements, display table structure
随机推荐
MYSQL05_ Ordr by sorting, limit grouping, group by grouping
Array and collection types passed by openfeign parameters
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (9)
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (8)
Guangcheng cloud service can fill in a daily report regularly every day
荐读 | 分享交易员的书单,向名家请教交易之道,交易精彩无比
[format] simple output (2)
If the deep replication of objects is realized through C #?
MYSQL03_ SQL overview, rules and specifications, basic select statements, display table structure
The difference between encodeuri and encodeuricomponent
TP5 inherits base and uses the variables in base
Close the computer port
Plug in for vscode
基于.NetCore开发博客项目 StarBlog - (2) 环境准备和创建项目
PDH optical transceiver 4-way E1 + 4-way 100M Ethernet 4-way 2m optical transceiver FC single fiber 20km rack type
How to count the number of all files in a directory under win10 system
全网讲的最细,软件测试度量,怎样优化软件测试成本提高效率---火爆
Judge whether there is a leap year in the given year
Service avalanche effect
FileNotFoundError: [Errno 2] No such file or directory