2017-09-10 343 views
0

我在我的Web API項目中使用HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value以獲取請求用戶,以用於身份驗證。 NameIdentifier返回當前用戶的電子郵件,而谷歌搜索建議它應該返回用戶的ID(Guid,在這種情況下,如果這很重要)。
爲什麼會發生這種情況,以及如何在沒有數據庫查詢的情況下返回當前用戶的ID?ClaimTypes.NameIdentifier返回的電子郵件地址不是Id

+0

啓動文件並在應用程序中使用什麼身份驗證機制?什麼創建了ClaimsPrincipal?它是.NET Core 2.0嗎? –

+0

是的,它是.NET Core 2.0。我正在使用JwtBearer進行身份驗證。我對ClaimsPrinciple不熟悉,所以我認爲JwtBearer正在處理這個問題? –

+0

對不起,我的身份驗證(使用JwtBeaer作爲jwt令牌) –

回答

0

我一直在使用ASP.net核心2.0面臨同樣的問題,因爲我產生JWT令牌這樣

public ClaimsIdentity GenerateClaimsIdentity(string email, string id) 
{ 
    return new ClaimsIdentity(new GenericIdentity(email, "Token"), new[] 
    { 
     new Claim(Helpers.Constants.Strings.JwtClaimIdentifiers.Id, id), 
     new Claim(Helpers.Constants.Strings.JwtClaimIdentifiers.Rol, Helpers.Constants.Strings.JwtClaims.ApiAccess) 
    }); 
} 

我試圖讓通過UserManagerCurrentUser但它總是返回null。我已經想通改變UserIdClaimType字符串「ID」,在這樣的

var builder = services.AddIdentity<User,IdentityRole>(o => 
{ 
    // configure identity options 
    o.Password.RequireDigit = false; 
    o.Password.RequireLowercase = false; 
    o.Password.RequireUppercase = false; 
    o.Password.RequireNonAlphanumeric = false; 
    o.Password.RequiredLength = 6; 

    //this line 
    o.ClaimsIdentity.UserIdClaimType = "id"; 
});