No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

前端 未结 5 725
滥情空心
滥情空心 2020-12-05 01:35

I have a .NET Core 2.0 app and have a problem with authorization. I want to use custom authorization with special requests. Header and standard default authentication. First

5条回答
  •  生来不讨喜
    2020-12-05 02:05

    Do not use authorization instead of authentication. I should get whole access to service all clients with header. The working code is :

    public class TokenAuthenticationHandler : AuthenticationHandler 
    {
        public IServiceProvider ServiceProvider { get; set; }
    
        public TokenAuthenticationHandler (IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider) 
            : base (options, logger, encoder, clock) 
        {
            ServiceProvider = serviceProvider;
        }
    
        protected override Task HandleAuthenticateAsync () 
        {
            var headers = Request.Headers;
            var token = "X-Auth-Token".GetHeaderOrCookieValue (Request);
    
            if (string.IsNullOrEmpty (token)) {
                return Task.FromResult (AuthenticateResult.Fail ("Token is null"));
            }           
    
            bool isValidToken = false; // check token here
    
            if (!isValidToken) {
                return Task.FromResult (AuthenticateResult.Fail ($"Balancer not authorize token : for token={token}"));
            }
    
            var claims = new [] { new Claim ("token", token) };
            var identity = new ClaimsIdentity (claims, nameof (TokenAuthenticationHandler));
            var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), this.Scheme.Name);
            return Task.FromResult (AuthenticateResult.Success (ticket));
        }
    }
    

    Startup.cs :

    #region Authentication
    services.AddAuthentication (o => {
        o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
    })
    .AddScheme (SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });
    #endregion
    

    And mycontroller.cs

    [Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]
    public class MainController : BaseController
    { ... }
    

    I can't find TokenAuthenticationOptions now, but it was empty. I found the same class PhoneNumberAuthenticationOptions :

    public class PhoneNumberAuthenticationOptions : AuthenticationSchemeOptions
    {
        public Regex PhoneMask { get; set; }// = new Regex("7\\d{10}");
    }
    

    You should define static class SchemesNamesConst. Something like:

    public static class SchemesNamesConst
    {
        public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";
    }
    

提交回复
热议问题