简体   繁体   中英

Authorize Error - ASP.NET Web API with Token based authorization and Roles

I am using Web API 2 with OWIN token based authentication. All is going well except authorization based on Roles.

Here is my controller:

[Authorize(Roles = "Admin")]
[RoutePrefix("api/Account")]   
public class AccountController : ApiController
{
    ..............

    // POST api/Account/Register
    //[AllowAnonymous]
    [Route("Register")]
    public async Task<IHttpActionResult> Register(AppUser user)
    {
      ...............

The problem is the following: I logged in my application with a user that has role Admin but I get unauthorized error 401 when trying to register. I already rectified that the AspNetUser that I am using to log in is an Admin in AspNetUserRoles table.

Here is my GrantResourceOwnerCredentials method:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        using (AuthRepository _repo = new AuthRepository(new GloboStudioUniversityContext()))
        {
            IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }


        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        //identity.AddClaim(new Claim("role", "user"));
        identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
        identity.AddClaim(new Claim(ClaimTypes.Role, "Student"));
        identity.AddClaim(new Claim(ClaimTypes.Role, "Candidate"));

        context.Validated(identity);

    }

Can you check to see if the "Admin" claims is resolved in your api method ...

var identity = User.Identity as ClaimsIdentity;
var claim = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role && c.Value == "Admin");

if (claim == null) {
  //Raise 401
}

The Authorize attribute does not understand claims. It looks for Admin as a role, so it invokes "User.IsInRole" method of the IPrincipal interface.

In order for this work you would need to add the claims as roles in your owin pipeline and assign to HttpContext.Current.User.

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