Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save domingoladron/6e84db0b53a86e677b2a09cf246acd86 to your computer and use it in GitHub Desktop.
Save domingoladron/6e84db0b53a86e677b2a09cf246acd86 to your computer and use it in GitHub Desktop.
aspnetcore.toggleauth.startup.configureservices.cs
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