ASP.NET Web Api 具有基于角色的授权

ASP.NET Web Api with Role based authorization

我正在使用 Web API 2 和基于 OWIN 令牌的身份验证。唯一不起作用的是基于角色的授权。

在我的 AuthorizationServerProvider.GrantResourceOwnerCredentials 实施中,这是我分配角色的方式:

identity.AddClaim(client.ApplicationType == ApplicationTypes.WebClient
            ? new Claim(ClaimTypes.Role, "user")
            : new Claim(ClaimTypes.Role, "admin"));

但在使用 [Authenticate(Roles="user")] 的控制器中,只是 returns 向客户端发送授权拒绝消息。我检查了变量,这是里面的内容

所以角色似乎在那里,但是 user.Claims 是空的并且 IsInRole("user") 也 returns 负数。

我在这里发现了几个关于 Whosebug 和逻辑方面的问题,我没有看到我错过了什么。我唯一想到的是覆盖授权命令,但这是不必要的,因为基于角色的授权似乎已经集成...

编辑:这是我的工作方法的样子:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin") ?? "*";
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

    Client client;
    using (var repo = new AuthRepository())
    {
        client = repo.FindClient(context.ClientId);
        if (client.ApplicationType != ApplicationTypes.Service)
        {
            var user = await repo.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect." + context.UserName);
                return;
            }
        }
}

不要直接添加角色声明,而是使用 UserManager:

UserManagerInstance.AddToRole(userId, "admin");

这样角色将被保留(到 AspNetUserRoles 或您配置的任何内容),以便以后的请求。如果您直接添加声明,则不会发生这种情况,因为您将其添加到您的用户身份的 "instance" 中,它将随着当前请求而消失。

回答您的进一步要求:

如果您希望在票证上编纂声明,则必须在按照您的方式添加声明后执行此操作(在 GrantResourceOwnerCredentials 中):

var props = new AuthenticationProperties(new Dictionary<string, string>
        {
            { "userId", "blah,blah" },
            { "role", "admin" }
        });

var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);

这样您就不必"persist"这类用户

当然,您必须重写 OAuthAuthorizationServerProvider 的 TokenEndpoint 方法,以便稍后 request/responses.

检索这些数据
    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }

        return Task.FromResult<object>(null);
    }

可能以某种方式解决了它,但对我来说,如果我这样说就可以了:

[Authorize(Roles = "user")]
[Route("")]
[HttpGet]
public async Task<IHttpActionResult> GetUserSpecificServers() { ... }