private credential convertToDomainObject(CredentialDto credentialModel) { credential credential = null; if (credentialModel is AmazonCredentialDto) { credential = Mapper.Map <AmazonCredentialDto, amazoncredential>(credentialModel as AmazonCredentialDto); } else if (credentialModel is eBayCredentialDto) { credential = Mapper.Map <eBayCredentialDto, ebaycredential>(credentialModel as eBayCredentialDto); } else if (credentialModel is ShipStationCredentialDto) { credential = Mapper.Map <ShipStationCredentialDto, shipstationcredential>(credentialModel as ShipStationCredentialDto); } else if (credentialModel is BigCommerceCredentialDto) { credential = Mapper.Map <BigCommerceCredentialDto, bigcommercecredential>(credentialModel as BigCommerceCredentialDto); } else { throw new InvalidCastException(string.Format("Unknown credential type \'{0}\' for casting!", credentialModel.MarketplaceType)); } return(credential); }
public async Task <IActionResult> CrateToken([FromBody] CredentialDto credentialDto) { try { var user = await _userMgr.FindByNameAsync(credentialDto.Username); if (user != null) { if (_hasher.VerifyHashedPassword(user, user.PasswordHash, credentialDto.Password) == PasswordVerificationResult.Success) { var userClaims = await _userMgr.GetClaimsAsync(user); var claims = CreateClaims(user, userClaims); var creds = CreateCredentials(); var token = CreateJwtSecurityToken(claims, creds); var returnToken = new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo }; return(Ok(returnToken)); } } } catch (Exception ex) { _logger.LogError($"Exception thrown while creating JWT: {ex}"); } return(BadRequest("Failed to generate token")); }
public async Task <ActionResult <TokenDto> > GetToken([FromBody] CredentialDto credentialDto) { var client = await _clientRepository.GetClientByNameAsync(credentialDto.ClientName); if (client == null) { return(Unauthorized()); } //Validate username/password if (BCrypt.Net.BCrypt.Verify(credentialDto.Key, client.Key)) { //Build token var validity = 120; var expires = DateTime.UtcNow.AddMinutes(validity); var tokenData = new TokenDto() { Token = BuildToken(credentialDto, validity), ExpiryUtc = expires }; return(Ok(tokenData)); } return(Unauthorized()); }
public async Task <LoginPlainResponse> Login(CredentialDto credentials) { var loginResponse = new LoginPlainResponse(); loginResponse.IsSuccessful = false; loginResponse.ErrorMessage = "Email or password are incorrect. Try again."; var user = await _unitOfWork.userRepository.GetByEmail(credentials.Email); if (user == null) { return(loginResponse); } if (user.VerifyPassword(credentials.Password)) { var jwtToke = GenerateJwtToken(user); loginResponse.IsSuccessful = true; loginResponse.ErrorMessage = ""; loginResponse.Data = new TokensDto { Jwt = jwtToke, refreshToken = await GenerateRefreshToken(user, jwtToke) }; return(loginResponse); } return(loginResponse); }
public IActionResult Login([FromBody] CredentialDto credDto) { try { if (credDto == null) { throw new BasicException("Wrong data syntax."); } if (!ModelState.IsValid) { BadRequest(ModelState); } User user = _userRepository.GetAll().FirstOrDefault(x => x.EmailAddress.Equals(credDto.EmailAddress)); if (user == null || !user.Password.Equals(GetHashedPaswd(credDto.Password))) { return(Unauthorized()); } var token = new JWTCreator() { Audience = _cfg["Tokens:Audience"], Issuer = _cfg["Tokens:Issuer"], ExpiryInMinutes = expiryMinutes, SecurityKey = JwtSecurityKey.Create(_cfg["Tokens:Key"]), Subject = user.UserGUID }.AddClaim("EmailAddress", user.EmailAddress) .Build(); DateTime curruntTime = DateTime.Now; _userJwtMapRepository.Delete(curruntTime); _userJwtMapRepository.Add(token.Value, user, curruntTime.AddMinutes(expiryMinutes)); return(Ok(Json(new { message = "success", jwt = token.Value }))); } catch (BasicException ex) { _logger.LogError(ex.Message); return(BadRequest(ex.Message)); } catch (NotFoundException ex) { _logger.LogError(ex.Message); return(NotFound(ex.Message)); } catch (PermissionException ex) { _logger.LogError(ex.Message); return(Unauthorized()); } catch (Exception ex) { _logger.LogError(ex.Message); return(BadRequest()); } }
public Task <SwaggerResponse <AuthResponse> > AuthenticateAsync(CredentialDto credentials) { var headers = new Dictionary <string, IEnumerable <string> >(); try { var authResponse = _appUser.Authenticate(credentials); return(Task.FromResult( new SwaggerResponse <AuthResponse>( StatusCodes.Status200OK, headers, new AuthResponse { Token = authResponse.authToken, ValidFor = authResponse.expiresIn, Id = authResponse.id, Refreshtoken = authResponse.refreshToken, Status = new OpResult { Success = true, Result = "Authentication successful" } }))); } catch (RepositoryException exception) { return(Task.FromResult( new SwaggerResponse <AuthResponse>( exception.StatusCode, headers, new AuthResponse { Token = "", Status = new OpResult { Success = false, Result = "Authentication failed" } }, exception.Message))); } }
public async Task <IActionResult> Login([FromBody] CredentialDto credentialDto) { try { if (credentialDto == null) { return(BadRequest()); } var user = await _userManager.FindByEmailAsync(credentialDto.Email); if (user != null) { if (_hasher.VerifyHashedPassword(user, user.PasswordHash, credentialDto.Password) == PasswordVerificationResult.Success) { return(Ok(await CreateToken(user))); } } }catch (Exception ex) { _logger.LogError($"Exception thorwn while loggin in: {ex}"); } return(BadRequest("Failed to login")); }
public HttpResponseMessage Create(CredentialDto credential) { string token = sessionServices.Create( new Credential(credential.Username, credential.Password)); if (token == null) { return(Request.CreateResponse(HttpStatusCode.Forbidden)); } HttpResponseMessage response = Request.CreateResponse( HttpStatusCode.Created, new { Token = token }); #region Please add necessary information on response headers // A created result should contains the resource URI. Since the user // has logged into the system, it should contains the correct cookie // setter. response.Headers.Location = new Uri(Url.Link("get session", new { token }), UriKind.RelativeOrAbsolute); response.Headers.AddCookies(new [] { new CookieHeaderValue(SessionCookieKey, token) }); #endregion return(response); }
public async Task <IActionResult> IssueLoginToken([FromBody] CredentialDto credential, string gRecaptchaResponse) { try { //if (!GoogleReCaptchaHelper.IsReCaptchaPassed(gRecaptchaResponse, _googleReCaptchaConfigs.SecretKey, _googleReCaptchaConfigs.URL)) // { // return BadRequest("CAPTCHA fail"); // } var loginInfo = await _identityService.IssueLoginTokenAsync(credential); return(Ok(loginInfo)); } catch (IdentityException ex) { return(BadRequest(ex.Message)); } catch (BadRequestException ex) { return(BadRequest(ex.Message)); } catch (NotFoundException ex) { return(NotFound(ex.Message)); } catch (Exception ex) { _logger.LogCritical($"IssueLoginToken() Error: {ex}"); return(StatusCode(500, "Internal Server Error")); } }
public HttpResponseMessage Create(CredentialDto credential) { string token = sessionServices.Create( new Credential(credential.Username, credential.Password)); if (token == null) { return(Request.CreateResponse(HttpStatusCode.Forbidden)); } HttpResponseMessage response = Request.CreateResponse( HttpStatusCode.Created, new { Token = token }); #region Please add necessary information on response headers // A created result should contains the resource URI. Since the user // has logged into the system, it should contains the correct cookie // setter. throw new NotImplementedException(); #endregion return(response); }
private CredentialDto convertToModel(credential credential) { CredentialDto model = null; if (credential is amazoncredential) { model = Mapper.Map <amazoncredential, AmazonCredentialDto>(credential as amazoncredential); } else if (credential is ebaycredential) { model = Mapper.Map <ebaycredential, eBayCredentialDto>(credential as ebaycredential); } else if (credential is shipstationcredential) { model = Mapper.Map <shipstationcredential, ShipStationCredentialDto>(credential as shipstationcredential); } else if (credential is bigcommercecredential) { model = Mapper.Map <bigcommercecredential, BigCommerceCredentialDto>(credential as bigcommercecredential); } else { throw new InvalidCastException(string.Format("Unknown credential type \'{0}\' for casting!", credential.MarketplaceType)); } return(model); }
public BigCommerceMarketplaceOrdersProviderTests() { AutoMapperConfig.RegisterAutoMappers(); _credentialService = new CredentialService(); _credential = _credentialService.GetCredential("BigCommerce", MarketplaceMode.TEST.ToString()); _credentialRepository = new CredentialRepository(); _credentialRepo = _credentialRepository.GetDefaultCredential("BigCommerce", MarketplaceMode.TEST.ToString()); }
public async Task <IActionResult> Login([FromBody] CredentialDto user) { string token = await this.authenticator.Login(user); if (string.IsNullOrWhiteSpace(token)) { return(Unauthorized()); } return(Json(new { token })); }
public async Task <IActionResult> Login([FromBody] CredentialDto user) { return(await authenticator.Login(user).Select(token => { return Json(new { token }); }).ToActionResult()); }
public async Task <IActionResult> Authenticate([FromBody] CredentialDto credentials) { if (!ModelState.IsValid) { return(HandleInvalidModelState(ModelState)); } var result = await _implementation.AuthenticateAsync(credentials).ConfigureAwait(false); return(ProcessResponse <AuthResponse>(result)); }
public ActionResult <UserTokenDto> SignIn([FromBody] CredentialDto model) { if (!ModelState.IsValid) { return(BadRequest()); } var userToken = _userAppService.Auth(model); return(Ok(userToken)); }
public bool CreateCredential(CredentialDto model) { // unbox the correct object type for the credential var credential = convertToDomainObject(model); credential.CreatedBy = model.ModifiedBy; credential.Created = DateTime.UtcNow; _context.credentials.Add(credential); _context.SaveChanges(); model.Id = credential.Id; return(true); }
public async Task <IActionResult> Login([FromBody] CredentialDto credentials) { if (ModelState.IsValid) { var response = await _userService.Login(credentials); if (!response.IsSuccessful) { return(new BadRequestObjectResult(response.ErrorMessage)); } return(new OkObjectResult(response)); } return(BadRequest()); }
public async Task <IActionResult> SignIn([FromBody] CredentialDto Credentials) { if (!ModelState.IsValid) { return(ValidationFailed()); } var user = await _service.AuthenticateAsync(Credentials.username, Credentials.password); if (user == null) { return(Error("Incorrect username or password")); } return(Success(user, "Sign In successfully")); }
public UserTokenDto Auth(CredentialDto model) { var user = _userService.GetUserAuth(model.Email, EncryptHelper.Sha256(model.Password)); if (user == null) { return(null); } var token = TokenHelper.GenerateJwtToken(user.Email, user.Password); var userToken = new UserTokenDto(user.UserId, user.Name, token); return(userToken); }
public async Task <IActionResult> CreateToken([FromBody] CredentialDto dto) { try { var user = await _userMgr.FindByNameAsync(dto.UserName); if (user != null) { if (_hasher.VerifyHashedPassword(user, user.PasswordHash, dto.Password) == PasswordVerificationResult.Success) { var userClaims = await _userMgr.GetClaimsAsync(user); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.GivenName, user.Name), new Claim(JwtRegisteredClaimNames.FamilyName, user.Surname), new Claim(JwtRegisteredClaimNames.Email, user.Email) }.Union(userClaims); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: _config["Tokens:Issuer"], audience: _config["Tokens:Audience"], claims: claims, expires: DateTime.UtcNow.AddMinutes(15), signingCredentials: creds ); return(Ok(new { //Generate a JWT security token token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo })); } } } catch (Exception ex) { _logger.LogError($"Exception thrown while creating JWT: {ex}"); } return(BadRequest("Failed to generate token")); }
public bool UpdateCredential(int id, CredentialDto model) { // get the curent credential var existingCredential = _context.credentials.FirstOrDefault(x => x.Id == id); // unbox to the correct object for crendential var updatedCredential = convertToDomainObject(model); updatedCredential.ModifiedBy = model.ModifiedBy; updatedCredential.Modified = DateTime.UtcNow; _context.Entry(existingCredential).CurrentValues.SetValues(updatedCredential); _context.SaveChanges(); return(true); }
public async Task <IActionResult> Login([FromBody] CredentialDto credentials) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } return(Ok(await _usr.Login(credentials.UserName, credentials.Password))); } catch (InvalidOperationException ex) { return(BadRequest(ex.Message)); } }
public LoginDto Login(CredentialDto credentialDto) { LogIn state = playerStore.LogNewUser(credentialDto); if (state == LogIn.Failed) { return new LoginDto { IsLoggedIn = LogIn.Failed, Profil = null } } ; LoginDto dto = playerStore.GetProfilOf(credentialDto).GetDto(); dto.IsLoggedIn = state; return(dto); }
private string BuildToken(CredentialDto credentialDto, int validity) { var claims = new[] { new Claim(ClaimTypes.NameIdentifier, credentialDto.ClientName, ClaimValueTypes.String, _config["Jwt:Issuer"]) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken(_config["Jwt:Issuer"], _config["Jwt:Issuer"], claims: claims, expires: DateTime.Now.AddMinutes(validity), signingCredentials: creds); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public CredentialDto GetCredentialsByCompany(int companyId, string credentialType, string mode) { var credential = new CredentialDto(); using (var context = new EisInventoryContext()) { var result = context.credentials .FirstOrDefault(x => x.CompanyId == companyId && x.MarketplaceType == credentialType && x.Mode == mode); if (result == null) { return(null); } credential = convertToModel(result); } return(credential); }
public LogIn LogNewUser(CredentialDto logDto) { if (!AllUsersCredential().Any(p => p.CheckCredential(logDto))) { return(LogIn.Failed); } Database.Player userDb = dbContext.Players.FirstOrDefault(p => p.Email == logDto.Email); if (userDb == null || userDb.Password != logDto.Password) { return(LogIn.Failed); } Profil user = new Profil(userDb); LoggedUsers.Add(user); return(LogIn.Success); }
public async Task <IActionResult> Login([FromBody] CredentialDto dto) { try { var result = await _signInMgr.PasswordSignInAsync(dto.UserName, dto.Password, false, false); if (result.Succeeded) { return(Ok()); } } catch (Exception ex) { _logger.LogError($"Exception thrown while logging in: {ex}"); } return(BadRequest("Failed to login")); }
public PlayerModule(SpotifyConnection spotifyConnection, PlayerStore playerStore, PlayerConnection playerConnection) : base("v1/player") { Get("token", _ => spotifyConnection.GetCurrentToken()); Post("login", parameters => { CredentialDto credentialDto = this.Bind <CredentialDto>(); return(Response.AsJson(playerConnection.Login(credentialDto))); }); Post("signup", parameters => { SignUpDto signUpDto = this.Bind <SignUpDto>(); return(Response.AsJson(playerConnection.SignUp(signUpDto))); }); Get("info/{token}", parameters => { Guid sessionToken = Guid.Parse(parameters.token); return(playerStore.GetProfilOf(sessionToken)); }); }
public IActionResult Login([FromBody] CredentialDto credential) { User user; try { credential.Password = credential.Password.ToSha512(); user = context.Set <User>() .Where(x => x.Email == credential.Email && x.Password == credential.Password) .Select(x => new User { Id = x.Id, Email = x.Email }) .First(); } catch { throw new InvalidCredentialException(); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(configuration.GetValue <string>("JwtSecret")); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Email, user.Email.ToString()), new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), }), Expires = DateTime.UtcNow.AddHours(2), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var securityToken = tokenHandler.CreateToken(tokenDescriptor); var token = new TokenDto { Token = tokenHandler.WriteToken(securityToken) }; return(Ok(token)); }