Click here to Skip to main content
15,894,291 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 tokeen


What I have tried:

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);
           
        }
Posted

1 solution

If I got your point, beside adding predefined standard claims, you can easily add custom name/value to your claims and get them back in your UI:

var Claims = new Claim[]
{
   new Claim("userId",userId)
};
 
Share this answer
 
Comments
ahmed_sa 7-Sep-19 8:14am    
thank you for reply on jwt there are thing name payload
token.payload
but i dont know how to use it
or how to implement it
zamanipour 7-Sep-19 8:28am    
i just changed a line in your own code: 'new Claim(JwtRegisteredClaimNames.Sub,userId)' and replaced it with new custom name/value pair. you can add as many claims as you want. for using jwt, it depends on your front-end technology. after you implement the required logic to decrypt your message in front-end (search for it based on your technology) you can have your payload as a json object and you can use claims object to modify the page.
ahmed_sa 7-Sep-19 8:53am    
thank you for reply can you make reply by details if possible this is actually what
i need to complete what you write by make example as reply
can you clear that ( you can have your payload as a json object and you can use claims object to modify the page.)
zamanipour 7-Sep-19 8:29am    
check out https://www.codeproject.com/Articles/5160941/ASP-NET-CORE-Token-Authentication-and-Authorizatio
ahmed_sa 7-Sep-19 9:34am    
Are this code add user id to payload
see modified code
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);
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900