Created
August 17, 2018 13:50
-
-
Save postb99/59c77669ba83ad01b03338255ee9ef42 to your computer and use it in GitHub Desktop.
Multiple auth schemes in .NET Core 2.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://github.com/aspnet/Security/issues/1469 | |
JWT token if any in request header, then OpenIdConnect (Azure AD) or anything else. | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
// Add CORS | |
services.AddCors(); | |
// Add authentication before adding MVC | |
// Add JWT and Azure AD (that uses OpenIdConnect) and cookies. | |
// Use a smart policy scheme to choose the correct authentication scheme at runtime | |
services | |
.AddAuthentication(sharedOptions => | |
{ | |
sharedOptions.DefaultScheme = "smart"; | |
sharedOptions.DefaultChallengeScheme = "smart"; | |
}) | |
.AddPolicyScheme("smart", "Authorization Bearer or OIDC", options => | |
{ | |
options.ForwardDefaultSelector = context => | |
{ | |
var authHeader = context.Request.Headers["Authorization"].FirstOrDefault(); | |
if (authHeader?.StartsWith("Bearer ") == true) | |
{ | |
return JwtBearerDefaults.AuthenticationScheme; | |
} | |
return OpenIdConnectDefaults.AuthenticationScheme; | |
}; | |
}) | |
.AddJwtBearer(o => | |
{ | |
o.Authority = Configuration["JWT:Authentication:Authority"]; | |
o.Audience = Configuration["JWT:Authentication:ClientId"]; | |
o.SaveToken = true; | |
}) | |
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme) | |
.AddAzureAd(options => Configuration.Bind("AzureAd", options)); | |
services | |
.AddMvc(config => | |
{ | |
var policy = new AuthorizationPolicyBuilder() | |
.RequireAuthenticatedUser() | |
.Build(); | |
// Authentication is required by default | |
config.Filters.Add(new AuthorizeFilter(policy)); | |
config.RespectBrowserAcceptHeader = true; | |
}); | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment