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

Asp.net web api ASP.NET Web API中基于角色的授权-如何在主体上设置角色?,asp.net-web-api,thinktecture-ident-model,Asp.net Web Api,Thinktecture Ident Model,我在最新出版的书中使用配方10-3来支持我的Web API中的基本身份验证。此配方使用Thinktecture的第三方库。从下面的代码中可以看出,我正在根据我自己的帐户服务对用户进行身份验证 using Thinktecture.IdentityModel.WebApi.Authentication.Handler; public static class WebApiConfig { public static void Register(HttpConfiguration conf

我在最新出版的书中使用配方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));

        ...
   }
}
My account service显然知道用户及其分配的角色,但Authorize attibute无法获得此信息(角色未在主体上设置)


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

AuthenticationHandler只进行身份验证。您需要在单独的步骤中设置角色(例如,在委托处理程序中)

如果您使用的是WebAPIv2,我建议您切换到基本的auth-OWIN中间件

这使您能够完全控制创建的主体


还有一个nuget。

AuthenticationHandler只进行身份验证。您需要在单独的步骤中设置角色(例如,在委托处理程序中)

如果您使用的是WebAPIv2,我建议您切换到基本的auth-OWIN中间件

这使您能够完全控制创建的主体


还有一个nuget。

我发现AddBasicAuthentication方法实际上有一个重载,它使用一个委托来提供角色。这正是我想要的。因此,现在调用AddBasicAuthentication如下所示,一切都像一个符咒:

authenticationConfiguration.AddBasicAuthentication((userName, password) => accountService.Authenticate(userName, password), (username) => accountService.GetRoles(username));

我发现AddBasicAuthentication方法实际上有一个重载,它使用一个委托来提供角色。这正是我想要的。因此,现在调用AddBasicAuthentication如下所示,一切都像一个符咒:

authenticationConfiguration.AddBasicAuthentication((userName, password) => accountService.Authenticate(userName, password), (username) => accountService.GetRoles(username));

哈哈,完全忘了。尽管如此,还是建议使用OWIN方法。它可能会有很大帮助,但在我的ThinkStructure中,AddBasicAuthentication()没有重载。。。版本3.6.1.0。你的是什么?我的ThinkTecture AuthenticationHanlder版本来自NuGet软件包版本1.1.0…哈哈。完全忘记了。尽管如此,还是建议使用OWIN方法。它可能会有很大帮助,但在我的ThinkStructure中,AddBasicAuthentication()没有重载。。。版本3.6.1.0。你的是什么?我的ThinkTecture AuthenticationHanlder版本来自NuGet软件包版本1.1.0…我如何在单独的步骤中设置角色?在我的最新版本中,没有允许分配角色的重载委托
AddBasicAuthentication((用户名,密码)=>accountService.Authentication(用户名,密码),(用户名)=>accountService.GetRoles(用户名))如何在单独的步骤中设置角色?在我的最新版本中,没有允许分配角色的重载委托
AddBasicAuthentication((用户名,密码)=>accountService.Authentication(用户名,密码),(用户名)=>accountService.GetRoles(用户名))