Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identity Authorize Attribute Roles with Web API

I have a small Web API application that uses Identity to manage users using Owin Bearer Tokens. The basics of this implementation work fine: I can register a user, login a user and access Web API end points that are marked with [Authorize].

My next step is to limit Web API endpoints using roles. For example, a controller that only users in the Admin role can access. I've created the Admin user as below and I add them to the Admin role. However when I update my existing controllers from [Authorize] to [Authorize(Roles = "Admin")] and try to access it using the Adim account, I get a 401 Unauthorized.

    //Seed  on Startup
    public static void Seed()
    {
        var user = await userManager.FindAsync("Admin", "123456");
        if (user == null)
        {
            IdentityUser user = new IdentityUser { UserName = "Admin" };
            var createResult = await userManager.CreateAsync(user, "123456");

            if (!roleManager.RoleExists("Admin"))
                var createRoleResult = roleManager.Create(new IdentityRole("Admin"));

            user = await userManager.FindAsync("Admin", "123456");
            var addRoleResult = await userManager.AddToRoleAsync(user.Id, "Admin");
        }
    }


   //Works
   [Authorize]
    public class TestController : ApiController
    {
        // GET api/<controller>
        public bool Get()
        {
            return true;
        }
    }

   //Doesn't work
   [Authorize(Roles = "Admin")]
    public class TestController : ApiController
    {
        // GET api/<controller>
        public bool Get()
        {
            return true;
        }
    }

Q: What is the correct way to set up and use roles?


like image 370
user-8564775 Avatar asked Oct 27 '14 05:10

user-8564775


Video Answer


1 Answers

How do you set the claims for the users when they login I believe you are missing this line of code in method GrantResourceOwnerCredentials

 var identity = new ClaimsIdentity(context.Options.AuthenticationType);
 identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
 identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
 identity.AddClaim(new Claim(ClaimTypes.Role, "Supervisor"));

And if you want to create the identity from DB use the below:

 public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
        // Add custom user claims here
        return userIdentity;
    }

Then in GrantResourceOwnerCredentials do the below:

ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
like image 183
Taiseer Joudeh Avatar answered Sep 28 '22 03:09

Taiseer Joudeh