Gli*_*kot 7 c# jwt asp.net-core asp.net-core-webapi
我正在使用JWT和.Net Core 2.1,以及
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
Run Code Online (Sandbox Code Playgroud)
我的控制器类上的装饰器.在2.0中,您似乎必须执行以下操作,但现在已标记为已废弃:
var authenticateInfo = await HttpContext.Authentication.GetAuthenticateInfoAsync("Bearer");
string accessToken = authenticateInfo.Properties.Items[".Token.access_token"];
Run Code Online (Sandbox Code Playgroud)
我已经看到了一些其他相当迂回的扩展授权类等的方法,我宁愿避免使用它们.我只是想像我编码它们那样访问令牌的细节,例如.Sub,以及我添加的自定义声明,如"Name"和"Roles".如何在.Net Core 2.1中这样做?
Sha*_*tin 10
尝试将转换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);
}
Run Code Online (Sandbox Code Playgroud)
以下是支持该属性的.NET Core特定文档HttpContext.User.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");
Run Code Online (Sandbox Code Playgroud)
从 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";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6163 次 |
| 最近记录: |