Objective
In the previous article, I spoke about the words that the identity needs to know and the corresponding points of knowledge, and know the location of the identity in the entire login process, this article is mainly in the. NET authentication system in a more important part, is the certification (authentication) , because you want to make the Identity clear, it is not around authentication.
Before writing an article about ASP. NET Core middleware, there is a part ( 怎么样自定义自己的中间件
) is specific about the authentication system of a specific use, interested friends can read this article.
In fact, identity is also a specific use of authentication system, we must be authentication and Identity as two things, once confused, you will easily into the.
Here's how the authentication system in ASP. Don't be afraid, actually very simple, all is dry goods ~
Getting Started
You should remember Mr. Obama in the previous article, he is not in Washington now, he came to China to travel, now live in Beijing, these days heard the West Lake scenery is good, so in 12306 set a Beijing to Hangzhou high-speed rail ticket. After taking the ticket, he showed us the following:
Today is number 11.11th, Obama is very happy, reason you understand. As soon as the departure time, so, took the ticket to the railway station wicket, just the ID card and train tickets to pass to the ticket inspector. "Cut", the director shouted. I was making a movie.
The director said: "Obama, you play too bad, do not play, you come to play the ticket clerk, let the next little disparities play on the road from the Obama." Obama reluctantly said: "Well, hope that Xiao Li can be affected by you."
"Action", the director shouted again, the story began ~
AuthenticationManager
After he became a ticket-inspector, he was particularly pleased because he had the right to control the ability of others to get on the bus, and perhaps secretly put a few people in for some extra money.
When he learned what he was capable of, he felt that the name of the ticket inspector was simply too low, and soon he had a new tall name called: the AuthenticationManager, and he felt that he should be in the core position, why? You think about it, then a large set of railway manned system, can have income to earn money, all rely on him to put people in, if a person do not put in, another big help people can only go to Hexibeifeng.
Here, the smart classmate may already know how Obama put himself in a central position. Yes, he put himself in the HttpContext. What do you think? Enough core.
This extends the first point of knowledge: where the AuthenticationManager is located
There are classmates in the above found public abstract ClaimsPrincipal User { get; set; }
, this is not our last article in the "Certificate of the parties" , now Xiao Li play that role? Yes, this User
is the small Lee in this article, you found him in advance to hide here, hey.
There is a point of knowledge, that is AuthenticationScheme
, what does it mean? And look at
How can Mr Obama, who dares to put himself in such a central position, have the power to speak? For example, in the ticket, when someone handed over an ID card and a train ticket, then how to verify that these two documents are legal? Here's what Barack Obama has to offer to validate two types of documents:
Program 1, for identification card verification, you can see whether it and ID card picture is consistent, age is consistent with the specific age of the parties.
Program 2, for the verification of train tickets, you can see the trips, whether the time is in line with the departure target, you can see the ticket on the identity number and identity card consistent.
Which, for each of these scenarios, corresponds to a AuthenticationScheme
(validation scheme name), is not understood.
This is the second point of knowledge authenticationscheme is very important.
Knowing Obama's responsibilities makes it easy to write out the code:
PublicAbstractClassauthenticationmanager{The authenticatecontext contains a context that requires authentication, and there's Little LeePublicAbstract TaskAuthenticateasync (Authenticatecontext context);Shake handsPublicabstract Task challengeasync (string authenticationscheme, authenticationproperties properties, challengebehavior behavior); //Log in public abstract Task signinasync (string Authenticationscheme, ClaimsPrincipal Principal, authenticationproperties properties); //logout public abstract Task signoutasync (string Authenticationscheme, Authenticationproperties properties);}
Obama as a ticket inspector, there is a certification method, AuthenticateAsync()
Note that this is a core function, the other can not, but only not without this function, if not, he can not be called a ticket inspector.
Then there is a handshake ChallengeAsync
, login and logout, the following talk about the author of the SignInAsync
SignOutAsync
three methods of understanding it.
Challengeasync: is a process of RFC2167 defined in the Community agreement file about the handshake in the HTTP authentication process, mainly Digest Authentication (Digest authentication), See here for more information.
is not a bit professional, can not understand, nothing, there is a popular version of. Xiao Li is going to the station, this time Xiao Li asked our ticket inspector Mr. Obama.
- Xiao Li : Hello, ticket inspector, may I pit? ”
- ticket Inspector Barack Obama : "Catching the train?" Yes, please show me your ID. ”
- Xiao Li : ok, this is my ID, do you have a look? ”
- Inspector Obama : "Well, the papers are fine, go inside."
Such a process is a handshake (digest-challenge) or a process called question and answer, understand the principle of challengeasync it? is not very simple.
Signinasync,signoutasync: Personally feel that these two should not be placed here, because it does not belong to the responsibility of certification, also does not belong to the provisions of the agreement content. But these two methods do need to be abstract, and should be extracted separately to store, as for why this, perhaps because of the following reasons:
1. The abstraction of login and logout is closely combined with the authentication, in most cases the preservation of the authentication data needs to be carried out in signin, for example, the cookie authentication middleware is stored in the Signin method.
2, AuthenticationManager This object is in HttpContext
Inside the context, the principle of abstraction and encapsulation is appropriate, so that the user can invoke it easily.
About AuthenticationManager has been introduced, is it very simple?
Iauthenticationhandler
Some students may ask, if AuthenticationManager does not provide an interface, it is only an abstract class, if the custom authentication method must inherit it, which is unfriendly to the developer, also violates the concept of interface-oriented programming. Well, that's true, then the interface comes in:
public interface iauthenticationhandler{void getdescriptions (describeschemescontext context); task authenticateasync ( Authenticatecontext context); task challengeasync ( Challengecontext context); task signinasync (SignInContext context); task signoutasync (SignOutContext (context)}
This interface is extended in the AuthenticationManager implementation class DefaultAuthenticationManager
, so you do not have to look at the source of the inside, remember that if you need to rewrite the authentication related things, the implementation IAuthenticationHandler
can be.
Authentication Middleware
The initial implementation of the Iauthenticationhandler, encapsulated the Authenticationhandler this abstract class, the specific core functions are handed down to the downstream to achieve, the following Cookieauthentication middleware core class Cookieauthenticationhandler is inherited from the Authenticationhandler, know so much is enough.
Cookieauthentication Middleware
The story will continue, Obama in the receipt of small Lee pass the ID card and train tickets, first took the train ticket in a two-dimensional code machine scanned, and then took the ID card in a machine brush, after verification, found that there is no problem. So he picked up a seal and covered it with a "examined".
What happened in the middle of all this?
First, in the QR code scanning process, the process of the two-dimensional code machine will parse the two-dimensional code on your train ticket, if the discovery fails to resolve, will directly respond to authentication failure. That means you don't want to get in the pit.
If the resolution is successful, you will get the information in your ticket, and then get the party information in your bill to verify whether it is listed as a railway company blacklist.
If the validation is passed, you will be issued an identification code to write an identification code that matches your identity to your train ticket and to the computer system next to the ticket inspector, "examined".
Say this examined is a bit advanced, it will write some information to your train ticket chip, then what information is written? 1. Personal information of Mr. Obama. 2, verify some of the upper and lower information on the way. 3, the use of the verification scheme.
You know, after that, it's easy to implement this verification method, right? The following is the core method of the core class Cookieauthenticationhandler in the Cookieauthentication middleware Handleauthenticateasync (), as you can understand the implementation of the Authenticateasync of the Iauthenticationhandler interface:
ProtectedOverrideAsync task<authenticateresult>Handleauthenticateasync (){Parsing two-dimensional codevar result =await Ensurecookieticket ();if (!result. Succeeded) {return result;} //to verify the party information from the QR code var context = New Cookievalidateprincipalcontext (Context, result. Ticket, Options); await Options.Events.ValidatePrincipal (context); if (context. Principal = = null) {return authenticateresult.fail ( "No principal"); if (context. Shouldrenew) {Requestrefresh (result. Ticket); } //examined, write chip return authenticateresult.success (new authenticationticket (context. Principal, context. Properties, Options.authenticationscheme));}
Handlesigninasync
Our story continues ...
After the Obama ticket was completed, the tickets were handed to Xiao Li, Xiao Li after the ticket, the director shouted again: "Cut" ...
How to stop, Xiao Li and Obama belly doubts, the director said: "Obama Ah, you are good at the ticket inspector, or continue to play your role, play good lunch for you double, Xiao Li, you come to play the ticket clerk."
Can eat two bento box, Obama after listening to the heart is very happy.
"Action" the director shouted ...
Obama took the ticket, toward the station inside the train parking, walked to the train door to go in, there was a person, Obama knew that this person is to do in the car passenger registration (PS: In general, to do the passenger registration is in the course of the train, here we assume that the passenger registration of people more diligent , just at the door of the car), and let Obama in after the registration is complete.
So, what did you do in the registration process?
First, the Registrar's handheld device will parse the train ticket to write the information in the chip, found no problem, began to their own hands inside the registration information, mainly including ticket owner information, expiration time, auditor and so on.
So the whole process is a process of handlesigninasync, in terms of the program is, the assembly cookie login context information, written to the header of the Http stream, also written to the client browser Cookie.
At this point, the whole process is over, let's take a look at the code:
//method inside the flow, I only listed the core part, affecting the reading of the whole delete protected override async Task Span class= "Hljs-title" >handlesigninasync (signincontext signin) { //parsing the information in the chip var result = await Ensurecookieticket (); //organization login context, set expiration time, etc. //use data protected encrypt the information on the register this var cookievalue = Options.TicketDataFormat.Protect (ticket); //written to the browser header await applyheaders (Cookievalue);}
You can ignore this part of the content if you don't want to know it:
In Handlesigninasync this function of the source code, which has a very clever design, is await Options.Events.SignedIn(signedInContext);
such a code, what is the use of it? And before and after altogether called two times, has the classmate know is why? I'm going to give an answer in the next article.
Remember the HttpContext in front of ClaimsPrincipal User
you? The role that Xiao Li temporarily replaced, now has the value, he is Obama.
After Obama sat in his seat, after a 6-hour journey from Beijing to Hangzhou, he had to admire the speed of China's high speed rail, after appreciating the scenery of the late West Lake, Obama sent us a picture:
So far, the whole workflow of Cookieauthentication middleware has been finished, and the story is over.
The above is the story behind these two lines of code:
var user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "奥巴马") }, CookieAuthenticationDefaults.AuthenticationScheme));await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user);
Summarize
In this article we know the AuthenticationManager, also know the Iauthenticationhandler and briefly introduced a bit authentication middleware and cookieauthentication middleware, One of the cookieauthentication middleware is our future use of the most middleware, this article also made a detailed introduction, I think through this article in the future use of the process should not be a problem.
Some students may ask, said so many certified things it and Identity have what relationship? Did I hide his relationship with the Identity of the entire article you didn't see? Do you really want to know? Let's take a look at the next article.
By the way to make an advertisement: Chengdu area has recommended work? Interested in contacting the upper right corner.
If you feel that this blog is helpful to you, thank you for your "recommendation", if you are interested in. NET core can follow me, I will regularly share on the blog about. NET core learning experience.
This address: http://www.cnblogs.com/savorboard/p/aspnetcore-identity2.html
Author Blog: Savorboard
An introduction to the Identity of ASP (ii)