Core 2.0 multiple auth schemes problem: default one overrides all, and no default ignores all
The problem I am reporting seems to be similar to https://github.com/aspnet/Security/issues/1381.
Summary
My TL;DR summary is that in ASP.NET Core 2,0 it seems impossible to have multiple authentication schemes handling requests with corresponding values of the Authorization header, while we had no trouble implementing this in 1.1 and earlier with OWIN.
Details
Using ASP.NET Core 2.0, we are adding two custom authentication schemes, let's call them "Abc" and "Xyz", using services.AddSchema() method. When I send a request with Authorization header having either Abc SomeAuthInfo or Xyz SomeOtherAuthInfo value, I expect a corresponding handler to be called by the framework, as it happened in OWIN and later in Core 1.1. That does not happen. The only non-invasive way to make it work was specifying default schema via services.AddAuthentication("Abc"), which resulted in "Abc" scheme working and "Xyz" not working.
Eventually, I have to do this:
di.AddScoped<IAuthenticationHandlerProvider, AuthSchemeMappingAuthenticationHandlerProvider>();
di.AddSingleton<IAuthenticationSchemeProvider, BugWorkaroundAuthenticationSchemeProvider>();
with those two hand-rolled classes hacking the default ASP.NET Core 2.0 logic letting us look at what Authorization header value starts with - the scheme - and map it the appropriate handler.
The Question
My question is, is this a bug, or have I simply failed to find a legitimate way to map auth schemes to their handlers?
I have this exact same issue. I have Jwt and Facebook authentication enabled (Jwt is default scheme). When I pass Jwt token in the authorization header, works perfectly. When I pass the access token in the authorization header that I received from facebook, it fails. Did you ever find anything out about this?
So far I have not heard anything from ASP.NET dev team. I have implemented a workaround by replacing two classes as shown in my post, but I hope to replace it with a better solution. I'm hoping someone can suggest a better way.
My question is, is this a bug, or have I simply failed to find a legitimate way to map auth schemes to their handlers?
Good or bad, this is a deliberate change that was announced here: https://github.com/aspnet/Announcements/issues/262. Basically, the new stack only allows you to have a single automatic scheme handler by default. Having to override the scheme provider is expected if you want to change the default selection mechanism.
Don't miss this questions/answers thread if you need more information: https://github.com/aspnet/Security/issues/1338.
@vgribok What @PinpointTownes says is right, this is by design. However, nothing stops you from calling context.AuthenticateAsync("Scheme") to access the right user information.
How were you doing this before? Was it dynamic basic on something in the incoming request?
Yes, it was dynamic based on the scheme name in the incoming requests' Authorization header. In Core 1.1 it worked without us having to manually do the mapping - we just specified every scheme as default, which was weird but possible.
What would be helpful is a clean code example showing how to do it properly in Core 2.0. Right now it's not hard to figure out how to add multiple schemes, but getting them to be employed is difficult, and I could not find clear guidance for how to do it properly. "Programmer's Guide" type of docs would be very appreciated.
The code in 2.0 would look like a piece of middleware that does this:
app.UseAuthentication();
app.Use(async (context, next) =>
{
// Write some code that determines the scheme based on the incoming request
var scheme = GetSchemeForRequest(context);
var result = await context.AuthenticateAsync(scheme);
if (result.Succeeded)
{
context.User = result.Principal;
}
await next();
});
FWIW, we're actively looking at some first class improvements in this area for 2.1 (see https://github.com/aspnet/Security/pull/1410).
UPDATE: It's actually not as simple as what I wrote. This won't work well for challenge/forbid. Your best bet is to use an authentication policy and set the right scheme on the controller action itself.
Are you using MVC?
Thanks. Yes, we are using MVC, but we build same kind of identity & principal from three and potentially more different auth schemes. Our auth handlers have federation-like functionality, and because of that our roles will be the same regardless of the scheme type in the inbound request, which in turn makes explicit usage of scheme with controllers impossible.
I'd like to add 2c on what would be intuitive design for me. I don't quite understand the value of the DefaultAuthenticationScheme. (Default challenge scheme I understand.) IMHO, the process here is two-step: 1) Building Principal from request, and 2) authorizing protected resources (like Controller methods) by matching Claims supplied by the Principal to ones demanded by the protected resource via Authorize attribute. In this flow, at step 1, multiple sources of identity and claims can be supplied - via potentially multiple Authorization headers, cookies, and wherever else is in the request. The only value of a schema I can see is to simplify mapping of "properly"-supplied auth info, meaning Authorization header to handlers. That, I hoped, was implemented in Core 2.0 and allowed to get rid of per-schema middleware we had to have in Core 1.1 and OWIN. So far very good: having only one framework-supplied AuthenticationMiddleware may have even more benefits, like maybe calling multiple auth handlers in parallel, for example, bypassing the sequential nature of a middleware we had to do in 1.1. But in this design, for the life of me, I can't see the place for the default auth schema.
I may be able to see default auth schema only in the case where Principal has multiple claim types, and Authorize attribute does not specify Claim.Type (AuthorizeAttribute.AuthenticationSchemes) making it impossible to determine what Roles property is really specifying. There default auth schema, which would really be default claim type, would make sense to me. Current design, though, with AuthorizeAttribute.AuthenticationSchemes implying relationship to the Claim.Type, while not being it IFAICT, is a stretch: as I mentioned, a single incoming Authorization header with a single scheme can result in a single IIdentity being a part of Principal with multiple types of claims. Just as true is the observation that multiple Authorization headers in the same request can result in a Principal having Claims of just a single Claim.Type. If you agree with that assumption, it effectively breaks default scheme as a coupling link between the inbound request and the application of claims authorization.
To summarize, current approach of somewhat tight coupling via default scheme of auth info in the inbound requests with applying Claims-based authorization is a stretch. IMHO, there should not be coupling at all, and maybe that's what can be done using Policies - I still need to learn that part, but that adds new layers of complexity and to the length of a learning curve. Even back in 2013 when .NET 5.2 introduced Claims authorization, it was too complex to most folks used to ASP.NET cookie auth, but what I am seeing now it really complex, while not seemingly covering relatively straightforward use cases.
So the DefaultAuthenticateScheme's purpose is twofold, its mainly used by the single default authentication middleware to set HttpContext.User to the result of a specific authentication scheme.
Its fine to have multiple sources of identity and claims used to produce the HttpContext.User that you then use for Authorization. You can either write a custom uber AuthenticationHandler and register that as your default scheme, and it can pull from whatever sources you want. Or you can add your own custom middleware that assembles the httpContext.User however you like, and just don't use DefaultAuthenticationScheme.
Authentication today isn't aware of authorization at all, it only cares about producing a ClaimsPrincipal per scheme. Authorization has to be aware of authentication somewhat, so AuthenticationSchemes in the policy is a mechanism for you to associate the policy with schemes used to build the effective claims principal for authorization (or it just uses the default httpContext.User for the request, which does rely on DefaultAuthenticateScheme)
Or you can add your own custom middleware that assembles the httpContext.User however you like, and just don't use DefaultAuthenticationScheme.
This is what my sample does above, but what breaks down is the call to Challenge/Forbid if there is no user. The new authentication schemes solves this nicely.
Its fine to have multiple sources of identity and claims used to produce the HttpContext.User that you then use for Authorization. You can either write a custom uber AuthenticationHandler and register that as your default scheme, and it can pull from whatever sources you want.
This is a super interesting idea and not one I thought about before. I might try to whip up a sample with this.
Yeah this is basically using the authenticationScheme as the authentication policy today
Its fine to have multiple sources of identity and claims used to produce the HttpContext.User that you then use for Authorization. You can either write a custom uber AuthenticationHandler and register that as your default scheme, and it can pull from whatever sources you want.
This is a super interesting idea and not one I thought about before. I might try to whip up a sample with this.
This is what we do in our IdentityServer access token validation handler that is implemented in terms of other handlers (specifically JWT Bearer and introspection).
https://github.com/IdentityServer/IdentityServer4.AccessTokenValidation
Its fine to have multiple sources of identity and claims used to produce the HttpContext.User that you then use for Authorization. You can either write a custom uber AuthenticationHandler and register that as your default scheme, and it can pull from whatever sources you want. Or you can add your own custom middleware that assembles the httpContext.User however you like, and just don't use DefaultAuthenticationScheme.
For sure, I can certainly roll out my own anything, but with services.AddScheme() enabling multiple schemes and with the presence of a general-purpose app.UseAuthentication(), the requirement to add custom components to make use of multiple schemes is surprising, as the framework seems to have all necessary information to make scheme-handler mapping generic and transparent, improving user experience by not requiring users create custom components. That's what my custom AuthenticationHandlerProvider and AuthenticationSchemeProvider do together, without resorting to using custom middleware or the uber-handler (unless handler provider is considered to be that): they map scheme from the inbound Authorization header to a registered handler with matching scheme, without needing to know what those schemes and handlers are. I am basically asking for the less hack-y way to do it (complete example would be more helpful than an outline), and to understand what is the reason why it is not a part of the framework, i.e. whether it's just a matter of ASP.NET team having time to do it, or if there is a reason for current approach to stay like this, even though Core 1.1 and OWIN didn't require this.
Yeah this is basically using the authenticationScheme as the authentication policy today
@HaoK how hacky is something like this?
services.AddAuthentication("Dynamic")
.AddJwtBearer("Scheme2", options =>
{
})
.AddJwtBearer("Scheme1", options =>
{
})
.AddDynamicAuthentication(options =>
{
options.SchemeSelector = context =>
{
// Write whatever logic you need to pick the "current" scheme
string authHeader = context.Request.Headers["Authorization"];
// Authorization: Scheme
var scheme = authHeader.Split(' ')[0];
return scheme;
};
});
I guess the authN policy concept is still cleaner because some authN policies require a unique set of schemes for (authenticate, challenge, signin, signout). For example, a "facebook" policy would look like:
"Facebook" -> (authenticate: "cookies", challenge: "facebook", signin: "cookies", signout: "cookies")
Thanks! That's not hacky, and I'll happily use it. I hope this will become the default behavior in one of the upcoming versions of ASP.NET Core.
@davidfowl that looks fine and no hacky really.
So thinking about it more, you really could implement a scheme as a policy today already.
Just have the handler forward to the right other schemes already in its implementation. For your example: lets say we added a AuthenticationPolicyHandler and just made it easy to setup schemes that behaved as policies (forwarders):
You'd still do something
.AddAuthenticationPolicy("FacebookPolicy", policy => {
policy.DefaultScheme = "Cookies"
policy.ChallengeScheme = "Facebook";
})
And we'd have a new base AuthenticationPolicyHandler that could just take a named AuthenticationPolicyOption "FacebookPolicy" and used that to dispatch the Authenticate/Challenge/Forbid/SignIn/SignOut to the appropriate schemes.
Might be cleaner/simpler than building out all the additional services/classes in the current PR for authN policies.
And probably instead of calling it authentication policy, call it something else to disambiguate it from AuthorizationPolicy. (AuthenticationForwarderHandler or something)
Might be cleaner/simpler than building out all the additional services/classes in the current PR for authN policies.
Yep that's what I'm thinking as well.
I was thinking that you could get all the flexibility making the scheme selector a policy selector.
Closing this issue because we're using https://github.com/aspnet/Security/issues/1359 as the main discussion (and there's a linked PR as well). If there's anything not covered there, please comment in the other thread. Thanks!
Thank you, @davidfowl ! Your comment helped me to solve another issue, that I stumbled upon while implementing IdentityServer4 with REST API controllers in the same app. Existing samples show how to implement this as separate apps: one with IdentityServer4 for auth and other apps with authentication based on JWT in request headers via AuthorizeAttribute. The problem arose because using services.AddAuthentication(...).AddJwtBearer(...) together with services.AddIdentityServer(...) leads to incorrect behavior: logging in didn't actually log in. But without services.AddAuthentication(...).AddJwtBearer(...) my AuthorizeAttribute didn't handle JWT token in Authorization header. So I implemented it manually:
app.Use(async (context, next) =>
await AuthenticateApiRequestByAuthorizeHeader(context, next, app.ApplicationServices));
private async Task AuthenticateApiRequestByAuthorizeHeader(HttpContext context, Func<Task> next, IServiceProvider serviceProvider)
{
bool isApiRequest = context.Request.Path.StartsWithSegments("/api");
if (isApiRequest)
{
string token = context.Request.Headers["Authorization"].FirstOrDefault()?.Substring("Bearer ".Length);
if (token != null)
{
var validator = serviceProvider.GetServiceOrDie<ITokenValidator>();
var validationResult = await validator.ValidateAccessTokenAsync(token);
if (!validationResult.IsError && validationResult.Claims.Any(c => c.Type == "email"))
{
string email = validationResult.Claims.FirstOrDefault(c => c.Type == "email")?.Value;
var userManager = serviceProvider.GetServiceOrDie<UserManager<ApplicationUser>>();
var user = await userManager.FindByEmailAsync(email);
if (user != null)
{
var signInManager = serviceProvider.GetServiceOrDie<SignInManager<ApplicationUser>>();
await signInManager.SignInAsync(user, isPersistent: false);
var userClaimsPrincipalFactory = serviceProvider.GetServiceOrDie<UserClaimsPrincipalFactory<ApplicationUser>>();
context.User = await userClaimsPrincipalFactory.CreateAsync(user);
}
}
}
}
await next();
}
where GetServiceOrDie is an extension
public static T GetServiceOrDie<T>(this IServiceProvider serviceProvider)
{
var service = serviceProvider.GetService<T>();
if (EqualityComparer<T>.Default.Equals(service, default(T)))
throw new Exception($"Failed to get service of type {typeof(T)}");
return service;
}
Problem
I had a similar problem, when I was implementing a middleware with an HTTP protocol extension. And to work via that protocol, a custom cookie authentication is required. It all wouldn't be a problem if it was a separate app server, but the requirement was to run under a specific path on a server, which is using a different authentication scheme.
So the problem is that I can't easy specify a custom rule like context.Request.Path.Value.StartsWith("/documents") in the Startup.cs for applying an authentication scheme. And I needed it because the /documents path was handled in a middleware, not in a controller.
Workaround A workaround, which worked for me was to write my own implementation of IAuthenticationHandlerProvider (with just a minor difference from the original implementation), which would resolve the authentication scheme differently for different parts in GetHandlerAsync() method. The remaining bit was to register my implementation in IStartup.ConfigureServices() method like the OP showed:
di.AddScoped<IAuthenticationHandlerProvider, AuthSchemeMappingAuthenticationHandlerProvider>();
It feels hacky, but works.
Questions
- @vgribok, why did you need your own IAuthenticationSchemeProvider implementation? It seems working without it.
- Is it even possible to implement a dynamic scheme, which can pass authentication on other schemes (as suggested by @davidfowl above)? Apart from .NET Core v1 implementation via middleware, new
AuthenticationHandlerclasses can't pass it on to the next one.