Blazor WebApi身份信息



我在从API中获取用户标识信息时遇到问题。我的项目由一个独立的WASM应用程序、IDP和WebApi组成。

我已经设置好了一切,它也能工作,但我要做的是Blazor客户端的调用,从api中获取一些数据。Api然后使用用户的电子邮件地址来识别他们,并为他们获取数据。

我研究过类似的问题,但这些解决方案对我的项目不起作用。

[HttpGet("GetData")]
public async Task<IActionResult> GetData()
{
string test = User.Identity.Name; // returns null
string username = "myuser@users.com";
List<string> data= new List<string>();
data= (await _dataRepository.GetData(username)).ToList();
if (data.Count > 0)
{
return Ok(data);
}
else
{
return NoContent();
}
}

那么,在我设置用户名的地方,有没有办法获得通过请求的用户的电子邮件?

已编辑访问令牌:

{
"alg": "RS256",
"kid": "2D49329C75FC43C78590AF6F6A0EFDB2",
"typ": "at+jwt"
}
{
"nbf": 1639243158,
"exp": 1639246758,
"iss": "https://localhost:5000",
"aud": "https://localhost:5000/resources",
"client_id": "ATS",
"sub": "4892725f-f6da-4a28-827a-ce666bb6f098",
"auth_time": 1638729064,
"idp": "local",
"jti": "53CB2F8FCB2EB34E3501E2C210B59B5D",
"sid": "8463E4AA74D7369C1176249ED8FA46B1",
"iat": 1639243158,
"scope": [
"openid",
"profile",
"MY_API"
"email"
],
"amr": [
"pwd"
]
}

首先,您通常会使用[Authorize(…(]属性来保护控制器操作方法的安全,并在ASP.NET Core中查找授权以获取更多详细信息。

其次,当找不到姓名/电子邮件时,最常见的问题是您需要使用打开索赔映射

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();

这是因为默认情况下,Microsoft和OpenID对声明名称有不同的意见,因此,明智的做法是首先清除此映射,然后通过设置以下内容告诉Microsoft名称/角色声明的名称:

opt.TokenValidationParameters.RoleClaimType = "roles";
opt.TokenValidationParameters.NameClaimType = "name";

有关索赔映射的更多详细信息,请访问:

https://learn.microsoft.com/en-us/aspnet/core/security/authentication/claims?view=aspnetcore-6.0

相关内容

最新更新