【发布时间】:2015-11-18 09:08:11
【问题描述】:
我正在使用基于 OWIN 令牌的身份验证的 Web API 2。唯一不起作用的是基于角色的授权。
在我的 AuthorizationServerProvider.GrantResourceOwnerCredentials 实现中,这是我分配角色的方式:
identity.AddClaim(client.ApplicationType == ApplicationTypes.WebClient
? new Claim(ClaimTypes.Role, "user")
: new Claim(ClaimTypes.Role, "admin"));
但在控制器中使用 [Authenticate(Roles="user")] 只是向客户端返回授权被拒绝消息。我检查了变量,这就是里面的内容
所以角色似乎在那里,但是 user.Claims 是空的,并且 IsInRole("user") 也返回负数。
我在 stackoverflow 上发现了几个问题,从逻辑上讲,我看不出我错过了什么。我唯一想到的是覆盖授权命令,但这有点不必要,因为基于角色的授权似乎已经集成......
编辑:这就是我的工作方法的样子:
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;
}
}
}
【问题讨论】: