我有一個 .net 6 web api,當我嘗試使用以下配置獲取當前用戶 ID 時,總是回傳 null。
//in api controller
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
//in Program.cs
services.Configure<IdentityOptions>(options =>
options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);
services.AddHttpContextAccessor();
有什么想法可以解決嗎?
提前致謝。
uj5u.com熱心網友回復:
由于您配置了 IdentityOptions 選項,我假設您正在使用 Asp.net Core Identity 進行身份驗證和授權,對嗎?
我創建了一個 Asp.net 核心應用程式并使用 Asp.net 核心身份,使用您的代碼配置身份選項后,我可以獲得用戶 ID。結果如下:
為什么 User.FindFirstValue(claimtypes.nameidentifier) 總是回傳 null?
關于這個問題,可能由以下原因引起:
當您請求 API 端點時,請求不包括具有名稱識別符號宣告的 JWT 令牌或 cookie。您需要在請求 API 端點時添加 JWT 令牌或 cookie。
在這種情況下,你可以使用 F12 開發者網路工具來檢查請求頭是否有 cookie 或 Authorization 頭,參考這個截圖(它使用 cookie 來存盤身份資訊):
JWT 令牌或 cookie 不包含名稱識別符號宣告。
您可以設定一個斷點來檢查用戶的宣告,是否可以找到名稱識別符號宣告。在此螢屏截圖中,我使用的是 Asp.net core Identity,只需添加以下代碼:
services.Configure<IdentityOptions>(options => options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);
如果用戶的宣告不包含名稱識別符號宣告,則問題可能與代碼的登錄部分有關,最好共享相關代碼。
檢查中間件
app.UseAuthentication()
,app.UseAuthorization()
確保您已在 Program.cs 或 Startup.cs 中正確添加它們。像這樣的代碼:
如果上述方法仍然不起作用,請分享詳細步驟和代碼,或者您可以創建一個最小、完整的示例來重現問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/525795.html
標籤:asp.net 核心asp.net-core-webapi.net-6.0
上一篇:如何從應用程式中訪問配置選項?