Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom authorization attribute in .NET Core [duplicate]

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?

like image 697
vaindil Avatar asked Jan 07 '17 20:01

vaindil


People also ask

How do I override an authorized attribute in .NET Core?

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.

How does Authorize attribute work C# .NET Core?

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.

When should we use Authorize attribute?

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.

How do I Authorize a user in .NET Core?

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.


1 Answers

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")]
like image 168
Lukasz Mk Avatar answered Nov 10 '22 19:11

Lukasz Mk