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

查看:38
本文介绍了如何从 .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);
        }

这就像验证用户操作的魅力一样,但是如果用户使用我之前提供的令牌登录他的请求标头 (Bearer),我怎么知道我的服务器正在与谁通话.

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天全站免登陆