Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i set up a default for ActiveAuthenticationSchemes?

In my ASP.Net Core 2 project, I have a custom AuthenticationHandler middleware that i want to plug in.

public class BasicAuthenticationMiddleware : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public BasicAuthenticationMiddleware(IOptionsMonitor<AuthenticationSchemeOptions> options,
        ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
        : base(options, logger, encoder, clock)
    {
    }
    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var principal = new GenericPrincipal(new GenericIdentity("User"), null);
        var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), "BasicAuth");
        return Task.FromResult(AuthenticateResult.Success(ticket));
    }
}

In my startup I have the following:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = "BasicAuth";
        options.DefaultChallengeScheme = "BasicAuth";
        options.AddScheme("BasicAuth", x => {
            x.DisplayName = "BasicAuthenticationMiddleware";
            x.HandlerType = typeof(BasicAuthenticationMiddleware);
        });
    });
}

And finally my view controller:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values/Works
    [HttpGet]
    [Route("Works")]
    [Authorize(ActiveAuthenticationSchemes = "BasicAuth")]
    public string Works()
    {
        return "works";
    }

    // GET api/values/DoesNotWork
    [HttpGet]
    [Route("DoesNotWork")]
    [Authorize]
    public string DoesNotWork()
    {
        return "does not work";
    }

}

My authenticator HandleAuthenticateAsync will be called when I specify ActiveAuthenticationSchemes to my scheme name, but otherwise it will not. I have a demo app showing the behavior here: https://github.com/JohnPAguirre/AuthenticationSchemaProblem

I want my BasicAuthenticationMiddleware to log everyone in with my demo logic. How can i make the ActiveAuthenticationSchemes default to "BasicAuth" for all requests?

Anyone have any ideas on what I could be missing?

like image 370
JohnAguirre Avatar asked Aug 18 '17 00:08

JohnAguirre


1 Answers

I did manage to set a default authentication scheme By setting the scheme I want as the only authentication scheme of the DefaultPolicy for authorization. Use the following below in your config. I have used it in between AddMvc and AddAuthentication and it works fine.

services.AddAuthorization(config => {
    var def = config.DefaultPolicy;
    config.DefaultPolicy = new AuthorizationPolicy(def.Requirements, 
        new List<string>(){ "BasicAuth" });
});
like image 184
Neville Nazerane Avatar answered Oct 05 '22 23:10

Neville Nazerane