1

我有一個自定義授權屬性,它驗證頭中的令牌並設置用戶主體。.NET Web Api 2 UserPrincipal.IsAuthenticated在使用依賴注入(Unity)時始終爲false

//when token is validated 
var userIdentityBase = new UserIdentityBase(token); <-- Inherited GenericIdentity 
IPrincipal principal = new GenericPrincipal(userIdentityBase, null); 

actionContext.Request.GetRequestContext().Principal = principal; 
HttpContext.Current.User = principal; 
Thread.CurrentPrincipal = principal; 

當我檢查身份的內部控制器 enter image description here

但是,當我注入的IPrincipal我的服務類,它不工作了,這工作得很好。 IsAuthenticated是錯誤的。

統一設置代碼:

container.RegisterType<IPrincipal>(new InjectionFactory(u => HttpContext.Current.User)); 

注射時,它不工作(包括屏幕截圖採取withing相同的請求): enter image description here

有什麼建議?

+0

依賴關係解析程序正在解決應用程序啓動的依賴關係。在當時沒有當前用戶 –

+0

@MarcusH,所以沒有辦法在運行時注入用戶主體? – Robert

+0

我不認爲有,但我沒有事實來支持。我已經通過將用戶作爲參數或將靜態變量設置爲當前用戶來解決此問題。 –

回答

0

我已經通過創建自己的接口和實現來解決這個問題,它將在運行時提取用戶身份。就像我的情況

接口

public interface IIdentityProvider 
{ 
    IPrincipal GetPrincipal(); 
} 

實現一個魅力:

public class IdentityProvider : IIdentityProvider 
{ 
    public IPrincipal GetPrincipal() 
    { 
     return HttpContext.Current.User; 
    } 
} 

統一登記:

container.RegisterType<IIdentityProvider, IdentityProvider>(); 

與用法:

IIdentityProvider _identityProvider; 
public BookingRecordService(IIdentityProvider identityProvider) 
{ 
    _identityProvider = identityProvider; 

    var isAuth = _identityProvider.GetPrincipal().Identity.IsAuthenticated; 
}