Junior — Middle
How does the creation and issuance of tokens for user authentication occur in the system?.
sobes.tech AI
Answer from AI
In authentication systems on C#, creating and issuing tokens usually occurs as follows:
- After successfully verifying the user's credentials (login and password), the server generates a token, such as a JWT (JSON Web Token).
- The token contains encoded information about the user and its expiration time, signed with a secret key to prevent tampering.
- The token is returned to the client, which stores it (for example, in localStorage or a cookie).
- In subsequent requests, the client sends the token in the Authorization header (usually "Bearer <token>").
- The server verifies the signature and expiration time of the token to confirm the user's identity.
Example of generating a JWT using the System.IdentityModel.Tokens.Jwt library:
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key_here"));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[] {
new Claim(ClaimTypes.Name, "username"),
new Claim(ClaimTypes.Role, "User")
};
var token = new JwtSecurityToken(
issuer: "yourIssuer",
audience: "yourAudience",
claims: claims,
expires: DateTime.Now.AddHours(1),
signingCredentials: credentials
);
string tokenString = new JwtSecurityTokenHandler().WriteToken(token);
// tokenString is the token sent to the client