I'm building an API in .NET Core 1.1. I build a custom User
object from HttpContext.User
in a base controller that all of my other controllers inherit from, and I have authentication enabled by default (must be manually disabled with [AllowAnonymous]
when necessary). The User
object has an IsAdmin
property. Right now I'm checking if the user is an admin at the top of each relevant function like below, but I feel like there must be a way to add a custom attribute to simplify and clean up this code.
For reference, User.IsAdmin
is shorthand for this:
bool.Parse(HttpContext.User.FindFirst("IsAdmin")?.Value)
Instead of this:
[HttpGet]
public async Task<IActionResult> Get()
{
if (!User.IsAdmin)
return Forbid();
// logic
}
I'd like this (or something similar):
[AdminOnly]
[HttpGet]
public async Task<IActionResult> Get()
{
// logic
}
I tried looking at the source for [AuthorizeAttribute]
to try to build from, but it's just a shell and I don't know where the real magic happens.
How can I accomplish this?
Right-click on the solution and add a new class. Enter the class name and click on Add. Next Inherite Attribute, IAuthorizationFilter to CustomAuthorization class which has overridden the OnAuthorization method. The OnAuthorization Method has the AuthorizationFilterContext parameter.
Authorization in ASP.NET Core is controlled with AuthorizeAttribute and its various parameters. In its most basic form, applying the [Authorize] attribute to a controller, action, or Razor Page, limits access to that component to authenticated users. Now only authenticated users can access the Logout function.
This attribute is useful when you want to use the Authorize attribute on a controller to protect all of the actions inside, but then there is this single action or one or two actions that you want to unprotect and allow anonymous users to reach that specific action.
Add the UseAuthentication middleware after UseRouting in the Configure method in the Startup file. This will enable us to authenticate using ASP.NET Core Identity. With all of this in place, the application Is all set to start using Identity.
The solution suggested by @JoeAudette seems to be the best option.
Create your own policy in Startup.cs
ConfigureServices():
services.AddAuthorization(options =>
options.AddPolicy("PolicyName", p =>
{
p.RequireAuthenticatedUser();
p.RequireClaim("IsAdmin", true); <- your criteria here (claim type, claim value) ???
p.Build();
})
);
Then just use it as an attribute:
[Authorize("PolicyName")]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With