locked
How to add UserId to payload when generate access Token Using JWT asp.net core 2.2 ? RRS feed

  • Question

  • User696604810 posted

    problem

    How to add UserId to payload when generate access Token Using JWT asp.net core 2.2 ?

    i make function generate access token but i need to modify it to have or load userid on payload and get result as json ?

    how to do that if possible ?

    public string GenerateTokens(string userId)
            {
    
                var Claims = new Claim[]
                         {
                new Claim(JwtRegisteredClaimNames.Sub,userId)
                         };
                var signingkey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is secret phrase"));
                var SigningCredntials = new SigningCredentials();
                var Jwt = new JwtSecurityToken();
                
                return new JwtSecurityTokenHandler().WriteToken(Jwt);
            }
    configure service on startup
    public void ConfigureServices(IServiceCollection services)
            {
                
                //=================This Setting Related To generate Access Token Data===============
                var signingkey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is secret phrase"));
               
                services.AddAuthentication(options => {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    
                }).AddJwtBearer(cfg =>
                {
                    cfg.RequireHttpsMetadata = false;
                    cfg.SaveToken = false;
                    cfg.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                    {
                        IssuerSigningKey = signingkey,
                        ValidateAudience = false,
                        ValidateIssuer = false,
                        ValidateLifetime = false,
                        ValidateIssuerSigningKey = true
                    };
                });
             
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
               
            }

    Saturday, September 7, 2019 3:48 AM

All replies

  • User475983607 posted

    The shared code snippet does not compile as the SigningCredentials() constructor is missing input parameters.

    Below is a functional JWT token test that uses Identity to look up the user account.

            [HttpPost]
            public async Task<IActionResult> GenerateToken([FromBody] LoginViewModel model)
            {
                if (ModelState.IsValid)
                {
                    var user = await _userManager.FindByEmailAsync(model.Email);
    
                    if (user != null)
                    {
                        var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
                        if (result.Succeeded)
                        {
    
                            var claims = new[]
                            {
                              new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                              new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                            };
    
                            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
                            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    
                            var token = new JwtSecurityToken(_config["Tokens:Issuer"],
                              _config["Tokens:Issuer"],
                              claims,
                              expires: DateTime.Now.AddMinutes(30),
                              signingCredentials: creds);
    
                            return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
                        }
                    }
                }
    
                return BadRequest("Could not create token");
            }
    {
      "Tokens": {
        "Issuer": true,
        "Key": "DEF74CFD-1743-4438-8DF1-0F3056406508"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AllowedHosts": "*",
      "ConnectionStrings": {
        "JwtApiContextConnection": "Server=(localdb)\\mssqllocaldb;Database=JwtApi;Trusted_Connection=True;MultipleActiveResultSets=true"
      }
    }
         public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddAuthentication()
                  .AddJwtBearer(cfg =>
                  {
                      cfg.RequireHttpsMetadata = false;
                      cfg.SaveToken = true;
    
                      cfg.TokenValidationParameters = new TokenValidationParameters()
                      {
                          ValidIssuer = Configuration["Tokens:Issuer"],
                          ValidAudience = Configuration["Tokens:Issuer"],
                          IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                      };
    
                  });
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            }

    Saturday, September 7, 2019 12:45 PM
  • User696604810 posted

    i modified my code as below 

    are this code like custom claim or not and how to generate result as json result

     public string GenerateTokens(string userId)
            {
    
                var Claims = new Claim[]
                         {
                new Claim(JwtRegisteredClaimNames.Sub,userId)
                         };
                var signingkey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is secret phrase"));
                var SigningCredntials = new SigningCredentials(signingkey, SecurityAlgorithms.HmacSha256);
                var Jwt = new JwtSecurityToken();
                var jsonu = new { id = userId };
                Jwt.Payload["user"] = jsonu;
                return new JwtSecurityTokenHandler().WriteToken(Jwt);
            }

    are this correct i need to add user id only on payload

    Saturday, September 7, 2019 1:31 PM
  • User475983607 posted

    Is there a reason why you are unable to review or test your code? 

    You forgot to add the claims and you are not following the coding pattern in the shared code snippet. 

    Saturday, September 7, 2019 2:29 PM
  • User-1764593085 posted

    Your code has added the userId into the payload, anyway, you could configure your JwtSecurityToken like below

    var claims =  new List<Claim>
    {
    new Claim(JwtRegisteredClaimNames.Sub, userId),

    //More custom claims
    };
    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    //create token with correct issuer and audience var token = new JwtSecurityToken(_config["Jwt:Issuer"], _config["Jwt:Issuer"], claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); return new JwtSecurityTokenHandler().WriteToken(token);

    You create a JWT token string and you could decode it by referring to 

    https://stackoverflow.com/questions/38340078/how-to-decode-jwt-token

    Monday, September 9, 2019 9:15 AM
  • User-474980206 posted
    You should read the jwt token documentation. The payload is a json mapped object consisting of claims which are name/value pairs. To add a user ID to the payload, you add a claim with the value of userid.
    Monday, September 9, 2019 3:12 PM