ahmed elbarbary

ahmed elbarbary

  • 637
  • 1.6k
  • 282k

How to add userid to payload when generate access token usin

Sep 6 2019 11:40 PM
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 ?
I need if string userid paramters have values add it to payload of generate access token .
What I have tried:
  1. public string GenerateTokens(string userId)  
  2. {  
  3. var Claims = new Claim[]  
  4. {  
  5. new Claim(JwtRegisteredClaimNames.Sub,userId)  
  6. };  
  7. var signingkey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is secret phrase"));  
  8. var SigningCredntials = new SigningCredentials();  
  9. var Jwt = new JwtSecurityToken();  
  10. return new JwtSecurityTokenHandler().WriteToken(Jwt);  
  11. }  
  12. configure service on startup  
  13. public void ConfigureServices(IServiceCollection services)  
  14. {  
  15. //=================This Setting Related To generate Access Token Data===============  
  16. var signingkey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is secret phrase"));  
  17. services.AddAuthentication(options => {  
  18. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;  
  19. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;  
  20. }).AddJwtBearer(cfg =>  
  21. {  
  22. cfg.RequireHttpsMetadata = false;  
  23. cfg.SaveToken = false;  
  24. cfg.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()  
  25. {  
  26. IssuerSigningKey = signingkey,  
  27. ValidateAudience = false,  
  28. ValidateIssuer = false,  
  29. ValidateLifetime = false,  
  30. ValidateIssuerSigningKey = true  
  31. };  
  32. });  
  33. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);  
  34. }  

Answers (1)