在ASP.NET的Web API,基于角色的授权 - 如何设置的主要角色? [英] Role-based authorization in ASP.NET Web API - how to set roles on the principal?
问题描述
我使用的配方10-3新近发布的书 ASP.NET网页API 2食谱,以支持我的Web API基本身份验证。这个配方利用了Thinktecture第三方库。正如从下面的code看到的,我对身份验证我自己的帐户服务的用户。
I am using recipe 10-3 in the newly released book ASP.NET Web Api 2 Recipes to support basic authentication in my Web API. This recipe utilizes a 3rd party library from Thinktecture. As seen from the below code, I am authentication the user against my own account service.
using Thinktecture.IdentityModel.WebApi.Authentication.Handler;
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...
var authenticationConfiguration = new AuthenticationConfiguration();
var accountService = ServiceLocator.Get<AccountService>();
authenticationConfiguration.AddBasicAuthentication((userName, password) => accountService.Authenticate(userName, password));
config.MessageHandlers.Add(new AuthenticationHandler(authenticationConfiguration));
...
}
}
现在我想使基于角色的授权使用授权的属性我控制器:
Now I want to make role-based authorization in my controllers using the Authorize attribute:
[Authorize(Roles="administrator")]
public IHttpActionResult Get()
{
...
}
我的帐户服务显然知道有关用户及其分配的角色,但这些信息是不提供给授权attibute(角色没有设置本金)。
My account service obviously knows about the users and their assigned roles, but this information is not available to the Authorize attibute (the roles are not set on the principal).
我如何做到这一点?可以Thinktecture认证处理器配置上设置的主要角色?或者我应该让自己的自定义属性授权(从授权属性派生)?如果是这样,我应该重写OnAuthorization方法来创建并使用自己的帐户设置服务主体?或者,也许直接覆盖IsAuthorized方法?或者,也许别的东西...
How do I accomplish this? Can the Thinktecture authentication handler be configured to set the roles on the principal? Or should I make my own custom Authorize attribute (deriving from the Authorize attribute)? And if so, should I override the OnAuthorization method to create and set the principal using my account service? Or maybe override the IsAuthorized method directly? Or maybe something else...
推荐答案
我发现了AddBasicAutentication方法实际上有一个重载,接受委托提供的角色。这正是我一直在寻找。所以,现在的呼叫AddBasicAuthentication看起来像这样,一切就像一个魅力:
I found out that the AddBasicAutentication method actually has an overload that takes a delegate for providing the roles. This is exactly what I was looking for. So now the call to AddBasicAuthentication looks like this, and everything works like a charm:
authenticationConfiguration.AddBasicAuthentication((userName, password) => accountService.Authenticate(userName, password), (username) => accountService.GetRoles(username));
这篇关于在ASP.NET的Web API,基于角色的授权 - 如何设置的主要角色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!