如何从.Net Core API中的身份验证JWT令牌中获取身份用户? [英] How to get Identity User from his authentication JWT token in .Net Core API?

查看:50
本文介绍了如何从.Net Core API中的身份验证JWT令牌中获取身份用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 .Net Core 用于我的API,因此没有任何视图.我还使用 ASP.net Core Identity 框架来授权数据库中的用户.对于登录用户,我使用以下代码:

I'm using .Net Core for my API, so no views or whatsoever. I'm also using ASP.net Core Identity framework to authorize users in my database. For logging in users, I use this code:

private string GenerateAuthenticationResult(ApplicationUser user)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                // Things to be included and encoded in the token
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Email, user.Email),
                    new Claim("id", user.Id)
                }),
                // Token will expire 2 hours from which it was created
                Expires = DateTime.UtcNow.AddHours(2),
                //
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return tokenHandler.WriteToken(token);
        }

这就像用于验证用户操作的超级按钮一样,但是如果用户使用我之前提供的令牌登录他的请求标头(承载者),那么我如何知道服务器正在与谁进行通讯.

This works like a charm for authenticating user actions, but how can I know whom my server is talking to provided that the user used the token I provided earlier for logging in in his request header (Bearer).

TL;博士

我想从请求标头中提供的令牌中提取用户ID或用户电子邮件.

I want to extract user ID or user Email from the token provided in the request header.

谢谢.

推荐答案

您可以使用 AddJwtBearer 来验证JWT令牌:

You can use AddJwtBearer validating JWT tokens :

var sharedKey = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes("yourkey"));
services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;

    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = sharedKey,

        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateLifetime = false,            
    };
});

并通过在 Configure 方法中添加 app.UseAuthentication(); 来启用asp.net核心身份验证中间件.之后,您可以在受保护的操作/控制器上添加 [Authorize] 属性.

And enable asp.net core authentication middleware via adding app.UseAuthentication(); in Configure method . After that , you can add [Authorize] attribute on protected actions/controllers .

要在进行身份验证后获取电子邮件和用户ID:

To get the email and user id after authentication in action :

var  email= User.Claims.Where(x => x.Type == ClaimTypes.Email).FirstOrDefault()?.Value;
var  userid= User.Claims.Where(x => x.Type == "id").FirstOrDefault()?.Value;

此处使用 ClaimTypes.Email ,因为 JwtRegisteredClaimNames.Email 将由中间件自动映射到 ClaimTypes.Email .参见源代码.

Here ClaimTypes.Email is used since JwtRegisteredClaimNames.Email will map to ClaimTypes.Email by middleware automatically . See source code .

以下是一些有关JWT身份验证的有用文章:

Here are some useful articles for JWT Authentication :

https://jasonwatmore.com/post/2018/08/14/aspnet-core-21-jwt-authentication-tutorial-with-example-api

https://jasonwatmore.com/post/2019/10/11/aspnet-core-3-jwt-authentication-tutorial-with-example-api

这篇关于如何从.Net Core API中的身份验证JWT令牌中获取身份用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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