Introduction to ASP. NET Core Identity (2), asp. netidentity
Preface
In the previous article, I talked about the words and corresponding knowledge points about Identity, and learned that Identity is in the entire logon process. authentication is an important part of the Authentication system. Authentication is not applicable to Identity Authentication.
In fact, Identity is also a specific use of the Authentication system, you must regard Authentication and Identity as two things, once confused, you will easily fall.
The following describes how the Authentication System in ASP. NET Core is like. Don't be afraid. It's actually very simple. It's all dry ~
Getting Started
Everyone should remember Mr. Obama in the previous article. He does not live in Washington anymore. He has traveled to China and now lives in Beijing. I have heard that the West Lake has a good scenery over the past few days, therefore, a high-speed rail ticket from Beijing to Hangzhou was set at 12306. After obtaining the ticket, he showed us:
Today is 11.11. Obama is very happy, because you know. As the departure time was approaching, I took the ticket to the railway station gate and handed my ID card and train ticket to the ticket Examiner. "Cut", the director shouted. Nima used to make movies ~
The director said: Obama, you are playing a bad job. Don't do it. Come and run the ticket reviewer. Let Lee next to Obama to show the route. Obama reluctantly said, "well, I hope Mr. Lee can accept you ".
"Action", the director shouted again, and the story began ~
AuthenticationManager
Obama was very happy when he became a vote clerk. Because he has the right, he can control whether others can get on the bus. Maybe he can secretly put a few people in the house to get out of the bus.
After learning what he could do, he thought the name of the ticket reviewer was too low. Soon, he had a new tall name named AuthenticationManager ), moreover, he thinks he should be at the core. Why? You can think about whether such a huge railway manned system can generate a profitable income. It relies entirely on him for not letting people in. If not, in addition, a large group of people can only go to the northwest wind.
By now, smart people may already know what kind of core position Obama puts himself in. Yes, he put himself in HttpContext. How is it? Core enough.
The first knowledge point is the location of AuthenticationManager.
Some people found the public abstract ClaimsPrincipal User {get; set;} in the above. This is not the "credential client" we mentioned in the previous article. What role does Xiao Li assume now? Yes, this User is Xiao Li in this article, and you will find him hiding from this place in advance, hey.
Another knowledge point is AuthenticationScheme. What does it mean? See
Obama dared to put himself at such a core position and also had his ability. What should he do? For example, if someone else handed over an ID card and a train ticket while checking the ticket, how can we verify that these two documents are valid? The following is a verification plan proposed by Obama for two types of certificates:
Solution 1: for ID card verification, you can check whether the person is consistent with the ID card profile, and whether the age meets the specific age of the person.
Solution 2: for the verification of train tickets, you can check the number of trains, whether the time meets the departure target, and whether the identity number on the ticket is consistent with the ID card.
Among them, each scheme corresponds to an AuthenticationScheme (verification scheme name), do you understand.
This is the second knowledge point. AuthenticationScheme is very important.
After knowing Obama's responsibilities, it is easy to write the code:
public abstract class AuthenticationManager
{
// AuthenticateContext contains the context that needs to be authenticated, there is Xiaoli in it
public abstract Task AuthenticateAsync (AuthenticateContext context);
// Handshake
public abstract Task ChallengeAsync (string authenticationScheme, AuthenticationProperties properties, ChallengeBehavior behavior);
//Sign in
public abstract Task SignInAsync (string authenticationScheme, ClaimsPrincipal principal, AuthenticationProperties properties);
//Sign out
public abstract Task SignOutAsync (string authenticationScheme, AuthenticationProperties properties);
}
As a ticket reviewer, Obama has an authentication method, AuthenticateAsync (). Note that this is a core function. Other functions can be used but cannot be used, if not, he cannot be called a ticket reviewer.
Then there is another handshake ChallengeAsync, logging in to SignInAsync and logging out SignOutAsync. Let's talk about the author's understanding of these three methods.
ChallengeAsync: A handshake process defined in RFC2167 in the Community protocol file, mainly digest Authentication ).
Is it a little professional? You can't understand it. It's okay. There's a popular version. Mr. Lee is about to enter the station. At this time, Mr. Obama asked our ticket reviewer.
- Xiao Li: "Hello, ticket reviewer. Can I enter the station ?"
- Vote clerk OBAMA: "Do you want to catch a train? Yes, please show me your ID card ?"
- Xiao Li: "Okay, this is my ID card. Check it ?"
- Vote clerk OBAMA: "Well, there is no problem with the credential. Please go in"
This process is a process of shaking (digest-challenge) or Q & A. Have you understood the principle of ChallengeAsync? Is it easy.
SignInAsync and SignOutAsync: I personally think these two should not be put here, because they do not belong to the authentication responsibility or the content specified in the agreement. However, the two methods do need to be abstracted and an interface should be extracted for storage. The reason for this may be:
1. the abstraction of login and logout is closely integrated with authentication. In most cases, the storage of authentication materials must be performed in SignIn, for example, the Cookie Authentication middleware saves the Cookie in the SignIn method.
2. The AuthenticationManager object is in HttpContext
It is appropriate to put the content in the context based on the principles of abstraction and encapsulation, so that users can conveniently call it.
I have already finished introducing AuthenticationManager. Is it easy?
IAuthenticationHandler
Some may ask, if AuthenticationManager does not provide an interface and is only an abstract class, it is unfriendly for developers to inherit the custom authentication method, it also violates the idea of interface-oriented programming. Well, this is indeed the case, so the interface comes:
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 authultauthenticationmanager implementation class of AuthenticationManager, so you don't have to look at the source code. Remember to rewrite Authentication-related items in the future to implement IAuthenticationHandler.
Authentication Middleware
The initial implementation of IAuthenticationHandler encapsulates the abstract class AuthenticationHandler and delivers the specific core functions to the downstream for implementation. The following CookieAuthentication middleware core class CookieAuthenticationHandler inherits from AuthenticationHandler, knowing so much is enough.
CookieAuthentication Middleware
The story will continue. After receiving the ID card and train ticket handed by Mr. Li, Mr. Obama scanned the train ticket on a QR code machine and then brushed it on a machine with his ID card, after verification, no problems were found. So I picked up the seal and covered it with an "acceptance ".
What happened in the middle?
First, in the QR code scanning process, the QR code machine will parse the QR code on your train ticket. If the parsing fails, the machine will directly respond to the authentication failure. That is, you should not enter the station.
If the resolution is successful, you will get the information in your ticket, and then you will get the information of the Parties in your ticket to verify whether it is listed as a blacklist of the Railway Bureau.
If the verification is successful, an identification code will be issued to you to write the identification code that meets your identity into the computer system next to your train ticket and the ticket reviewer, that is, "acceptance ".
This is a bit advanced. It will write some information into your train ticket chip. What information will be written into it? 1. Obama's personal information. 2. Some upstream and downstream information during verification. 3. verification scheme used.
After that, we can easily implement this verification method, right? The following is the core method HandleAuthenticateAsync () in CookieAuthenticationHandler, the core class of CookieAuthenticationHandler middleware. You can also understand it as the AuthenticateAsync of the IAuthenticationHandler interface:
protected override async Task <AuthenticateResult> HandleAuthenticateAsync ()
{
// Parse the QR code
var result = await EnsureCookieTicket ();
if (! result.Succeeded)
{
return result;
}
// Take the party information from the QR code for verification
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);
}
// check the chip, write to the chip
return AuthenticateResult.Success (new AuthenticationTicket (context.Principal, context.Properties, Options.AuthenticationScheme));
}
HandleSignInAsync
Our story continues ......
After Obama checked the ticket, he handed the ticket to Xiao Li. After Mr. Li received the ticket, the director shouted: "cut "......
Why did he stop again? James and Obama are confused. The director said, "Obama, you did a good job as a vote clerk. Let's continue playing your role, I have prepared a lunch box for you. Xiao Li, let's show you the ticket reviewer ".
You can have two lunch boxes. Obama is very happy after hearing this.
The "action" director shouted ......
Obama took the pass and walked toward the parking place of the train in the station. When he arrived at the door of the train, another person appeared. Obama knew, this person registers the passengers in the vehicle (ps: Generally, the passengers are registered during the train. Here we assume that the person who registers the passengers is diligent, in front of the car door). After the registration is complete, let Obama in.
So what have you done in the registration process?
First, the Register's handheld device will parse the information written into the chip in the train ticket. If no problem is found, it will start to register information with the registration book in his hand, mainly including the ticket Owner information, expiration time, reviewer.
In this way, the whole process is HandleSignInAsync. The program term is to assemble the Cookie login context information, write it into the Http stream header, and write it into the client browser cookie.
Now, the entire process is complete. Let's take a look at the Code:
// The process in the method, I only listed the core parts, all of which affect reading
protected override async Task HandleSignInAsync (SignInContext signin)
{
// Parse the information in the chip
var result = await EnsureCookieTicket ();
// Organize login context, set expiration time, etc.
// Use data protected to encrypt the information on the register
var cookieValue = Options.TicketDataFormat.Protect (ticket);
// write to browser header
await ApplyHeaders (cookieValue);
}
If you do not want to know more, you can ignore this part of content:
In the source code of the HandleSignInAsync function, there is a clever design: await Options. Events. SignedIn (signedInContext); what is the use of such a code? Besides, the call was performed twice. Do you know why? I am going to give the answer in the next article.
Do you still remember ClaimsPrincipal User in the previous HttpContext? This is the role temporarily replaced by Mr. Li. Now it's worth it. He's Obama.
After sitting in the seat, Obama traveled six hours from Beijing to Hangzhou and had to admire the speed of China's high-speed trains. After enjoying the scenery of the late West Lake, obama sent us a picture:
So far, the entire workflow of CookieAuthentication middleware has been completed, and the story is over.
The above is the story behind the two lines of code:
var user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "奥巴马") }, CookieAuthenticationDefaults.AuthenticationScheme));
await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user);
Summary
In this article, we know the AuthenticationManager, IAuthenticationHandler, and briefly introduce the Authentication middleware and CookieAuthentication middleware. The CookieAuthentication middleware is one of the most widely used middleware in the future, this article also gives a detailed introduction to it. I think this article will not solve the problem in the future.
Some may ask, what is the relationship between so many authentication items and Identity? Didn't you see the entire article hiding the relationship between him and Identity ?.... Really want to know? Let's take a look at the next article.