我正在使用带有.Net Core 2.1的JWT,以及
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
我的控制器类上的装饰器。 在 2.0 中,您似乎必须执行以下操作,但现在它被标记为过时:
var authenticateInfo = await HttpContext.Authentication.GetAuthenticateInfoAsync("Bearer");
string accessToken = authenticateInfo.Properties.Items[".Token.access_token"];
我已经看到了其他一些相当迂回的扩展授权类的方法,以及我宁愿避免的方法。 我只是想像我编码它们一样访问令牌的详细信息,例如.我添加的子和自定义声明,如"名称"和"角色"。 如何在.Net Core 2.1中执行此操作?
尝试将HttpContext.User.Identity
转换为ClaimsIdentity
。
claimsIdentity = User.Identity as ClaimsIdentity;
// alternatively
// claimsIdentity = HttpContext.User.Identity as ClaimsIdentity;
// get some claim by type
var someClaim = claimsIdentity.FindFirst("some-claim");
// iterate all claims
foreach (var claim in claimsIdentity.Claims)
{
System.Console.WriteLine(claim.Type + ":" + claim.Value);
}
下面是支持HttpContext.User.Identity
属性的.NET Core特定文档。
- HttpContext
- HttpContext.User
- 索赔主体
- ClaimsPrincipal.Identity
无需投射,至少如果您使用的是.Net Core 3.1
.只需从控制器访问如下值:
var nameIdentifier = User.FindFirst(ClaimTypes.NameIdentifier);
var name = User.FindFirst(ClaimTypes.Name);
var givenName = User.FindFirst(ClaimTypes.GivenName);
var surname = User.FindFirst(ClaimTypes.Surname);
var email = User.FindFirst(ClaimTypes.Email);
var mobilePhone = User.FindFirst(ClaimTypes.MobilePhone);
var authenticationMethod = User.FindFirst(ClaimTypes.AuthenticationMethod);
var emails = User.FindFirst("emails");
从access_token中,您可以读取如下值:
var handler = new JwtSecurityTokenHandler();
var jwtSecurityToken = handler.ReadJwtToken(adb2cTokenResponse.access_token);
var givenName = jwtSecurityToken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.GivenName).Value;
var familyName = jwtSecurityToken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.FamilyName).Value;
//Unless Alternate email have been added in Azure AD there will only be one email here.
//TODO Handle multiple emails
var emails = jwtSecurityToken.Claims.First(claim => claim.Type == ADB2CJwtRegisteredClaimNames.Emails).Value;
public struct ADB2CJwtRegisteredClaimNames
{
public const string Emails = "emails";
public const string Name = "name";
}