Asp.net The sample code of realizing user-defined authentication in core

Time:2020-8-12

Asp.Net Although the core integrates many common identity authentication, many times, we still need to implement our own identity authentication interface. This article will briefly introduce how to implement the user-defined identity authentication interface.

First, write a simple interface.


[Authorize]
[HttpGet]
public object Foo()
{
  return DateTime.Now.ToString();
}

Due to the “authorize” flag, the user will be judged whether he has passed the authentication before accessing the function body. If the user is not authenticated, a 500 error will be obtained.

User defined authentication processing class:

Implement an iauthenticationhandler interface

public class MyAuthHandler : IAuthenticationHandler
  {
    public const string SchemeName = "MyAuth";

    AuthenticationScheme _scheme;
    HttpContext     _context;

    /// <summary>
    ///Initialize authentication
    /// </summary>
    public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
    {
      _scheme = scheme;
      _context = context;
      return Task.CompletedTask;
    }

    /// <summary>
    ///Authentication processing
    /// </summary>
    public Task<AuthenticateResult> AuthenticateAsync()
    {
      var req   = _context.Request.Query;
      var isLogin = req["isLogin"].FirstOrDefault();

      if (isLogin != "true")
      {
        return  Task.FromResult ( AuthenticateResult.Fail ("not logged in");
      }

      var ticket = GetAuthTicket("test", "test");
      return Task.FromResult(AuthenticateResult.Success(ticket));
    }

    AuthenticationTicket GetAuthTicket(string name, string role)
    {
      var claimsIdentity = new ClaimsIdentity(new Claim[]
      {
        new Claim(ClaimTypes.Name, name),
        new Claim(ClaimTypes.Role, role),
      }, "My_Auth");

      var principal = new ClaimsPrincipal(claimsIdentity);
      return new AuthenticationTicket(principal, _scheme.Name);
    }

    /// <summary>
    ///Handling of insufficient authority
    /// </summary>
    public Task ForbidAsync(AuthenticationProperties properties)
    {
      _context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
      return Task.CompletedTask;
    }

    /// <summary>
    ///Processing when not logged in
    /// </summary>
    public Task ChallengeAsync(AuthenticationProperties properties)
    {
      _context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
      return Task.CompletedTask;
    }
  }

The main function is authenticateasync, which mainly includes the following steps

The first is to judge whether the user has passed the authentication according to the HTTP context. Here, I implement it relatively simply. Judge whether the islogin in the querystring is true, and if it is true, it will pass the verification. If the authentication is passed, a claim principal object is generated, and the authentication success is returned

Claims principal object, which is the validation model of. Net core. ASP.NET Core’s verification model is claims based authentication. There are some articles on the Internet to introduce him to authentication with ASP.NET Core。 The significance of their representatives is as follows:

Claim is user information, such as user name, role, mail. Commonly used are user names and roles. In particular, roles are often used in authorization information. A group of claims constitutes an identity and a claim identity object, which can be understood as “certificate”. The driver’s license is a kind of certificate, and the passport is also a kind of certificate. Understanding records the basic information of users. The holder of claims identity is claims principal. A claim principal can hold multiple claims identities, for example, a person holds both a driver’s license and a passport.

After the certification is passed, it can also be passed HttpContext.User Property to get the user name, role, and so on

To register a custom authentication processing class:

stay startup.cs The configuration is as follows:

Enable authentication Middleware


app.UseAuthentication();
app.UseAuthorization();

configuration option


services.AddAuthentication(options =>
  {
    options.AddScheme<MyAuthHandler>(MyAuthHandler.SchemeName, "default scheme");
    options.DefaultAuthenticateScheme = MyAuthHandler.SchemeName;
    options.DefaultChallengeScheme  = MyAuthHandler.SchemeName;
  });

Test:

After the above functions are completed, the previous test is carried out, and the authentication information is accessed in the URL

You can see that the interface can be accessed successfully this time, indicating that the authentication information is in effect.

This is about Asp.net The article on the implementation of custom authentication sample code in the core is introduced here, more related Asp.net Core custom identity authentication content, please search the previous articles of developeppaer or continue to browse the related articles below. I hope you can support developeppaer more in the future!