0

I have added a custom authorization attribute like this:

  public class RequireSubscription: System.Web.Mvc.AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult("~/User/Login");
                return;
            }
            if (!filterContext.HttpContext.User.IsInRole("Subscriber"))
            {
                filterContext.Result = new RedirectResult("~/Subscriptions/Subscribe");
                return;
            }
        }
    }

So the logic is plain and simple, if user doesn't have a specific role, then he gets redirected to subscribe...

However, user can have multiple roles added upon login like this:

ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, model.Email));

List<Claim> claims = new List<Claim>();
var roles = user.UserRoles.Where(x=>x.Active==true).ToList();

foreach (var item in roles)
{
    claims.Add(new Claim(ClaimTypes.Role, item.Roles.RoleName));
}

identity.AddClaims(claims);
identity.AddClaim(new Claim(ClaimTypes.Name, model.Email));

AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddHours(3) }, identity);

Where I now have need to check for multiple roles in Authorization attribute ....

The logic should be changed to allow user to access the controller when he has "Subscriber" role among the whole list of them like this:

Regular
Subscriber
TestRole

If any of these equals to =Subscriber, he should be allowed access. However that isn't the case now since I'm guessing with my method I'm only checking the first role that is set, and not others?

How could I fix this to check for all user roles assigned upon login ?

Bender Bending
  • 729
  • 8
  • 25
User987
  • 3,663
  • 15
  • 54
  • 115
  • Anyone guys? =) – User987 Jul 24 '17 at 18:52
  • Your question answer may be. [See this thread ](https://stackoverflow.com/questions/14477757/how-can-i-check-if-a-user-is-in-any-one-of-a-few-different-roles-with-mvc4-simpl?answertab=active#tab-top) – Mian Almas Jul 25 '17 at 05:33
  • For some reason I don't have a Roles.GetRolesForUser() method available in the authorization class? – User987 Jul 25 '17 at 10:37
  • then you can try this without gettig Roles.GetRolesForUser() [See this](https://stackoverflow.com/questions/32369229/usage-of-user-isinrole-in-a-view?answertab=active#tab-top) – Mian Almas Jul 26 '17 at 04:22

0 Answers0