Skip to content

Instantly share code, notes, and snippets.

@demaderios
Last active May 21, 2020 19:22
Show Gist options
  • Save demaderios/34bb42851a6ea9583eb9eb67a2398ef1 to your computer and use it in GitHub Desktop.
Save demaderios/34bb42851a6ea9583eb9eb67a2398ef1 to your computer and use it in GitHub Desktop.
Custom .Net Core policy using Func
public static void ConfigureAuthorization(this IServiceCollection services)
{
services.AddAuthorization(options =>
{
options.AddPolicy("CanAccessSuperTopSecretArea", policy =>
{
context => context.User.HasClaim(claim => claim.Type == "TopSecretUser" || claim.Type == "OtherTopSecretUser" ||
context.User.IsInRole("SupremeOverlord"))
}
}
}
public class TopSecretController : Controller
{
[Authorize(Policy = "CanAccessSuperTopSecretArea")]
public IActionResult Index()
{
return View();
}
}
@demaderios
Copy link
Author

This authorization service extension (to avoid cluttering up Startup.cs) creates a policy called "CanAccessSuperTopSecretArea". A user in this policy must have the claim "TopSecretUser" OR "OtherTopSecretUser" OR is in the role "SupremeOverlord".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment