public async Task <IActionResult> LoginUser(LoginUserModel model) { if (model.Mode.ToLowerInvariant().Equals(LoginModeType.Password.ToString().ToLowerInvariant()) && (string.IsNullOrEmpty(model.Login) || string.IsNullOrEmpty(model.Password))) { return(ReturnBadRequest("login or password is empty")); } var refreshTokenBuilder = new SecurityTokenBuilder() .AddConfiguration(_configuration) .AddEncriptionKey(Constants.JwtRefreshEncriptionKey) .AddIssuerKey(Constants.JwtIssuer) .AddAudienceKey(Constants.JwtAudience) .AddExpiryKey(Constants.JwtRefreshTokenExpiration); var tokenBuilder = new SecurityTokenBuilder() .AddConfiguration(_configuration) .AddEncriptionKey(Constants.JwtEncryptionKey) .AddIssuerKey(Constants.JwtIssuer) .AddAudienceKey(Constants.JwtAudience) .AddExpiryKey(Constants.JwtExpiryTime); switch (model.Mode.ToLowerInvariant()) { case "password": var result = await _usersRepository.LoginUserAsync(model.Login, CryptoHelper.GetSha256String(model.Password)); if (result.User != null) { string refreshToken = string.Empty; if (result.LoginResult) { tokenBuilder.AddClaims(CryptoHelper.GetUserClaims(result.User)); refreshTokenBuilder.AddClaims(CryptoHelper.GetRefreshUserClaims(result.User)); HttpContext.Response.Cookies.Append(_configuration.GetValue <string>(Constants.JwtCookieToken), tokenBuilder.BuildAccessToken(), new CookieOptions { MaxAge = TimeSpan.FromMinutes(_configuration.GetValue <int>(Constants.JwtExpiryTime)), HttpOnly = true }); refreshToken = refreshTokenBuilder.BuildAccessToken(); var refreshTokenModel = new RefreshToken { UserId = result.User.Id, Token = refreshToken, ValidTo = DateTime.UtcNow.AddMinutes(_configuration.GetValue <double>(Constants.JwtRefreshTokenExpiration)) }; var _ = await _usersRepository.RefreshToken(model.Login, refreshTokenModel); } return(result.LoginResult ? Ok(CryptoHelper.GetUserToken(result.User, tokenBuilder, refreshToken)) : ReturnBadRequest("login failed")); } else { return(ReturnBadRequest("user not found")); } case "refresh": refreshTokenBuilder.AddAccessToken(model.RefreshToken); var userId = refreshTokenBuilder.GetUserId(); var userResult = await _usersRepository.CheckUserRefreshTokenAsync(userId, model.RefreshToken); if (userResult.LoginResult) { var user = userResult.User; refreshTokenBuilder.AddClaims(CryptoHelper.GetRefreshUserClaims(user)); refreshTokenBuilder.SetCreateNew(); var refreshToken = refreshTokenBuilder.BuildAccessToken(); var refreshTokenModel = new RefreshToken { UserId = user.Id, Token = refreshToken, ValidTo = DateTime.UtcNow.AddMinutes(_configuration.GetValue <double>(Constants.JwtRefreshTokenExpiration)) }; var _ = await _usersRepository.RefreshToken(userId, refreshTokenModel); tokenBuilder.AddClaims(CryptoHelper.GetUserClaims(user)); return(Ok(CryptoHelper.GetUserToken(user, tokenBuilder, refreshToken))); } else { return(Unauthorized("refreshToken not valid")); } default: return(Unauthorized("mode is not found")); } }