2014-08-29 3 views
1

내 웹 API에서 기본 인증을 지원하기 위해 새로 출시 된 책 ASP.NET Web Api 2 Recipes에서 제조법 10-3을 사용하고 있습니다. 이 제조법은 Thinktecture의 타사 라이브러리를 사용합니다. 아래 코드에서 알 수 있듯이 사용자를 내 계정 서비스에 대해 인증합니다.ASP.NET 웹 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 특성에서 파생 된 사용자 지정 Authorize 특성을 만들어야합니까? 그렇다면 OnAuthorization 메서드를 재정 의하여 내 계정 서비스를 사용하여 주체를 만들고 설정해야합니까? 아니면 직접 IsAuthorized 메서드를 재정의 할 수 있습니까? 아니면 뭔가 다른 ...

답변

2

AddBasicAutentication 메서드에는 실제로 역할을 제공하기위한 대리자를 사용하는 오버로드가 있음을 알게되었습니다. 이것은 내가 찾고 있었던 바로 그 것이다. 이제 AddBasicAuthentication에 대한 호출이 이렇게 보입니다. 모든 것이 매력처럼 작동합니다.

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

롤. 그 사실을 완전히 잊었습니다. 여전히 - OWIN 방식이 더 권장됩니다. – leastprivilege

+0

많은 도움이 될 수 있지만 내 Thinktecture에는 AddBasicAuthentication()에 대한 과부하가 없습니다 ... 버전 3.6.1.0. 너 뭐야? –

+0

내 ThinkTecture AuthenticationHanlder 버전은 NuGet 패키지 버전 1.1.0입니다 ... –

3

AuthenticationHandler는 인증 만 수행합니다. 별도의 단계 (예 : 위임 처리기)에서 역할을 설정해야합니다.

당신이 웹 API v2에서 경우 - 차라리 기본 인증의 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)); ' –