2015-12-30 37 views
4

在ASP.NET 5 MVC 6 RC1中,如何從控制器或過濾器中檢索AuthenticationPropertiesHttpContext.Authentication似乎沒有此功能。在ASP.NET 5中獲取AuthenticationProperties

我想過註冊一個CookieAuthenticationEvents.OnValidatePrincipal處理程序,然後在CookieValidatePrincipalContext參數上使用Properties屬性。然後,我可以將這些AuthenticationProperties存儲在請求緩存中,以便稍後我可以獲得諸如IssuedUtc之類的內容。

有沒有更好的解決方案,我不需要自己存儲這個?

我沒有使用ASP.NET標識,而是將cookie中間件作爲獨立使用。

回答

4

在ASP.NET 5,檢索驗證屬性是有點麻煩,因爲它必須通過實例的AuthenticateContext來完成:

var context = new AuthenticateContext("[your authentication scheme]"); 
await HttpContext.Authentication.AuthenticateAsync(context); 

if (context.Principal == null || context.Properties == null) { 
    throw new InvalidOperationException("The request is not authenticated."); 
} 

var properties = new AuthenticationProperties(context.Properties); 
+0

這是否有任何副作用(AuthenticateAsync似乎嚇人)?我可以在請求期間多次執行此操作嗎?任何性能缺陷? – user764754

+1

沒有副作用,儘管這不是保證(因爲你完全可以自由地實現自己的處理程序並添加自定義邏輯)。你當然可以多次調用它。由於缺省的認證處理程序(如cookies中間件)返回緩存的結果,因此影響應該幾乎沒有引起注意:隨後的'AuthenticateAsync'調用應該非常快。 – Pinpoint