User987
User987

Reputation: 3825

Roles.GetRolesForUser unavailable in custom authorization attirbute

I'm trying to implement my own custom attribute where I have to fetch all roles for current user like this:

public class CustomRoleAuthorization: System.Web.Mvc.AuthorizeAttribute
    {

   public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult("~/Login");
                return;
            }
            var requiredRoles = Roles.Split(Convert.ToChar(",")).ToList();

            var userRoles = Roles.GetRolesForUser(filterContext.HttpContext.User.Identity.Name);

            foreach (var item in requiredRoles)
            {
                if (!filterContext.HttpContext.User.IsInRole(item))
                {
                    filterContext.Result = new RedirectResult("~/Index/Index");
                    return;
                }
            }

        }
}

But for some reason this line doesn't works:

 var userRoles = Roles.GetRolesForUser(filterContext.HttpContext.User.Identity.Name);

It says that the Roles property is a string and that it doesn't contains a method GetRolesForUser?

How can I add this extension method to my project so that I can get all user roles from identity upon loging in ??

@Stephen this is how I set the roles upon login:

 if (user.PasswordHash == PasswordSecurity.CreatePasswordHash(model.Password, user.PasswordSalt))
 {
  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);
 return Json("ok");
 }

Upvotes: 0

Views: 254

Answers (1)

user3559349
user3559349

Reputation:

AuthorizeAttribute contains a public string Roles { get; set; } property (refer documentation) so you need to use the fully qualified name

var userRoles = System.Web.Security.Roles.GetRolesForUser(...

or you can create an alias for the assembly name

Upvotes: 1

Related Questions