public async Task <IActionResult> RequestToken(RequestTokenDto dto) { _logger.LogInformation("Requesting user token for user {Email}", dto?.Email); if (!await _userService.ValidateUserPassword(dto.Email, dto.Password)) { _logger.LogWarning("Username or password is invalid"); return(BadRequest("Username or password is invalid")); } var user = await _userService.GetUser(dto.Email); if (!user.IsActive) { _logger.LogWarning("User is suspended"); return(BadRequest("User is suspended")); } var userRole = await _userService.GetUserRole(dto.Email); var userProjects = await GetUserProjects(dto.Email); var tokenKey = _configuration["Security:Tokens:Key"]; var tokenIssuer = _configuration["Security:Tokens:Issuer"]; var tokenAudience = _configuration["Security:Tokens:Audience"]; var token = AuthorizationToken.GenerateToken(user.Id, dto.Email, userRole, userProjects, tokenKey, tokenIssuer, tokenAudience); return(Ok(token)); }
public async void RequestToken_ReturnsUserIsSuspended() { _userService.Setup(s => s.ValidateUserPassword(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(true); _userService.Setup(s => s.GetUser(It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync((string email, CancellationToken cancellationToken) => new User { Id = 1, Email = email, UserName = email, IsActive = false }); var controller = new TokenController(_userService.Object, _projectService.Object, _catapultEngineService.Object, _configuration.Object, _logger.Object); var dto = new RequestTokenDto { Email = "*****@*****.**" }; var result = await controller.RequestToken(dto); var badRequestResult = Assert.IsType <BadRequestObjectResult>(result); Assert.Equal("User is suspended", badRequestResult.Value); }
public async void RequestToken_RecoveryCodeIsNotCorrect() { _userService.Setup(s => s.ValidateUserPassword(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(new Api.Core.Entities.SignInResult() { Succeeded = false, RequiresTwoFactor = true }); _userService.Setup(s => s.RedeemTwoFactorRecoveryCode(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(false); var controller = new TokenController(_userService.Object, _projectService.Object, _catapultEngineService.Object, _configuration.Object, _applicationSetting, _logger.Object); var dto = new RequestTokenDto { UserName = "******", Password = "******", RecoveryCode = "123" }; var result = await controller.RequestToken(dto); var badRequestResult = Assert.IsType <BadRequestObjectResult>(result); Assert.Equal("Recovery Code is not correct", badRequestResult.Value); }
public async void RequestToken_RecoveryCodeIsCorrect() { _userService.Setup(s => s.ValidateUserPassword(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(new Api.Core.Entities.SignInResult() { Succeeded = false, RequiresTwoFactor = true }); _userService.Setup(s => s.RedeemTwoFactorRecoveryCode(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(true); _userService.Setup(s => s.GetUser(It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync((string email, CancellationToken cancellationToken) => new User { Id = 1, Email = email, UserName = email, IsActive = true }); _userService.Setup(s => s.GetUserRole(It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(UserRole.Administrator); _projectService.Setup(s => s.GetProjectsByUser(1, It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <CancellationToken>())) .ReturnsAsync(new List <(Project, ProjectMemberRole)> { (new Project { Id = 1, Name = "Project01" }, new ProjectMemberRole { Id = 1, Name = MemberRole.Owner }) }); _configuration.SetupGet(x => x["Security:Tokens:Key"]).Returns("key12345678910abcdefghijklmnopqrstuvwxyz"); _configuration.SetupGet(x => x["Security:Tokens:Issuer"]).Returns("issuer"); _configuration.SetupGet(x => x["Security:Tokens:Audience"]).Returns("audience"); var controller = new TokenController(_userService.Object, _projectService.Object, _catapultEngineService.Object, _configuration.Object, _applicationSetting, _logger.Object); var dto = new RequestTokenDto { UserName = "******", Password = "******", RecoveryCode = "123" }; var result = await controller.RequestToken(dto); var okResult = Assert.IsType <OkObjectResult>(result); var returnValue = Assert.IsType <string>(okResult.Value); Assert.NotEmpty(returnValue); }
public async Task <SessionResultDto> CreateSessionId(RequestTokenDto token) { var session = new SessionIdDto(token.request_token); var json = JsonConvert.SerializeObject(session); var data = new StringContent(json, Encoding.UTF8, "application/json"); var httpClient = new HttpClient(); var httpResult = await httpClient.PostAsync("https://api.themoviedb.org/3/authentication/session/new?api_key=7ba0016d8a29404b95fd34bb3130e470", data); string result = httpResult.Content.ReadAsStringAsync().Result; var resultado = JsonConvert.DeserializeObject <SessionResultDto>(result); //Console.WriteLine(result); return(resultado); }
public async void RequestToken_ReturnsUserPasswordInvalid() { _userService.Setup(s => s.ValidateUserPassword(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(false); var controller = new TokenController(_userService.Object, _projectService.Object, _catapultEngineService.Object, _configuration.Object, _logger.Object); var dto = new RequestTokenDto { Email = "*****@*****.**" }; var result = await controller.RequestToken(dto); var badRequestResult = Assert.IsType <BadRequestObjectResult>(result); Assert.Equal("Username or password is invalid", badRequestResult.Value); }
public async Task <Boolean> CreateSession(string login, string senha, RequestTokenDto token) { var session = new SessionPostDto(login, senha, token.request_token); var json = JsonConvert.SerializeObject(session); var data = new StringContent(json, Encoding.UTF8, "application/json"); var httpClient = new HttpClient(); var httpResult = await httpClient.PostAsync("https://api.themoviedb.org/3/authentication/token/validate_with_login?api_key=7ba0016d8a29404b95fd34bb3130e470", data); string result = httpResult.Content.ReadAsStringAsync().Result; Console.WriteLine(result); var resultado = false; if (result.Contains("true")) { resultado = true; } return(resultado); }
public async void RequestToken_ReturnsRequiresTwoFactor() { _userService.Setup(s => s.ValidateUserPassword(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(new Api.Core.Entities.SignInResult() { Succeeded = false, RequiresTwoFactor = true }); var controller = new TokenController(_userService.Object, _projectService.Object, _catapultEngineService.Object, _configuration.Object, _applicationSetting, _logger.Object); var dto = new RequestTokenDto { UserName = "******", Password = "******" }; var result = await controller.RequestToken(dto); var acceptedResult = Assert.IsType <AcceptedResult>(result); Assert.Equal(TokenResponses.RequiresTwoFactor, acceptedResult.Value); }
public async Task <string> RequestToken(RequestTokenDto dto) { var path = $"token"; return(await Api.Post(path, dto)); }
public async Task <IActionResult> RequestToken(RequestTokenDto dto) { _logger.LogRequest("Requesting user token for user {UserName}", dto?.UserName); var signInResult = await _userService.ValidateUserPassword(dto.UserName, dto.Password); if (!signInResult.Succeeded) { if (signInResult.RequiresTwoFactor && _applicationSetting.EnableTwoFactorAuth) { if (!string.IsNullOrEmpty(dto.AuthenticatorCode)) { var twoFactorResult = await _userService.VerifyTwoFactorToken(dto.UserName, dto.AuthenticatorCode); if (!twoFactorResult) { return(BadRequest("Authenticator Code is not correct")); } } else if (!string.IsNullOrEmpty(dto.RecoveryCode)) { var recoveryResult = await _userService.RedeemTwoFactorRecoveryCode(dto.UserName, dto.RecoveryCode); if (!recoveryResult) { return(BadRequest("Recovery Code is not correct")); } } else { return(Accepted("/account/token", TokenResponses.RequiresTwoFactor)); } } else if (!signInResult.RequiresTwoFactor) { _logger.LogWarning("Username or password is invalid. Username: {UserName}", dto?.UserName); return(BadRequest("Username or password is invalid")); } } var user = await _userService.GetUser(dto.UserName); if (!user.IsActive) { _logger.LogWarning("User is suspended"); return(BadRequest("User is suspended")); } var userRole = await _userService.GetUserRole(dto.UserName); var userProjects = await GetUserProjects(dto.UserName); var tokenKey = _configuration["Security:Tokens:Key"]; var tokenIssuer = _configuration["Security:Tokens:Issuer"]; var tokenAudience = _configuration["Security:Tokens:Audience"]; var token = AuthorizationToken.GenerateToken(user.Id, user.UserName, user.FirstName, user.LastName, userRole, userProjects, tokenKey, tokenIssuer, tokenAudience); _logger.LogResponse("Token for user {UserName} retrieved", dto?.UserName); return(Ok(token)); }
public async Task <ResponseTokenModel> RequestToken([FromBody] RequestTokenDto input) { ResponseTokenModel model = new ResponseTokenModel { Success = false, SetPassword = false }; if (input == null) { model.Msg = L("UserCenter_ParamError"); return(model); } if (string.IsNullOrWhiteSpace(input.ClientId)) { model.Msg = L("UserCenter_ParamError"); return(model); } var form = new Dictionary <string, string>(); form["client_id"] = input.ClientId; //避免将refresh_token传递到客户端,使用用户Id+缓存的形式替代 string userId = null; //用户登陆 if (input.ClientId == "app_customer_client") { form["client_secret"] = _appConfiguration["Customer:ClientSecrets"]; form["grant_type"] = _appConfiguration["Customer:GrantType"]; form["userInfo"] = DesEncrypt.Encrypt("userInfo"); form["userId"] = "1"; } //医生登陆 if (input.ClientId == "app_doctor_client") { form["client_secret"] = _appConfiguration["Doctor:ClientSecrets"]; form["grant_type"] = _appConfiguration["Doctor:GrantType"]; form["userInfo"] = DesEncrypt.Encrypt("userInfo"); form["userId"] = "1"; } var tokenModel = await _tokenService.RequestToken(form, input.ClientId); if (tokenModel != null) { model.Success = true; model.AccessToken = tokenModel.access_token; model.ExpiresIn = tokenModel.expires_in; model.TokenType = tokenModel.token_type; model.UserId = userId; List <string> deviceUsers = _cacheManager.GetCache(CacheKeyService.DeviceUser).Get(input.ClientId + userId, () => new List <string>()); if (!deviceUsers.Contains(input.DeviceUUID)) { deviceUsers.Add(input.DeviceUUID); _cacheManager.GetCache(CacheKeyService.DeviceUser).Set(input.ClientId + userId, deviceUsers); } //当前用户的token黑名单 List <string> tokenBlacklist = _cacheManager.GetCache(CacheKeyService.BlacklistToken).Get(input.ClientId + userId, () => new List <string>()); for (int i = 0; i < deviceUsers.Count; i++) { var deviceUser = deviceUsers[i]; if (deviceUser.Equals(input.DeviceUUID)) { List <string> curDeviceToken = _cacheManager.GetCache(CacheKeyService.DeviceToken).Get(input.ClientId + userId + deviceUser, () => new List <string>()); curDeviceToken.ForEach(p => tokenBlacklist.Remove(p)); continue; } //将其他所有设备的token放入黑名单 List <string> deviceToken = _cacheManager.GetCache(CacheKeyService.DeviceToken).Get(input.ClientId + userId + deviceUser, () => new List <string>()); if (deviceToken.Count > 0) { tokenBlacklist.AddRange(deviceToken); } } _cacheManager.GetCache(CacheKeyService.BlacklistToken).Set(input.ClientId + userId, tokenBlacklist); //当前用户的token List <string> proToken = _cacheManager.GetCache(CacheKeyService.DeviceToken).Get(input.ClientId + userId + input.DeviceUUID, () => new List <string>()); proToken.Add(tokenModel.access_token); _cacheManager.GetCache(CacheKeyService.DeviceToken).Set(input.ClientId + userId + input.DeviceUUID, proToken); _cacheManager.GetCache(CacheKeyService.RefreshToken).Set(input.ClientId + userId, tokenModel.refresh_token); } return(model); }