2016-07-15 142 views
1

我正在使用基于OWIN令牌的Web API 2验证。除了基于角色的授权之外,一切进展顺利。授权错误 - 基于令牌的授权和角色的ASP.NET Web API

这里是我的控制器:

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

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

的问题如下:我登录我的应用程序与具有角色admin用户,但我得到授权错误401尝试注册时。我已经纠正了我用来登录的AspNetUser是AspNetUserRoles表中的管理员。

这里是我的GrantResourceOwnerCredentials方法:

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); 

    } 
+0

为了调试的目的,您可以删除Authorize属性,然后在方法中调用User.IsInRole(“Admin”)'并且遍历所有声明以查看用户是否真的是Admin组的一部分。 – Michael

+0

我已经调试过,IsInRole说我的用户不属于管理员组。有什么可能错误或失踪? –

回答

0

你可以检查,看看是否“管理”权利要求书,你的API方法解决...

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

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

的授权属性不明白索赔。它查找Admin作为角色,因此它调用IPrincipal接口的“User.IsInRole”方法。

为了进行这项工作,您需要在您的owin管道中添加声明作为角色并分配给HttpContext.Current.User。