授权错误 - 具有基于令牌的授权和角色的ASP.NET Web API

时间:2016-07-15 14:09:24

标签: c# asp.net asp.net-web-api token owin

我正在使用基于OWIN令牌的Web API 2进行身份验证。一切顺利,除了基于角色的授权。

这是我的控制器:

[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表中的Admin。

这是我的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);

    }

1 个答案:

答案 0 :(得分:0)

你能检查一下&#34; Admin&#34;索赔在您的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视为一个角色,因此它会调用&#34; User.IsInRole&#34; IPrincipal接口的方法。

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