如何在.NET Core Web API中获取当前用户(来自JWT令牌) [英] How do I get current user in .NET Core Web API (from JWT Token)

查看:2788
本文介绍了如何在.NET Core Web API中获取当前用户(来自JWT令牌)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过大量的努力(以及大量的讲习班,指南等),我设法设置了一个小型的.NET Core REST Web API,并且当存储的用户名和密码有效时,Auth Controller会发出JWT令牌.

After a lot of struggling (and a lot of tuturials, guides, etc) I managed to setup a small .NET Core REST Web API with an Auth Controller issuing JWT tokens when stored username and password are valid.

令牌将用户ID存储为子声明.

The token stores the user id as sub claim.

当方法使用Authorize批注时,我还设法设置了Web API以验证那些令牌.

I also managed to setup the Web API to validate those tokens when a method uses the Authorize annotation.

 app.UseJwtBearerAuthentication(...)

现在我的问题是: 如何在控制器(通过Web API)中读取用户ID(存储在主题声明中)?

Now my question: How do I read the user id (stored in the subject claim) in my controllers (in a Web API)?

基本上是这个问题(如何获取最新信息ASP .NET Core中的用户),但我需要Web API的答案.而且我没有UserManager.所以我需要从某个地方阅读主题声明.

It is basically this question (How do I get current user in ASP .NET Core) but I need an answer for a web api. And I do not have a UserManager. So I need to read the subject claim from somewhere.

推荐答案

您可以使用此方法:

var email = User.FindFirst("sub")?.Value;

就我而言,我使用电子邮件作为唯一值

In my case I'm using the email as a unique value

这篇关于如何在.NET Core Web API中获取当前用户(来自JWT令牌)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆