2013-11-22 19 views
3

我需要一些幫助。我怎樣才能訪問當前經過身份驗證的用戶/ ClaimsPrincipal。在過去,我會使用HttpContext.Current,但現在看來似乎錯了。CurrentUser/ClaimsPrincipal

回答

0

在什麼情況下你想訪問它?我將從一個發佈OAuth2令牌的Web API服務的角度回答問題,因爲那正是我剛剛編程時的情況。如果這不是你的情況,請給我們你的具體情況。

如果你想驗證的用戶因此可以發出令牌,你已經覆蓋OAuthAuthorizationServerProvider,你會在context.Request.User,其中context是參數重寫的方法找到它。

在繼承自ApiController(在ASP.NET Web API中)的類中,您可以檢查this.User。這將是您放入OAuth2令牌的ClaimsPrincipal

11

使用OWIN,用戶可以在OWIN上下文的Authentication.User屬性中找到。

OwinContext context = Request.GetOwinContext(); 
ClaimsPrinicipal user = context.Authentication.User; 
// do stuff with user. 

布羅克艾倫有一個post on using cookie authentication with OWIN

+2

如果您已添加到用戶的配置文件中,如何使用所有配置文件信息訪問User對象?或者另一種問它的方式是你的方法獲得'ClaimsPrincipal'對象。我如何獲得完全水分的「IdentityUser」對象?我知道我可以通過UserManager獲取它,但我不想在每次需要用戶時調用該方法。這是唯一的方法嗎? – Bloodhound

3

如果您使用Web Api 2,您現在應該使用RequestContext.Principal來滿足您的任何身份檢查/分配需求。