• <i id='vvSb8'><tr id='vvSb8'><dt id='vvSb8'><q id='vvSb8'><span id='vvSb8'><b id='vvSb8'><form id='vvSb8'><ins id='vvSb8'></ins><ul id='vvSb8'></ul><sub id='vvSb8'></sub></form><legend id='vvSb8'></legend><bdo id='vvSb8'><pre id='vvSb8'><center id='vvSb8'></center></pre></bdo></b><th id='vvSb8'></th></span></q></dt></tr></i><div id='vvSb8'><tfoot id='vvSb8'></tfoot><dl id='vvSb8'><fieldset id='vvSb8'></fieldset></dl></div>

      <tfoot id='vvSb8'></tfoot>
        <bdo id='vvSb8'></bdo><ul id='vvSb8'></ul>
        <legend id='vvSb8'><style id='vvSb8'><dir id='vvSb8'><q id='vvSb8'></q></dir></style></legend>

        <small id='vvSb8'></small><noframes id='vvSb8'>

        JWT 如何添加自定义声明和解码声明

        时间:2023-06-03

          <tbody id='G0dkB'></tbody>
        1. <tfoot id='G0dkB'></tfoot>
            <bdo id='G0dkB'></bdo><ul id='G0dkB'></ul>
              <legend id='G0dkB'><style id='G0dkB'><dir id='G0dkB'><q id='G0dkB'></q></dir></style></legend>

                <i id='G0dkB'><tr id='G0dkB'><dt id='G0dkB'><q id='G0dkB'><span id='G0dkB'><b id='G0dkB'><form id='G0dkB'><ins id='G0dkB'></ins><ul id='G0dkB'></ul><sub id='G0dkB'></sub></form><legend id='G0dkB'></legend><bdo id='G0dkB'><pre id='G0dkB'><center id='G0dkB'></center></pre></bdo></b><th id='G0dkB'></th></span></q></dt></tr></i><div id='G0dkB'><tfoot id='G0dkB'></tfoot><dl id='G0dkB'><fieldset id='G0dkB'></fieldset></dl></div>

              1. <small id='G0dkB'></small><noframes id='G0dkB'>

                  本文介绍了JWT 如何添加自定义声明和解码声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

                  问题描述

                  限时送ChatGPT账号..

                  我正在尝试检索我在创建令牌时所做的一些自定义声明.但是,我不确定我应该写什么来检索这些声明.

                  I am trying to retrieve some custom claims that I made when I created my token. However, I am not sure on what I should write to retrieve those claims.

                  这是我的令牌创建函数

                  public String createToken(AuthenticationDTO Input)
                  {
                      //Set issued at date
                      DateTime issuedAt = DateTime.UtcNow;
                      //set the time when it expires
                      DateTime expires = DateTime.UtcNow.AddDays(7);
                  
                      //http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token
                      var tokenHandler = new JwtSecurityTokenHandler();
                  
                      //create a identity and add claims to the user which we want to log in
                      ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
                      {
                          new Claim("UserName", Input.UserName),
                          new Claim("Email",Input.Email),
                          new Claim("PhoneNumber",Input.PhoneNumber),
                          new Claim("FirstName",Input.FirstName),
                          new Claim("LastName",Input.LastName),
                          new Claim("Id",Input.Id)
                      });
                  
                      const string sec = HostConfig.SecurityKey;
                      var now = DateTime.UtcNow;
                      var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
                      var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
                  
                  
                      //create the jwt
                      var token =(JwtSecurityToken)
                              tokenHandler.CreateJwtSecurityToken(issuer: HostConfig.Issuer, audience: HostConfig.Audience,
                                  subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
                      var tokenString = tokenHandler.WriteToken(token);
                  
                      return tokenString;
                  }
                  

                  我决定命名我自己的声明,而不是使用提供的标准声明.但是,我不知道如何检索它们.这是我目前拥有的:

                  Instead of using the standard ones that are provided, I decided to name my own claims. However, I do not know how to retrieve them. This is what I have currently:

                  public AuthenticationDTO DecodeToken(String Input)
                  {
                      var key = Encoding.ASCII.GetBytes(HostConfig.SecurityKey);
                      var handler = new JwtSecurityTokenHandler();
                      var tokenSecure = handler.ReadToken(Input) as SecurityToken;
                      var validations = new TokenValidationParameters
                      {
                          ValidateIssuerSigningKey = true,
                          IssuerSigningKey = new SymmetricSecurityKey(key),
                          ValidateIssuer = false,
                          ValidateAudience = false
                      };
                      var claims = handler.ValidateToken(Input, validations, out tokenSecure);
                      return null;
                  }
                  

                  我注意到我的索赔是这样来的

                  I noticed that my claims are coming in like this

                  如何提取它们?

                  添加了 AuthentcationDTO

                  Added AuthentcationDTO

                  public class AuthenticationDTO
                  {
                      public String Id { get; set; }
                      public String UserName { get; set; }
                      public String Email { get; set; }
                      public String FirstName { get; set; }
                      public String LastName { get; set; }
                      public String PhoneNumber { get; set; }
                  }
                  

                  推荐答案

                  如果你想获取声明,即 preferred_username,你可以从 ClaimsPrincipal 获取.

                  If you want to gets claims i.e, preferred_username you can get that from ClaimsPrincipal.

                  var user = User as ClaimsPrincipal;
                  string username = user.Claims.Where(c => c.Type == "preferred_username")
                      .Select(x => x.Value).FirstOrDefault();
                  

                  User 将来自 Claims.对于那个写

                  User will come from Claims. For that write

                  使用 System.Security.Claims;

                  似乎 User 并非在所有版本中都可用.获得索赔的另一种方法是类似的.

                  It seems that User is not available in all versions. Another way to get claims will be something similar.

                  var prinicpal = (ClaimsPrincipal)Thread.CurrentPrincipal;
                  var email = prinicpal.Claims.Where(c => c.Type == ClaimTypes.Email)
                      .Select(c => c.Value).SingleOrDefault();
                  

                  AuthenticationDTO 分配所有值.

                  public AuthenticationDTO DecodeToken(String Input)
                  {
                      var key = Encoding.ASCII.GetBytes(HostConfig.SecurityKey);
                      var handler = new JwtSecurityTokenHandler();
                      var tokenSecure = handler.ReadToken(Input) as SecurityToken;
                      var validations = new TokenValidationParameters
                      {
                          ValidateIssuerSigningKey = true,
                          IssuerSigningKey = new SymmetricSecurityKey(key),
                          ValidateIssuer = false,
                          ValidateAudience = false
                      };
                      var claims = handler.ValidateToken(Input, validations, out tokenSecure);
                      var prinicpal = (ClaimsPrincipal)Thread.CurrentPrincipal;
                      if (principal is ClaimsPrincipal claims)
                      {
                           return new ApplicationDTO
                               {
                                   Id = claims.Claims.FirstOrDefault(x => x.Type == "sub")?.Value ?? "",
                                   UserName = claims.Claims.FirstOrDefault(x => x.Type == "preferred_username")?.Value ?? "",
                                   Email = claims.Claims.FirstOrDefault(x => x.Type == "email")?.Value ?? ""
                               };
                      }
                      return null;
                  }
                  

                  这篇关于JWT 如何添加自定义声明和解码声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

                  上一篇:System.IdentityModel.Tokens.JwtSecurityToken 自定义属性 下一篇:JwtSecurityToken 理解与异常

                  相关文章

                  最新文章

                  <legend id='udeeE'><style id='udeeE'><dir id='udeeE'><q id='udeeE'></q></dir></style></legend>
                      <tfoot id='udeeE'></tfoot>

                        <bdo id='udeeE'></bdo><ul id='udeeE'></ul>

                      <small id='udeeE'></small><noframes id='udeeE'>

                      <i id='udeeE'><tr id='udeeE'><dt id='udeeE'><q id='udeeE'><span id='udeeE'><b id='udeeE'><form id='udeeE'><ins id='udeeE'></ins><ul id='udeeE'></ul><sub id='udeeE'></sub></form><legend id='udeeE'></legend><bdo id='udeeE'><pre id='udeeE'><center id='udeeE'></center></pre></bdo></b><th id='udeeE'></th></span></q></dt></tr></i><div id='udeeE'><tfoot id='udeeE'></tfoot><dl id='udeeE'><fieldset id='udeeE'></fieldset></dl></div>