简体   繁体   English

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

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

I am using Web API 2 with OWIN token based authentication. 我使用Web API 2与基于OWIN令牌的身份验证。 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. 问题如下:我使用具有角色Admin的用户登录了我的应用程序,但在尝试注册时遇到了未经授权的错误401。 I already rectified that the AspNetUser that I am using to log in is an Admin in AspNetUserRoles table. 我已经纠正了我用来登录的AspNetUser是AspNetUserRoles表中的Admin。

Here is my GrantResourceOwnerCredentials method: 这是我的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);

    }

Can you check to see if the "Admin" claims is resolved in your api method ... 你能检查一下你的api方法是否解决了“Admin”声明...

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. Authorize属性不了解声明。 It looks for Admin as a role, so it invokes "User.IsInRole" method of the IPrincipal interface. 它将Admin视为角色,因此它调用IPrincipal接口的“User.IsInRole”方法。

In order for this work you would need to add the claims as roles in your owin pipeline and assign to HttpContext.Current.User. 为了完成这项工作,您需要在owin管道中将声明添加为角色并分配给HttpContext.Current.User。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM