簡體   English   中英

授權錯誤 - 具有基於令牌的授權和角色的ASP.NET Web API

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

我使用Web API 2與基於OWIN令牌的身份驗證。 一切順利,除了基於角色的授權。

這是我的控制器:

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

    }

你能檢查一下你的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
}

Authorize屬性不了解聲明。 它將Admin視為角色,因此它調用IPrincipal接口的“User.IsInRole”方法。

為了完成這項工作,您需要在owin管道中將聲明添加為角色並分配給HttpContext.Current.User。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM