Junior — Middle
How do you perform user authentication verification?
sobes.tech AI
Answer from AI
In C#, user authentication is often implemented using mechanisms like ASP.NET Identity or JWT (JSON Web Tokens). The process typically involves the following steps:
- The user enters their login and password.
- The server verifies these credentials by comparing them with stored data in the database (passwords are stored as hashes).
- If the credentials are correct, the server creates a token (e.g., JWT) or sets an authentication cookie.
- In subsequent requests, the server checks for the presence and validity of the token or cookie to confirm authenticity.
An example of creating a JWT in C# using the System.IdentityModel.Tokens.Jwt library:
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret_key"));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "yourdomain.com",
audience: "yourdomain.com",
claims: claims, // list of user claims
expires: DateTime.Now.AddHours(1),
signingCredentials: credentials);
string tokenString = new JwtSecurityTokenHandler().WriteToken(token);
Thus, authentication boils down to validating the entered data and issuing a token that confirms the user is authorized.