【问题标题】:Authorize Error - ASP.NET Web API with Token based authorization and Roles授权错误 - 具有基于令牌的授权和角色的 ASP.NET Web API
【发布时间】:2016-11-18 18:56:00
【问题描述】:

我正在使用基于 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)
    {
      ...............

问题如下:我使用具有管理员角色的用户登录我的应用程序,但在尝试注册时收到未经授权的错误 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);

    }

【问题讨论】:

  • 我已经调试过了,IsInRole 说我的用户不属于管理员组。有什么错误或遗漏的?

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


【解决方案1】:

您能否检查一下“管理员”声明是否在您的 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
}

Authorize 属性不理解声明。它将 Admin 作为角色查找,因此它调用 IPrincipal 接口的“User.IsInRole”方法。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 2020-05-18
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    相关资源
    最近更新 更多