2016-02-29 52 views
1

問題Identity.GetUserId()如何找到用戶標識?

User.Identity.GetUserId()如何找到當前用戶的ID?

它是否從Cookie中找到用戶標識,還是查詢數據庫?或者其他方法?

問題

出於某種原因,User.Identity.GetUserId()回報null當我添加一個有效Bearer Token我的HTTP請求頭和請求發送到我的控制器的端點:

// MVC Controller Action Method 

[Authorize] 
public HttpResponseMessage(UserInfoViewModel model) 
{ 
    // Request passes the Authorization filter since a valid oauth token 
    // is attached to the request header. 

    string userId = User.Identity.GetUserId(); 

    // However, userId is null! 

    // Other stuff... 
} 
+0

你使用什麼驗證方法?它可以是匿名認證? – enkryptor

回答

3

當用戶登錄到您的應用程序時,服務器使用ASP.NET身份驗證您的用戶使用數據庫並創建返回到UI的有效令牌。此令牌在其到期時有效,並具有驗證和授權用戶所需的所有信息,包括用戶的ID。接下來從客戶端到服務器端的調用必須在http請求頭中使用此令牌完成,但服務器不會再次調用數據庫,因爲ASP.NET身份知道如何解密令牌並獲取用戶的所有信息。

Cookie的使用只是將令牌存儲在客戶端的一種方式。正如我上面評論的那樣,您必須在登錄後的下一個請求中發送令牌,以便您可以將此令牌存儲在Cookie中或存儲在瀏覽器中的會話存儲中。

1

首先,確保你'不允許未經過身份驗證的用戶。

之後,你想解析承載令牌,你必須配置它。

你會需要這個包在啓動時Microsoft.Owin.Security.OAuth

如果必須配置ASP.NET身份使用承載認證與:

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { 
    // your options; 
}); 

也許您StartupAuth.cs文件

2

User.Identity.GetUserId()如何找到當前用戶的ID?

ClaimTypes.NameIdentifier是由函數User.Identity.GetUserId()

您將需要添加的要求在您的授權代碼中使用的要求,

identity.AddClaim(ClaimTypes.NameIdentifier, user.Id); 

身份類型ClaimIdentity。