如何在 ASP.NET API 中获取传入的访问令牌

How to get the incoming access token in ASP.NET API

我需要在 ASP.NET API 操作中使用传入的访问令牌中的声明来 运行 一些逻辑。我如何获得访问令牌?稍后如何在访问令牌中获取声明值?

[HttpGet]
[Authorize(Policy = "PaidMember")]
[Route("GetVideos")]
public async Task<IEnumerable<VideoModel>> GetVideos(string topicId)
{
    var accessToken = ... // TODO: Get the access token here

    // Then something like the following
    var type = accessToken.GetValue("membershiptype") // This line is made up
    return await _service.GetVideos(topicId, type );
}

您可以通过以下link作为查询的参考 https://www.youtube.com/watch?v=B2jDN53taDk&list=PL6n9fhu94yhW7yoUOGNOfHurUE6bpOO2b&index=23

您可以这样获取声明值:

(User.Identity as ClaimsIdentity).FindFirst("membershiptype").Value

这样就不需要获取原始令牌了

您可以通过以下方式获得声明:

HttpContext.User.Claims

请参阅此处获取具体声明:

如果您想检查声明,我建议您使用带有授权中间件的 ASP 管道。参见 Microsoft Docs - ASP.NET Core Middleware