System.InvalidOperationException: No authentication handler is configured to handle the scheme: Automatic
This might be a bug with Kestrel (not with IIS).
Scenario:
- Create a New Asp.Net Core (version 1.0.0) project
- Choose the Web API template
- Add the
[Authorize]attribute on the default ValuesController - Run the application
If I run the application with IIS and make a GET request to http://localhost:60513/api/values I get the expected 401 Unauthorized error
If however I run the application with Kestrel (e.g: dotnet run) and make a GET request to http://localhost:5000/api/values I get a 500 Internal Server Error with the following exception at kestrel:
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/api/values
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed for user: .
warn: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
Executing ChallengeResult with authentication schemes ().
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HKUMMBBBQ6AU": An unhandled exception was thrown by the application.
System.InvalidOperationException: No authentication handler is configured to handle the scheme: Automatic
at Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager.<ChallengeAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.ChallengeResult.<ExecuteResultAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeResultAsync>d__32.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1.<RequestProcessingAsync>d__2.MoveNext()
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 282.8427ms 200
I created a question at Stackoverflow thinking that this could be expected behavior to see if anybody could explain why.
Authorize requires at least one auth middleware in order to issue challenges. In IIS the IISMiddleware acts as an auth middleware and sets a 401 so IIS will set windows auth challenge headers. That doesn't apply when running just Kestrel, you need something like CookieAuth or JwtBearer, etc..
Just ran into the same issue with Kestrel. Working on Web API project for machine to machine communication using SaasKit as a middleware to identify tenants based on application/security key provided. So basically i used custom Authorization Provider to secure my API methods. As a workaround i added app.UseJwtBearerAuthentication(); in my Startup class as @Tratcher mentioned.
I have this same issue when trying to use dotnet watch run - but in my case I do have an auth middleware, just using OWIN so I can use WS Federation (targeting full framework of course):
app.UseOwinApp(
owin =>
{
owin.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
owin.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions());
owin.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions()
{
SignInAsAuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType,
MetadataAddress = "http://localhost:38152/FederationMetadata.xml",
Wtrealm = "http://localhost:13328/",
TokenValidationParameters =
new TokenValidationParameters() { RequireSignedTokens = false }
});
});
Can someone explain why my OWIN pipleline doesn't count as auth middleware for kestrel, but works perfectly with IIS Express?
Here is my UseOwinApp extension:
public static IApplicationBuilder UseOwinApp(
this IApplicationBuilder aspNetCoreApp,
Action<IAppBuilder> configuration)
{
return aspNetCoreApp.UseOwin(setup => setup(next =>
{
AppBuilder owinAppBuilder = new AppBuilder();
IApplicationLifetime aspNetCoreLifetime = (IApplicationLifetime)aspNetCoreApp.ApplicationServices.GetService(typeof(IApplicationLifetime));
AppProperties owinAppProperties = new AppProperties(owinAppBuilder.Properties);
owinAppProperties.OnAppDisposing = aspNetCoreLifetime?.ApplicationStopping ?? CancellationToken.None;
owinAppProperties.DefaultApp = next;
owinAppProperties.AppName = "MyWebSite";
configuration(owinAppBuilder);
return owinAppBuilder.Build<Func<IDictionary<string, object>, Task>>();
}));
}
UseWsFederationAuthentication is not supported in ASP.NET Core, the underlying auth mechanics have changed.
IIS/Express itself counts as an auth hander as it can forward Windows auth.
OK sure WS Federation isn't supported in ASP.Net Core. How about I change my example to this:
app.UseOwinApp(
owin =>
{
owin.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
owin.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions());
});
Can you please explain why that doesn't work? Is it because there is a disconnect between the Authorize attribute and the OWIN pipeline's authentication?
Exactly. ASP.NET Core only supports standardized OWIN interop keys, but the keys used by Katana for security were never standardized, so Katana auth middleware mostly won't work with Core.
I have the same issue . Created a embedded identityserver and WebAPI app in the same project . However I added the required middleware but it never works with kestrel .
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddIdentityServer(options =>
{
options.SiteName = "DreamBakery Security Token services";
})
.SetSigningCredential(new X509Certificate2(Path.Combine(Directory.GetCurrentDirectory(), @"Cert\CoreAppNgCert.pfx"), "joydeep"))
.AddInMemoryClients(Clients.Get())
.AddInMemoryUsers(Users.Get())
.AddInMemoryScopes(Scopes.Get())
.AddInMemoryStores();
services.AddAuthorization().AddDistributedMemoryCache();
services.AddCors(cors =>
cors.AddPolicy("AllowIdentityCors", policy =>
{
policy.AllowAnyOrigin()
.WithExposedHeaders("WWW-Authenticate")
.WithOrigins("https://localhost:5000");
}
));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
//app.Use(ChangeContextToHttps);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentityServer();
app.UseMvcWithDefaultRoute();
app.UseIdentityServer();
app.UseJwtBearerAuthentication();
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = Authority,
ScopeName = "Api",
RequireHttpsMetadata = false,
AutomaticAuthenticate = true,
AutomaticChallenge = true,
ScopeSecret = "secret",
EnableCaching = false,
SaveToken = true,
});
}
As mentioned by @Tratcher I have given app.UseJwtBearerAuthentication(). But it still doesn't work . I keep on getting this below stacktrace .
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[0]
An unhandled exception has occurred while executing the request
System.InvalidOperationException: No authentication handler is configured to han
dle the scheme: Automatic
at Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationMan
ager.<ChallengeAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at Microsoft.AspNetCore.Mvc.ChallengeResult.<ExecuteResultAsync>d__14.MoveNex
t()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeResultAsy
nc>d__32.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__
18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at IdentityServer4.Hosting.IdentityServerMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at IdentityServer4.Hosting.FederatedSignOutMiddleware.<Invoke>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at IdentityServer4.Hosting.AuthenticationMiddleware.<Invoke>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__
18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__
18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>d__7.MoveN
ext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at IdentityServer4.Hosting.BaseUrlMiddleware.<Invoke>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>
d__6.MoveNext()
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 709.7318ms 500 text/html; charset=utf-8
Ordering, auth needs to be before consumers like MVC.
@eilon @blowdart This seems really confusing. Why would I need to add authentication middleware to get a 401? Returning a 500 in this situation seems wrong.
HTTP requires a 401 be accompanied by headers telling the client how they can authenticate. If you're not going to tell the client how to log in you may as well use a 403 Forbidden. 401 is also a specific flow of auth, most of our providers use 301s instead. As such [Authorize] doesn't pick the status code at all, the middleware do that.
We added this check to catch common errors like the one above: https://github.com/aspnet/Security/issues/967#issuecomment-252465556. An app can send a 401 on its own, but [Authorize] won't.
Sure, I can see how returning a 403 makes more sense in this case.
I have written a middleware that will redirect the user to their token issuer depending on if MVC sets the HTTP status code to 401. Essentially this will take the 401 and change it to a 302 and redirect the user (which is what I believe is what you're referring to as the challenge).
It looks like MVC is short circuiting the response by attempting to issue the challenge (when debugging through Kestrel). Because MVC doesn't know about how my middleware will handle the challenge, it results in the exception above when it tries to issue the challenge by calling an authentication handler which does not exist.
Because MVC does not know about my custom middleware's authentication handler or how it will handle redirecting user's, is there a way to either...
- Register my custom authentication middleware so that MVC will know how to call my authentication handler OR
- Configure MVC to not issue the challenge/call an authentication handler, but rather just return the 401 and let my authentication middleware handle rerouting the request on the outbound side that is fired after MVC. I'm assuming this would be the equivalent to setting
AutomaticChallenge = falsein any of the built-in middleware.
Up to this point, I was under the impression that MVC would always return a 401 response code and let my middleware handle the challenge on the outbound side, after MVC had finished processing the request. Like others have mentioned, this is the observed behavior when debugging through IIS Express.
I assume your MVC app is using the [Authorize] attribute? Authorize does not just set a 401 because 401s are specific to one kind of auth. Authorize instead calls HttpContext.Authentication.ChallengeAsync() which calls into the authentication handlers in the pipeline. If no handlers respond then the above exception is thrown.
If you want to plug into Authorize as an authentication handler then you can follow the example of one of our other handlers. https://github.com/aspnet/Security/tree/dev/src/Microsoft.AspNetCore.Authentication.Cookies https://github.com/aspnet/Security/tree/dev/src/Microsoft.AspNetCore.Authentication.OAuth https://github.com/aspnet/IISIntegration/blob/dev/src/Microsoft.AspNetCore.Server.IISIntegration/IISMiddleware.cs#L81
Ah I see! It appeared that the MVC [Authorize] attribute was setting my response code to 401 because I only noticed the response status code change once MVC was invoked, but in reality because I was debugging with IIS Express, the IISMiddleware was handling the challenge request and setting it to 401 behind the scenes.
Thanks for the help, @Tratcher, I'll have a look at the middleware that you linked and write mine in such a way where it implements the authentication handler.
So basically, if I have an [Authorize] tag on some of my controller action, it will behave differently between IIS and Kestrel, unless I set AutomaticChallenge to true + set the OnRedirectToLogin event to make sure I'm returning 401 (if that's what I want). I did that, it's working, but I'm not fully happy with it, hence a few more questions.
Let's say I want to stick to AutomaticChallenge = false, could I be creating a "plug" middleware just to handle this challenge and do I have a way to insert this middleware only if I'm running outside of IIS. I can't find a way to programmaticaly detect if I'm outside of IIS ... Or maybe a way to detect that the IIS middleware is plugged already?
Thanks.
@daboul if you really want an auth middleware that just sets 401, why not use it with IIS as well? It shouldn't conflict.
@Tratcher Thank you for the suggestion, I guess I could do it this way, that's right. But it still doesn't feel right to add an extra layer of middleware when using IIS, while I don't need it. So if you happen to know a way do know whether I'm being IIS or not, I would still be interested. I discovered as well that the exception was due to the fact that I was using [Authorize] without specifying any ActiveAuthenticationSchemes, so I might also leverage that to get a cleaner code working both on Kestrel and IIS [Authorize(ActiveAuthenticationSchemes = AuthSchemeName)] Thanks.
We are closing this issue because no further action is planned for this issue. If you still have any issues or questions, please log a new issue with any additional details that you have.
I stumbled accross this problem and for future reference (for me), here is my solution, when using only cookie-authentication:
services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
options.Cookies.ApplicationCookie.AutomaticChallenge = true;
options.Cookies.ApplicationCookie.Events = new Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationEvents
{
OnRedirectToLogin = (context) =>
{
context.Response.StatusCode = 401;
return System.Threading.Tasks.Task.CompletedTask;
},
};
})