In depth interpretation ASP.NET Implementation of core authentication process

Time:2021-1-7

To make a long story short: we talked about it above ASP.NET What is core declaration based access control?
Today, let’s take advantage of the victory: let’s have a chat ASP.NET Authentication in the core.

Authentication is the process of determining the identity of a user. Authorization is the process of determining whether a user has access to a resource.

1. All changes are inseparable from the origin

Obviously, a conventional authentication use case consists of two parts
① User authentication
② React when an unauthorized user attempts to access a restricted resource

The registered authentication handler and its configuration options are called “schemes”, which can be used as a mechanism for users to refer to the authentication, challenge and forbidden behaviors of related handlers.

We often say:
Based on the cookie authentication scheme, if the authentication is successful, go on; if the authentication fails, jump back to the login page;
Based on basic identity authentication (BA) scheme, if the authentication is successful, go on; if the authentication is failed, return the WWW authenticate header to the browser, and the browser will pop up the authentication window again.

Two ASP.NET Core authentication principle

In ASP.NET In the core, the iauthentication service is responsible for the authentication. The authentication service will call the registered authentication handler to complete the authentication related operations. The whole authentication process is concatenated by the authentication middleware.

There are several key steps

1. Authentication handler
The authentication handler can be written in combination with the configuration item authentication scheme options in scheme.

The cookie based authentication scheme can specify the login address in options,
In the authentication scheme based on basic identity, user name / password can be specified in options;

2. The authenticator inherits from the authenticationhandler class or the iauthenticationhandler interface.

The core authentication function can be based on declarative access control to generate the authenticationticket object bound with claims principal and scheme. Regardless of authentication success or failure, the function returns the authenticateresult object.

Challenge (response to unauthorized users): for example, returning to the login page

Disallow (response to authenticated but not authorized access to a specific resource): for example, return a prompt string

The above is the service registration process

After receiving the request, the authentication middleware uses the iauthentication service to authenticate the httpcontext according to the required scheme. In fact, the authentication handler written in step 2 will be called internally.

Before the above authentication principle, there was a close combat: ASP.NET Core implements basic authentication.
The source code is as follows:https://www.jb51.net/article/196974.htm

Three ASP.NET The core gets the current user

For claim based access control, we will HttpContext.User Property to store identity information.


 var claims = new[] {
        new Claim(ClaimTypes.NameIdentifier,username),
        new Claim(ClaimTypes.Name,username),
      };
 var identity = new ClaimsIdentity(claims, Scheme.Name);
 var principal = new ClaimsPrincipal(identity);
 Context.User = principal;

There are two code situations to obtain the current login user in the web application

3.1 get the current login user in the controller

The controller is a first-class citizen who handles requests and is born with httpcontext.
Get the user object directly through the httpcontext attribute contained in the controllerbase base class.

In fact, razor page, razor view and middleware all contain httpcontext attributes / parameters, which can be used directly.

3.2 get the current login user in the service

At this time, the service is a part of request processing, and there is no directly available httpcontext.
ASP.NET The core provides the ihttpcontextaccessor class to inject the httpcontext object in this request (relying on the role of the injection framework).

//The following user entity class needs to obtain the current login user and inject httpcontext with the help of ihttpcontextaccessor
public class UserEntityService : IUserEntityService
{
  private IHttpContextAccessor _accessor;
  private readonly IMongoCollection<UserProfile> _users;

  public UserEntityService(IHttpContextAccessor accessor, IDefaultMongoDatabaseProvider databaseProvider)
  {
    _accessor = accessor;
    _users = databaseProvider.GetCollection<UserProfile>(CollectionNames.UserProfiles);
  }

  public Task<UserProfile> GetCurrentUserAsync()
  {
    var rawUser = this._accessor.HttpContext.User();
    if (rawUser == null)
    {
     return null;
    }
    var filter = Builders<UserProfile>.Filter.Eq("UserId", rawUser.UserId);
   return _users.Find(filter).FirstOrDefaultAsync();
  }
}

We don’t need to distinguish the above code occasions, and use the icurrentuser interface in the controller or application service to get the login user.

Narrator

In my opinion, ASP.NET The source code of core identity authentication is refined based on real cognition, which makes us marvel at the simplicity and clear hierarchy of the framework code.

Claim based access control has become a standard, ASP.NET Core / ABP vNext provides perfect support.

This article is about in-depth interpretation ASP.NET This is the article about the implementation of the core authentication process, and more about it ASP.NET Core authentication content please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!