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

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

我将 JWT 与 .Net Core 2.1 一起使用,

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

我的 Controller 类上的装饰器。在 2.0 中,您似乎必须执行以下操作,但现在已标记为已过时:

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

我见过一些其他相当迂回的扩展授权类的方法等,我宁愿避免这些方法。我只是想访问 token 的详细信息,就像我对它们进行编码一样,例如 .Sub,以及我添加的自定义声明,如“名称”和“角色”。如何在 .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 特定文档。

关于c# - 在 Web Api Controller (.Net Core 2.1) 中获取声明和订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52600259/

相关文章:

node.js - jti claim 应多久重新生成一次?

c# - JwtSecurityTokenHandler 返回小写声明类型

c# - System.Windows.Controls.WebBrowser WPF 的 NullReferenceException

c# - jQuery数据表使用ajax POST方法发送自定义对象

c# - 在 Asp.net Core 1.1 中使用 nodeservices 下载生成的 pdf 的 byte[]

java - Spring Security JWT - 400 错误请求 : "invalid grant" "Bad credentials"

c# - 使用 XML 获取所有同名元素的内容?

c# - 如何为单个 MSTest 测试方法设置区域性?

asp.net-core - 应用程序池回收后,Hangfire 重复作业停止

ASP.NET 5 MVC (Visual Studio 2015) : a keyword called Inject