我将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”)]的Controller中,它只会向客户端返回一条“拒绝授权”消息。我检查了变量,这是里面的内容
因此角色似乎在那里,但是user.Claims为空,IsInRole(“ user”)也返回负数。
我在这里发现了一些有关stackoverflow和逻辑方面的问题,我看不到我错过的内容。我唯一想到的就是覆盖Authorize Command,但这是不必要的,因为基于角色的授权似乎已经集成了...
编辑:这是我的工作方法看起来像:
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或您配置的任何对象),以便以后的请求可以使用。如果直接添加声明,则不会发生这种情况,因为您是将声明添加到用户身份的“实例”中,该实例将随当前请求一起消失。
回答您的更多要求:
如果您希望将索赔要求编入票证,则必须在按照自己的方式添加索赔要求之后执行此操作(在GrantResourceOwnerCredentials中):
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{ "userId", "blah,blah" },
{ "role", "admin" }
});
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
这样,您就不必“坚持”这类用户
当然,您将必须重写OAuthAuthorizationServerProvider的TokenEndpoint方法,以便在以后的请求/响应中检索这些数据。
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句