public async Task <IActionResult> LoginAsync( [FromBody] AuthLoginRequest request, [FromServices] JwtConfiguration jwtConfiguration) { try { var identityUser = await _identityUserManager.FindByNameAsync(request.Username); if (identityUser is null) { return(NotFound()); } var signInResult = await _signInManager.PasswordSignInAsync( identityUser, request.Password, isPersistent : false, lockoutOnFailure : false); if (!signInResult.Succeeded) { return(BadRequest()); } var chatUser = await _chatUserManager.GetUserAsync(request.Username); var jwtConfig = jwtConfiguration.GetSchemeConfig(JwtSchemes.User); var jwtClaims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, chatUser !.Id.ToString()), new Claim(JwtRegisteredClaimNames.UniqueName, request.Username), }; var signingCredentials = new SigningCredentials( key: jwtConfig.SecurityKey, algorithm: JwtConfiguration.SecurityAlgorithm ); var createdAt = DateTime.UtcNow; var validBefore = createdAt.AddMinutes(5); var token = new JwtSecurityToken( issuer: jwtConfig.Issuer, audience: jwtConfig.Audience, claims: jwtClaims, notBefore: createdAt, expires: validBefore, signingCredentials: signingCredentials); return(new JsonResult(new AuthLoginResponse( userId: chatUser !.Id, auth: new AuthTokenResponse( accessToken: new JwtSecurityTokenHandler().WriteToken(token), createdAt: createdAt.ToString("o"), validBefore: validBefore.ToString("o"))))); } catch (Exception ex) { _logger.LogWarning(ex, "Login failed."); return(BadRequest("Could not complete login.")); } }
public IActionResult RenewToken( [FromBody] AuthRenewTokenRequest request, [FromServices] JwtConfiguration jwtConfiguration) { try { var subClaim = User.FindFirst(JwtRegisteredClaimNames.Sub); var nameClaim = User.FindFirst(JwtRegisteredClaimNames.UniqueName); if (subClaim is null || nameClaim is null || !nameClaim.Value.Equals(request.Username, StringComparison.OrdinalIgnoreCase)) { return(BadRequest()); } var jwtConfig = jwtConfiguration.GetSchemeConfig(JwtSchemes.User); var jwtClaims = new Claim[] { subClaim, nameClaim, }; var signingCredentials = new SigningCredentials( key: jwtConfig.SecurityKey, algorithm: JwtConfiguration.SecurityAlgorithm ); var createdAt = DateTime.UtcNow; var validBefore = createdAt.AddMinutes(30); var token = new JwtSecurityToken( issuer: jwtConfig.Issuer, audience: jwtConfig.Audience, claims: jwtClaims, notBefore: createdAt, expires: validBefore, signingCredentials: signingCredentials); return(new JsonResult(new AuthTokenResponse( accessToken: new JwtSecurityTokenHandler().WriteToken(token), createdAt: createdAt.ToString("o"), validBefore: validBefore.ToString("o")))); } catch (Exception ex) { _logger.LogWarning(ex, "Could not issue a renewed token."); return(BadRequest()); } }