我正在使用新发布的“ASP.NET网络应用程序2”一书中的配方10-3来支持Web中的基本身份验证。这个食谱使用了一个来自Thinktecture的第三方库。从下面的代码中可以看出,我正在根据自己的帐户服务对用户进行身份验证。
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));
...
}
}现在,我希望在控制器中使用授权属性进行基于角色的授权:
[Authorize(Roles="administrator")]
public IHttpActionResult Get()
{
...
}我的帐户服务显然知道用户和他们分配的角色,但是这些信息不能提供给授权代理(角色没有设置在主体上)。
我怎样才能做到这一点?可以将Thinktecture身份验证处理程序配置为在主体上设置角色吗?或者我应该创建我自己的自定义授权属性(派生自授权属性)?如果是这样的话,我应该重写OnAuthorization方法来使用我的帐户服务创建和设置主体吗?或者直接覆盖IsAuthorized方法?或者别的什么..。
发布于 2014-08-30 22:27:31
我发现AddBasicAutentication方法实际上有一个重载,需要一个委托来提供角色。这正是我要找的。因此,现在对AddBasicAuthentication的调用看起来是这样的,所有的事情都很有魅力:
authenticationConfiguration.AddBasicAuthentication((userName, password) => accountService.Authenticate(userName, password), (username) => accountService.GetRoles(username));发布于 2014-08-30 09:09:20
AuthenticationHandler只进行身份验证。您需要在单独的步骤中设置角色(例如,在委托处理程序中)。
如果您使用的是Web v2,我建议您切换到基本的auth中间件。
这使您完全控制创建的主体。
这里也有一个努基特。
https://stackoverflow.com/questions/25572870
复制相似问题