首页 文章

ASP.NET Web API中基于角色的授权 - 如何在主体上设置角色?

提问于
浏览
1

我在新发布的书籍ASP.NET Web Api 2 Recipes中使用配方10-3来支持我的Web API中的基本身份验证 . 该配方使用了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属性在我的控制器中进行基于角色的授权:

[Authorize(Roles="administrator")]
public IHttpActionResult Get()
{
    ...
}

我的帐户服务显然知道用户及其分配的角色,但授权属性无法使用此信息(角色未在主体上设置) .

我该如何做到这一点?可以将Thinktecture身份验证处理程序配置为在主体上设置角色吗?或者我应该创建自己的自定义Authorize属性(从Authorize属性派生)?如果是这样,我应该覆盖OnAuthorization方法来使用我的帐户服务创建和设置主体吗?或者直接覆盖IsAuthorized方法?或者别的什么......

2 回答

相关问题