简体   繁体   中英

Authorize attribute for any roles

Let's say I have WebApi Controller

[Authorize]
public class SomeApiController : ApiController

Controller action methods itself does not have any [Authorize] or [AllowAnonymous] attributes.

I want Authorize attribute to return 401 (Unauthorized) error if user has no roles - seems logical (if user had role and now doesn't have ANY - he shouldn't be allowed to perform action even though user is authenticated). I have looked to asp.net mvc webstack I have found the following code in Authorize attribute:

if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole))
{
    return false;
}

So looks like if we didn't passed roles authorize attribute just checks if user is authenticated. Setting each role in Roles list is not an option for me ( I mean [Authorize(Roles="role1,role2,...")] ).

Therefore question - can I somehow achieve setting Authorize attribute to check if user has ANY role. Or it's better to write custom attribute inherited from above?

Create custom attribute like below:

public override void OnAuthorization(AuthorizationContext filterContext)
{
    string[] userRoles = System.Web.Security.Roles.GetRolesForUser(filterContext.HttpContext.User.Identity.Name);

    if (!userRoles.Any())
    {
        throw new HttpException(401, "Unauthorized");
    }
    base.HandleUnauthorizedRequest(filterContext);
}

}

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM