【问题标题】:Get information from bearer token从不记名令牌中获取信息
【发布时间】:2021-09-28 17:55:59
【问题描述】:

成功登录后我有一个 jwt,并希望从该令牌中获取数据(令牌已编码,其中包含使用声明保存的信息)。 有没有办法使用 HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme) 从承载令牌中获取数据? 我不知道如何从收到的令牌中获取数据。这是我的代码。

public async Task<TokenResponse> Login(string username, string password)
    {
        var user = await dataContext.Users
                        .FirstOrDefaultAsync(x => x.Username == username && x.Password == password.Encrypt())
                       ?? throw new BadRequestExceptions("Wrong username or password");

        var claims = new[]
        {
            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
            new Claim(ClaimTypes.Role, user.Role.ToString()),
            new Claim(ClaimTypes.GivenName,user.Name),
            new Claim(ClaimTypes.Upn, user.Username)
        };

        var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenConfig.Key));
        var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

        var tokenString = new JwtSecurityToken(tokenConfig.Issuer, tokenConfig.Audience, claims: claims, signingCredentials: signingCredentials);

        tokenResponse = new TokenResponse()
        {
            Token = new JwtSecurityTokenHandler().WriteToken(tokenString)
        };
        return tokenResponse;
    }

【问题讨论】:

  • 如果你做对了,你应该已经拥有了 ClaimsPrincipal 中的所有信息。但由于我看不到你的代码,所以我不知道你是否看到了。
  • @FranzGleichmann 我已经添加了 cmets,请您检查一下并告诉我如何从收到的令牌中获取数据?我是 asp .net core 的新手????
  • 您已在其中包含创建令牌的代码。 不是您处理收到的令牌的地方。您提供的代码基本上是无关紧要的。另外:我推荐taking the tour,以及阅读how to ask a good questionwhat's on topic
  • @FranzGleichmann 感谢您的支持,但我的问题是如何在该 ClaimsPrinciple 中接收信息,这就是为什么我没有您所说的代码 handle the received token

标签: c# asp.net .net visual-studio


【解决方案1】:

从令牌中获取数据的最佳方法(假设您有多个数据要检索)是扩展(扩展方法)ClaimsPrincipal,然后您可以从程序集中的任何位置调用您在该类中扩展的任何方法。 在下面找到一个示例:

public static class ClaimsPrincipalExtensions
{
    public static string GetUsername(this ClaimsPrincipal user)
    {
        return user.FindFirst(ClaimTypes.Name)?.Value;
    }

    public static int GetUserId(this ClaimsPrincipal user)
    {
        return int.Parse(user.FindFirst(ClaimTypes.NameIdentifier)?.Value);
    }
}

然后在你的控制器动作的某个地方,你可以调用 User.GetUsername()User.GetUserId()

但是,如果您只需要检索一两条记录,那么这就足够了:

int userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)

编码愉快!!!

【讨论】:

  • 非常感谢您的指导,我找到了解决问题的方法。祝你早/午/晚好?
猜你喜欢
  • 1970-01-01
  • 2021-08-14
  • 2019-03-30
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多