Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API role based authorization based on route parameter

I'm using roles in my ASP.NET Web API 2 project to limit access to certain resources.

Now I have the following scenario: A clubmanager can only do a GET for a club that he manages. A clubmanager should not be authorized to access clubs that he does not manage.

This is the method that gets a club:

[Authorize(Roles = "ClubManager")]
[Route("{clubId}")]
public Club GetClub(int clubId)

As you can see I only allow a user with the role "ClubManager" to access this resource. But I also have to make sure the user is manager of the club with the given clubId in the route parameter. Can I achieve this with the Authorize attribute? Or is my only option to do this check within the method itself?

like image 502
Tom Avatar asked Jan 04 '18 16:01

Tom


2 Answers

You could do this with a custom AuthorizeAttribute, for example:

public class ClubAuthoriseAttribute : System.Web.Http.AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        int clubId;
        int.TryParse((string) actionContext.ActionArguments["clubId"], out clubId);

        if (!UserCanManageClub(clubId))
        {
            return false;
        }

        return base.IsAuthorized(actionContext);
    }
}

And then use this new attribute instead:

[ClubAuthorise(Roles = "ClubManager")]
[Route("{clubId}")]
public Club GetClub(int clubId)

Note, this is assuming the parameter is named clubId, but you should have enough here to customise it to your needs.

like image 89
DavidG Avatar answered Sep 28 '22 04:09

DavidG


In my case, the ActionArguments property was not yet filled in the IsAuthorized method (see answer in ActionContext.ActionArguments Is Empty In IAuthenticationFilter). Instead, I was able to use

actionContext.RequestContext.RouteData.Values["clubId"]

Maybe, this helps someone in the future.

like image 29
Christoph Herold Avatar answered Sep 28 '22 04:09

Christoph Herold