2014-08-29 68 views
1

我在新發布的書ASP.NET Web Api 2 Recipes中使用食譜10-3來支持Web API中的基本身份驗證。這個食譜使用Thinktecture的第三方庫。從下面的代碼可以看出,我使用用戶身份驗證自己的帳戶服務。ASP.NET Web API中基於角色的授權 - 如何在主體上設置角色?

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() 
{ 
    ... 
} 

我的帳戶服務顯然知道有關用戶及其分配的角色,但這些信息是不可用授權attibute(角色未在委託人身上設置)。

我該如何做到這一點? Thinktecture身份驗證處理程序可以配置爲在主體上設置角色嗎?或者我應該創建自己的自定義授權屬性(派生自Authorize屬性)?如果是這樣,我是否應該重寫OnAuthorization方法以使用我的帳戶服務創建和設置主體?或者直接重寫IsAuthorized方法?或者也許別的東西...

回答

2

我發現AddBasicAutentication方法實際上有一個需要委託來提供角色的重載。這正是我所期待的。所以現在呼叫AddBasicAuthentication看起來像這樣,並且一切都像一個魅力:

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

大聲笑。完全忘記了這一點。儘管如此,OWIN方法更受推薦。 – leastprivilege 2014-08-31 09:30:20

+0

它可以幫助很大,但在我的Thinktecture中,AddBasicAuthentication()沒有重載(版本3.6.1.0)。你是什​​麼? – 2015-03-27 08:32:03

+0

我的ThinkTecture AuthenticationHanlder版本來自NuGet軟件包版本1.1.0 ... – 2015-03-27 09:26:22

3

AuthenticationHandler只進行身份驗證。您需要在單獨的步驟中設置角色(例如,在委派處理程序中)。

如果你的Web API第2版 - 我寧願建議切換到基本身份驗證OWIN中間件

https://github.com/thinktecture/Thinktecture.IdentityModel/tree/master/source/Thinktecture.IdentityModel.Owin.BasicAuthentication

這使您時生成的主要的完全控制。

https://github.com/thinktecture/Thinktecture.IdentityModel/blob/master/samples/OWIN/AuthenticationTansformation/KatanaAuthentication/Startup.cs

還有一個的NuGet。

+0

如何在一個單獨的步驟中設置角色?在我的版本(最新)沒有允許分配角色委託'AddBasicAuthentication((userName,password)=> accountService.Authenticate(userName,password),(username)=> accountService.GetRoles(username));' – 2015-03-27 10:52:26