Created
March 17, 2020 01:54
-
-
Save domingoladron/6e84db0b53a86e677b2a09cf246acd86 to your computer and use it in GitHub Desktop.
aspnetcore.toggleauth.startup.configureservices.cs
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
public void ConfigureServices(IServiceCollection services) | |
{ | |
//Other configuration above... | |
if (bool.Parse(Configuration["AUTHENTICATION_ENABLED"] ?? "true")) | |
{ | |
//add all your authentication setup logic here | |
services.AddMvcCore(options => options.EnableEndpointRouting = false) | |
.AddAuthorization(); | |
services | |
.AddAuthentication("Bearer") | |
.AddJwtBearer( | |
"Bearer", | |
options => | |
{ | |
options.Authority = Configuration["AUTHENTICATION_SERVER_URL"]; | |
//etc. whatever else you need in your options | |
}); | |
// Create a custom scope authorization policy | |
var scopeRequirementPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser() | |
.RequireClaim("scope", Configuration["AUTHENTICATION_SCOPE"]).Build(); | |
services.Configure<MvcOptions>(options => | |
options.Filters.Add(new AuthorizeFilter(scopeRequirementPolicy)) | |
); | |
services.AddAuthorization(options => | |
{ | |
options.AddPolicy("SomeRole", policy => policy.RequireRole("some_role")); | |
}); | |
} | |
else | |
{ | |
//If our configuration says to NOT enable authentication, then disable all authentication | |
services.AddMvcCore(opts => | |
{ | |
opts.EnableEndpointRouting = false; | |
opts.Filters.Add(new AllowAnonymousFilter()); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment