在Web Api Controller(.Net Core 2.1)中获取声明和订阅

时间:2018-10-01 23:42:47

标签: c# asp.net-core jwt asp.net-core-webapi

我正在将JWT与.Net Core 2.1和

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
我的控制器类上的

decorator。在2.0版中,您似乎必须执行以下操作,但现在已被标记为过时:

var authenticateInfo = await HttpContext.Authentication.GetAuthenticateInfoAsync("Bearer");
string accessToken = authenticateInfo.Properties.Items[".Token.access_token"];

我已经看到了扩展授权类的其他一些相当extending回的方法,而我宁愿避免这种方法。我只是想访问令牌的详细信息,就像我对它们进行编码一样,例如.Sub和我添加的自定义声明,例如“名称”和“角色”。在.Net Core 2.1中如何做?

2 个答案:

答案 0 :(得分:3)

尝试将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 特定文档。

答案 1 :(得分:0)

至少在使用.Net Core 3.1时无需强制转换。只需从Controller访问这样的值即可:

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";
}