I'm trying to create an authentication system. For this purpose, I want to store user ID in JWT token, so I can know which user which.
I created my JWT token like in below;
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret key"));//token secret key
var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var tokenOptions = new JwtSecurityToken(
issuer: "https://localhost:44309/",
audience: "https://localhost:44309/",
claims: new List<Claim>(),
expires: DateTime.Now.AddMinutes(5),
signingCredentials: signingCredentials
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
return Ok(new { Token = tokenString });
But I couldn't find a way to import user id into this. I tried to add another parameter to tokenOptions
like user:{ "id": user.ID},
but I couldn't add it since it's not a real parameter.
var tokenOptions = new JwtSecurityToken(
users:{ "id": user.ID},
issuer: "https://localhost:44309/",
audience: "https://localhost:44309/",
claims: new List<Claim>(),
expires: DateTime.Now.AddMinutes(5),
signingCredentials: signingCredentials
);
Any help? Thanks!
CodePudding user response:
Just add it to claims
like this:
var tokenOptions = new JwtSecurityToken(
issuer: "https://localhost:44309/",
audience: "https://localhost:44309/",
claims: new List<Claim>() { new Claim("id", user.ID) },
expires: DateTime.Now.AddMinutes(5),
signingCredentials: signingCredentials
);