What exactly is 'UseAuthentication()' for?

后端 未结 3 2123
天命终不由人
天命终不由人 2020-12-29 18:37

I have a question regarding authentication in ASP.NET Core 2: what exactly is the call app.UseAuthentication() for?

Is it a basic prerequisite so t

3条回答
  •  攒了一身酷
    2020-12-29 19:25

    If you write your custom middleware (like you do in your example), you don't need to call AddAuthentication because the authentication middleware won't be aware of your own.

    That being said, you probably don't want to create your own middleware: you probably want to create a new authentication handler that plays nicely with the ASP.NET authentication framework (so that you use the [Authorize] attribute on controllers).

    To create a custom authentication, you have to create a dedicated handler that inherit from AuthenticationHandler, and implements the relevant methods. You can have a look at an example of basic authentication on github: https://github.com/blowdart/idunno.Authentication, but here's a quick example to show the gist of the custom handlers.

    public class BasicAuthenticationOptions : AuthenticationSchemeOptions
    {
        public BasicAuthenticationOptions()
        {
        }
    }
    
    internal class BasicAuthenticationHandler : AuthenticationHandler
    {
        private const string _Scheme = "MyScheme";
    
        public BasicAuthenticationHandler(
            IOptionsMonitor options,
            ILoggerFactory logger,
            UrlEncoder encoder,
            ISystemClock clock) : base(options, logger, encoder, clock)
        {
        }
    
        protected override async Task HandleAuthenticateAsync()
        {
            string authorizationHeader = Request.Headers["Custom-Auth-Handler"];
    
            // create a ClaimsPrincipal from your header
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, "My Name")
            };
    
            var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme.Name));
            var ticket = new AuthenticationTicket(claimsPrincipal,
                new AuthenticationProperties { IsPersistent = false },
                Scheme.Name
            );
            
            return AuthenticateResult.Success(ticket);
        }
    }
    

    You can then register your new scheme in Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
            .AddScheme("MyScheme", options => { /* configure options */ })
    }
    

提交回复
热议问题