Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // *** Request model ***
- public class JwtTokensRequest
- {
- public string Username { get; set; }
- public string Password { get; set; }
- }
- // *** New user repository handlers ***
- private bool Authenticate(string username, string password)
- {
- var target = _users.Single(x => x.Username == username);
- if (!target.IsConfirmed)
- return false;
- // Get stored salt and hash
- byte[] salt = Convert.FromBase64String(target.PwdSalt);
- byte[] hash = Convert.FromBase64String(target.PwdHash);
- byte[] calcHash =
- KeyDerivation.Pbkdf2(
- password: password,
- salt: salt,
- prf: KeyDerivationPrf.HMACSHA256,
- iterationCount: 100000,
- numBytesRequested: 256 / 8);
- return hash.SequenceEqual(calcHash);
- }
- public Tokens JwtTokens(JwtTokensRequest request)
- {
- var isAuthenticated = Authenticate(request.Username, request.Password);
- if (!isAuthenticated)
- throw new InvalidOperationException("Authentication failed");
- // Get secret key bytes
- var jwtKey = _configuration["JWT:Key"];
- var jwtKeyBytes = Encoding.UTF8.GetBytes(jwtKey);
- // Create a token descriptor (represents a token, kind of a "template" for token)
- var tokenDescriptor = new SecurityTokenDescriptor
- {
- Subject = new ClaimsIdentity(new System.Security.Claims.Claim[]
- {
- new System.Security.Claims.Claim(ClaimTypes.Name, request.Username),
- new System.Security.Claims.Claim(JwtRegisteredClaimNames.Sub, request.Username),
- //new System.Security.Claims.Claim(ClaimTypes.Role, "User")
- }),
- Issuer = _configuration["JWT:Issuer"],
- Audience = _configuration["JWT:Audience"],
- Expires = DateTime.UtcNow.AddMinutes(10),
- SigningCredentials = new SigningCredentials(
- new SymmetricSecurityKey(jwtKeyBytes),
- SecurityAlgorithms.HmacSha256Signature)
- };
- // Create token using that descriptor, serialize it and return it
- var tokenHandler = new JwtSecurityTokenHandler();
- var token = tokenHandler.CreateToken(tokenDescriptor);
- var serializedToken = tokenHandler.WriteToken(token);
- return new Tokens
- {
- Token = serializedToken
- };
- }
- // *** New controller action to get tokens ***
- [HttpPost("[action]")]
- public ActionResult<Tokens> JwtTokens([FromBody] JwtTokensRequest request)
- {
- try
- {
- return Ok(_userRepository.JwtTokens(request));
- }
- catch (InvalidOperationException ex)
- {
- return BadRequest(ex.Message);
- }
- }
- // *** Configure JWT services: improved configuration ***
- builder.Services
- .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
- .AddJwtBearer(o => {
- var jwtKey = builder.Configuration["JWT:Key"];
- var jwtKeyBytes = Encoding.UTF8.GetBytes(jwtKey);
- o.TokenValidationParameters = new TokenValidationParameters
- {
- ValidateIssuer = true,
- ValidIssuer = builder.Configuration["JWT:Issuer"],
- ValidateAudience = true,
- ValidAudience = builder.Configuration["JWT:Audience"],
- ValidateIssuerSigningKey = true,
- IssuerSigningKey = new SymmetricSecurityKey(jwtKeyBytes),
- ValidateLifetime = true,
- };
- });
- // *** New needed configuration in appsettings.json ***
- "JWT": {
- "Key": "E(H+MbQeThWmZq4t6w9z$C&F)J@NcRfU",
- "Issuer": "localhost",
- "Audience": "localhost"
- }
Add Comment
Please, Sign In to add comment