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

Tom*_*Tom 5 c# authorize asp.net-web-api2

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)
Run Code Online (Sandbox Code Playgroud)

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?

Dav*_*idG 4

您可以使用自定义来执行此操作AuthorizeAttribute,例如:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用这个新属性来代替:

[ClubAuthorise(Roles = "ClubManager")]
[Route("{clubId}")]
public Club GetClub(int clubId)
Run Code Online (Sandbox Code Playgroud)

请注意,这是假设参数名为 name clubId,但您应该有足够的参数来根据您的需要对其进行自定义。