1

I'm creating an API, which does not use MVC, but rather generic middleware(s). It should be possible to be authenticated against both Basic and (Jwt) Bearer scheme (I'm aware of the security flaws of Basic Auth)

I can easily register both schemes in the services, but app.UseAuthentication middleware will only attempt to authenticate against the default scheme (this is intentional and described in the documentation). Allowing multiple scheme for the same endpoint can be done in MVC by Authorize filter, but I couldn't find a simple solution for non-MVC scenarios

I see, that many people are trying to achieve the same: https://github.com/aspnet/AspNetCore/issues/3620 https://github.com/aspnet/Security/issues/1469

balazska
  • 963
  • 6
  • 25

1 Answers1

2

I've ended up defining a simple middleware based on https://github.com/aspnet/Security/issues/1469#issuecomment-334982498

app.Use(async (context, next) =>
{
    var authHeader = AuthenticationHeaderValue.Parse(context.Request.Headers[HeaderNames.Authorization]);
    var schemeName = authHeader?.Scheme ?? string.Empty;

    var provider = context.RequestServices.GetService<IAuthenticationSchemeProvider>();
    var scheme = await provider.GetSchemeAsync(schemeName);

    if (scheme != null)
    {
        var result = await context.AuthenticateAsync(scheme.Name);
        if (result.Succeeded)
        {
            context.User = result.Principal;
        }
    }

    await next.Invoke();
});

Starting from 2.1, custom scheme policy can be added and forwarding default scheme using AuthenticationSchemeOptions.ForwardDefaultSelector, see: https://github.com/aspnet/Security/issues/1469#issuecomment-399239254

balazska
  • 963
  • 6
  • 25
  • I recommend using the ForwardDefaultSelectors if those are available, you can just make it check the authorization header scheme. You can also parse the authorization header with `AuthenticationHeaderValue.Parse()` or TryParse. – juunas Mar 08 '19 at 11:32
  • Ah, I was looking for such parser, but didn't find. I'll update the example, thanks! – balazska Mar 08 '19 at 11:34