public async Task <ActionResult <UserDto> > Login(UserDto login) { _logger.LogInformation("Login from " + login.Email); login.Email = login.Email.ToLower(); var user = await _context.User.Where(u => u.Email == login.Email).FirstOrDefaultAsync(); if (user != null) { var validPwd = Verify(login.Password, user.PwHash); if (validPwd) { login.Password = null; var token = new TokenDto(); token.JWT = GenerateToken(user); login.AccessJWTToken = token.JWT; var hash = HashJwt(token.JWT); user.AccessJWTToken = hash; await _context.SaveChangesAsync(); login.FullName = user.FullName; return(login); } } _logger.LogInformation("user not found: " + login.Email); ModelState.AddModelError(string.Empty, "Wrong username or password"); return(BadRequest(ModelState)); }
public TokenDto CreateToken(Cavus cavus) { var AccesTokenOmru = DateTime.Now.AddMinutes(_customTokenOptions.AccesTokenO); //Token ömrünü al var RefreshTokenOmru = DateTime.Now.AddMinutes(_customTokenOptions.RefreshTokenO); //Refresh token ömrünü al var SecuritKey = CustomSecurity.GetSymetricSecurityKey(_customTokenOptions.SecuritKey); SigningCredentials signingCredentials = new SigningCredentials(SecuritKey, SecurityAlgorithms.HmacSha256Signature); //imzamızı oluşturuyoruz JwtSecurityToken jwtSecurityToken = new JwtSecurityToken( issuer: _customTokenOptions.Issuer, expires: AccesTokenOmru, notBefore: DateTime.Now, claims: GetClaim(cavus, _customTokenOptions.Audience), signingCredentials: signingCredentials); var handler = new JwtSecurityTokenHandler(); var token = handler.WriteToken(jwtSecurityToken); var tokenDto = new TokenDto { AccessToken = token, RefreshToken = CreateRefreshToken(), AccesTokenLifeTime = AccesTokenOmru, RefreshTokenLifeTime = RefreshTokenOmru }; return(tokenDto); }
public void BuscarVentaPorFolio() { TokenDto token = new TokenDto(3215, 3); VentaResponse reponse = new SalesBusiness(token).BuscarVentaPorFolio("5", 0); Assert.IsNotNull(reponse); }
public TokenDto CreateToken(UserApp userApp) { var accessTokenExpiration = DateTime.Now.AddMinutes(_tokenOption.AccessTokenExpiration); var refreshTokenExpiration = DateTime.Now.AddMinutes(_tokenOption.RefreshTokenExpiration); var securityKey = SignService.GetSymmetricSecurityKey(_tokenOption.SecurityKey); SigningCredentials signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); JwtSecurityToken jwtSecurityToken = new JwtSecurityToken( issuer: _tokenOption.Issuer, expires: accessTokenExpiration, notBefore: DateTime.Now, claims: GetClaims(userApp, _tokenOption.Audience), signingCredentials: signingCredentials ); var handler = new JwtSecurityTokenHandler(); var token = handler.WriteToken(jwtSecurityToken); var tokenDto = new TokenDto { AccessToken = token, RefreshToken = CreateRefreshToken(), AccessTokenExpiration = accessTokenExpiration, RefreshTokenExpiration = refreshTokenExpiration }; return(tokenDto); }
public IActionResult decode([FromBody] TokenDto token) { try { string tokenStream = token.TokenString; // _config["Token:TokenSecretKey"]; var handler = new JwtSecurityTokenHandler(); var jsonToken = handler.ReadJwtToken(tokenStream); var tokenS = handler.ReadJwtToken(tokenStream) as JwtSecurityToken; var name = tokenS.Claims.First(Claim => Claim.Type == "unique_name").Value; var email = tokenS.Claims.First(Claim => Claim.Type == "email").Value; var userId = tokenS.Claims.First(Claim => Claim.Type == "User Id").Value; var phone = tokenS.Claims.First(Claim => Claim.Type == "Phone").Value; var address1 = tokenS.Claims.First(Claim => Claim.Type == "Address1").Value; var address2 = tokenS.Claims.First(Claim => Claim.Type == "Address2").Value; var address3 = tokenS.Claims.First(Claim => Claim.Type == "Address3").Value; var city = tokenS.Claims.First(Claim => Claim.Type == "City").Value; var country = tokenS.Claims.First(Claim => Claim.Type == "Country").Value; var status = "successful"; return(Ok(new { status, name, email, userId, phone, address1, address2, address3, city, country })); } catch (Exception ex) { var status = "fail!"; return(BadRequest(status)); } }
/// <summary> /// Metodo para obtener el cashout /// </summary> /// <param name="token"></param> /// <returns></returns> public ResponseBussiness <CompendioCashOut> ObtenerCashOut(TokenDto token) { return(tryCatch.SafeExecutor(() => { return inicioFinDiaRepository.ObtenerCashOut(token); })); }
/// <summary> /// Verifies the specified token and return the user id. /// </summary> /// <param name="token"></param> /// <returns></returns> public async Task <string> VerifyToken(string token) { TokenDto tokenDto = new TokenDto() { Token = token }; try { using (HttpClient httpClient = new HttpClient()) { var response = await httpClient.PostAsJsonAsync(_authBaseUrl + "Auth", tokenDto).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { throw new AuthenticationException(); } else { return(await response.Content.ReadAsAsync <string>()); } } } catch (Exception e) { throw new Exception(e.Message); } }
public IActionResult Token([FromBody] TokenDto token) { var jwtIssuerOptions = JwtBearerConfigureOptions.GetJwtIssuerOptions(_configuration); if (!jwtIssuerOptions.AccessKey.Contains(token.AccessKey) || !jwtIssuerOptions.SecretKey.Contains(token.SecretKey)) { return(NotFound <string>(null)); } var claims = new List <Claim> { new Claim(ClaimsIdentity.DefaultNameClaimType, token.AccessKey) }; var claimsIdentity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); var utcNow = DateTime.UtcNow; // создаем JWT-токен var jwtSecurityToken = new JwtSecurityToken( issuer: jwtIssuerOptions.Issuer, notBefore: utcNow, claims: claimsIdentity.Claims, expires: utcNow.Add(TimeSpan.FromMinutes(jwtIssuerOptions.LifetimeInMinutes)), signingCredentials: new SigningCredentials(JwtBearerConfigureOptions.GetSymmetricSecurityKey(jwtIssuerOptions.SigningKey), SecurityAlgorithms.HmacSha256)); var accessToken = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken); return(Ok(accessToken)); }
public async Task <IActionResult> Login([FromBody] SignIn command) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var account = await _authService.LoginAsync(command.Email, command.Password); if (account == null) { return(Unauthorized()); } var token = new TokenDto { Token = await GenerateToken(account, _jwtSettings) }; return(Json(new { LoginData = token, account.Role, account.Name, account.Surname, account.Email, account.PhoneNumber })); }
public IApplyPlayerSelectionDataSetCommonBuilder WithSelection(TokenDto tokenPlayer, int selectedLine, int selectedColumn) { this.tokenPlayer = tokenPlayer; this.selectedLine = selectedLine; this.selectedColumn = selectedColumn; return(this); }
public async Task <SessionDto> CreateSession(User user, string ipAddress = null) { user = await _userManager.FindByIdAsync(user.Id); var roles = (await _userManager.GetRolesAsync(user)).ToList(); Logger.LogInformation("Creating session for user {UserId}", user.Id); var refreshToken = await RefreshTokensService.CreateRefreshToken(user, ipAddress); var session = new SessionDto { Profile = new UserProfileDto { Id = user.Id, Username = user.UserName, Roles = roles, Fullname = user.FullName, }, AccessToken = _jwtFactory.GenerateToken(user.Id, user.UserName, roles, _jwtOptions.CalcExpiration()), RefreshToken = TokenDto.FromRefreshTokenEntity(refreshToken) }; return(session); }
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 <TokenDto> SignIn(SignInDto signInDto) { var user = await userRepository.FindByLoginAsync(signInDto.Email); TokenDto tokenDto = new TokenDto(); if (user == null || user.StatusOfVerification == "Processing" || user.StatusOfVerification == "Blocked") { tokenDto.Code = 401; return(tokenDto); } if (signInDto.Email != user.Email || !VerifyPassword(signInDto.Password, user.HashPassword, user.Salt)) { tokenDto.Code = 401; return(tokenDto); } //Return two tokens Access, Refresh tokenDto.Name = user.FirstName; tokenDto.Code = 200; tokenDto.AccessToken = token.GenerateToken(user); tokenDto.RefreshToken = token.RefreshGenerateToken(); //Save To database Refresh token RefreshTokens refreshToken = new RefreshTokens(tokenDto.RefreshToken, user.Id, true); refreshRepository.Create(refreshToken); await refreshRepository.SaveChangesAsync(); return(tokenDto); }
public async Task <TokenDto> GetToken(TokenDto user) { // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Audience = _appSettings.Audience, Issuer = _appSettings.Issuer, Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.GUID.ToString()), new Claim(ClaimTypes.Role, user.Type) }), Expires = DateTime.Now.AddDays(30), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); user.Token = tokenHandler.WriteToken(token); // remove password before returning // user.PWD = null; return(user); }
private InicioDiaResponse RealizarInicioDiaInternal(TokenDto token) { InicioDiaResponse inicioDiaResponse = new InicioDiaResponse(); inicioDiaResponse = inicioFinDiaRepository.InicioDia(token); return(inicioDiaResponse); }
private async Task <TokenDto> GenerateJwtToken(string email, IdentityUser user) { var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(ClaimTypes.NameIdentifier, user.Id) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes( configuration["JwtKey"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); // recommednded is 5 mins var expires = DateTime.Now.AddDays( Convert.ToDouble(configuration["JwtExpireDays"])); var token = new JwtSecurityToken( configuration["JwtIssuer"], configuration["JwtIssuer"], claims, expires: expires, signingCredentials: creds ); var response = new TokenDto { Email = email, Token = new JwtSecurityTokenHandler().WriteToken(token) }; return(response); }
/// <summary> /// Metodo para realizar el fin de día /// </summary> /// <param name="token"></param> /// <returns></returns> public ResponseBussiness <FinDiaResponse> RealizarFinDia(TokenDto token) { return(tryCatch.SafeExecutor(() => { return inicioFinDiaRepository.FinDia(token); })); }
public TokenDto GenerateToken(string userName) { string token = Guid.NewGuid().ToString(); DateTime issuedOn = DateTime.Now; DateTime expiredOn = DateTime.Now.AddSeconds(_SessionTimeout); var tokendomain = new Token { UserName = userName, AuthToken = token, IssuedOn = issuedOn, ExpiresOn = expiredOn }; using (var db = new A77DbContext()) { //db.Token.Add(tokendomain); db.Token.AddOrUpdate(tokendomain); db.SaveChanges(); } var tokenDto = new TokenDto { UserName = tokendomain.UserName, AuthToken = tokendomain.AuthToken, ExpiresOn = tokendomain.ExpiresOn, IssuedOn = tokendomain.IssuedOn }; return(tokenDto); }
public void Buscar() { TokenDto token = new TokenDto(3215, 3); var valor = new AdministracionVentaEmpleadoBusiness().Buscar("1717", "3215", "3"); Assert.IsNotNull(valor); }
public async Task Should_Login() { // Arrange User user = FakeUsers.Admin; var loginDto = new LoginDto { UsernameOrEmail = user.UserName, Password = UserSeedData.ValidPassword }; // Act HttpResponseMessage responseMessage = await _unAuthenticatedServer .CreateClient() .PostAsync(ApiEndpoints.AuthController.Login(), BuildStringContent(loginDto)); // Assert responseMessage.StatusCode.Should().Be(HttpStatusCode.OK); TokenDto result = await DeserializeResponseMessageAsync <TokenDto>(responseMessage); result.Token.Should().NotBeNullOrEmpty(); JwtSecurityToken decryptedToken = new JwtSecurityTokenHandler().ReadJwtToken(result.Token); decryptedToken.Claims.First(c => c.Type == JwtRegisteredClaimNames.NameId).Value.Should().Be(user.UserName); decryptedToken.Claims.First(c => c.Type == JwtRegisteredClaimNames.Name).Value.Should().Be(user.DisplayName); decryptedToken.Claims.First(c => c.Type == JwtRegisteredClaimNames.Sub).Value.Should().Be(user.Id.ToString()); decryptedToken.Claims.First(c => c.Type == "https://localhost:5001/person_id")?.Value.Should().Be(user.PersonId.ToString()); var refreshToken = GetCookieValueFromResponse(responseMessage, "refreshToken"); refreshToken.Should().NotBeNullOrEmpty(); }
private async Task <TokenDto> GenerateJwtToken(string email, MODUser user) { var roles = await userManager.GetRolesAsync(user); var role = roleManager.Roles.SingleOrDefault(r => r.Name == roles.SingleOrDefault()); var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim(ClaimTypes.Role, role.Name) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes( configuration["JwtKey"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var expires = DateTime.Now.AddDays( Convert.ToDouble(configuration["JwtExpireDays"])); var token = new JwtSecurityToken( configuration["JwtIssuer"], configuration["JwtIssuer"], claims, expires: expires, signingCredentials: creds); var response = new TokenDto { Key = new JwtSecurityTokenHandler().WriteToken(token), Email = email }; return(response); }
public async Task Should_Logout() { // Arrange HttpClient client = _unAuthenticatedServer .CreateClient(); User user = UserTestSeedData.Staff; var loginDto = new LoginDto { UsernameOrEmail = user.UserName, Password = UserSeedData.ValidPassword }; HttpResponseMessage loginResult = await client .PostAsync(ApiEndpoints.AuthController.Login(), BuildStringContent(loginDto)); TokenDto tokenDto = await DeserializeResponseMessageAsync <TokenDto>(loginResult); // Act HttpRequestMessage request = CreateRequestWithCookie(HttpMethod.Post, ApiEndpoints.AuthController.Logout(), loginResult); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenDto.Token); HttpResponseMessage responseMessage = await client.SendAsync(request); // Assert responseMessage.StatusCode.Should().Be(HttpStatusCode.NoContent); HttpResponseMessage refreshMessage = await client.SendAsync( CreateRequestWithCookie(HttpMethod.Post, ApiEndpoints.AuthController.RefreshToken(), loginResult)); refreshMessage.StatusCode.Should().Be(HttpStatusCode.Unauthorized); }
public TokenDto GenerateToken(Guid userId, string email) { var now = DateTime.Now; var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.UniqueName, userId.ToString()), new Claim(JwtRegisteredClaimNames.Sub, email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, now.ToTimeStamp().ToString(), ClaimValueTypes.Integer64) }; var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Key)), SecurityAlgorithms.HmacSha256); var expires = now.AddMinutes(jwtSettings.ExpiryTime); var jwt = new JwtSecurityToken( issuer: jwtSettings.Issuer, claims: claims, notBefore: now, expires: expires, signingCredentials: signingCredentials); var token = new JwtSecurityTokenHandler().WriteToken(jwt); var tokenDto = new TokenDto(token, expires, userId, email); return(tokenDto); }
public IActionResult Refresh(TokenDto tokenDto) { if (tokenDto.AccessToken == null || tokenDto.RefreshToken == null) { return(BadRequest("Invalid client request")); } var userToCreate = _mapper.Map <User>(tokenDto); tokenDto.AccessToken = _tokenService.CreateToken(userToCreate); tokenDto.RefreshToken = _tokenService.GenerateRefreshToken(); var userToken = new UserToken { User = userToCreate, RefreshToken = tokenDto.RefreshToken }; _tokenService.RevokeNewRefreshToken(userToken); if (userToCreate == null || userToken.RefreshToken == null || userToken.RefreshTokenExpiryTime <= DateTime.Now) { return(BadRequest("Invalid client request")); } return(Ok(userToken)); }
public async Task <TokenDto> CreateOauthTokenForZoomAsync(string code) { RestClient restClient = new RestClient(); var request = new RestRequest(); restClient.BaseUrl = new Uri(string.Format(WebConfigurationManager.AppSettings["AccessTokenUrl"], code, WebConfigurationManager.AppSettings["ZoomRedirectUrl"])); request.AddHeader("Authorization", string.Format(AuthorizationHeader)); var response = restClient.Post(request); string ResponseString = ""; var token = new TokenDto(); if (response.StatusCode == System.Net.HttpStatusCode.OK) { //var a = response.Content; ResponseString = JsonConvert.DeserializeObject(response.Content).ToString(); var result = JsonConvert.DeserializeObject <TokenDto>(ResponseString); // gan cho OAuthTokenViewModel token.access_token = result.access_token.ToString(); // access Token token.refresh_token = result.refresh_token.ToString(); token.type = 2; } return(token); }
/// <summary> /// Business para validar operación de Corte Z Offline /// </summary> public ResponseBussiness <ValidacionOperacionResponse> ValidarCorteOffline(TokenDto token, AutenticacionOfflineRequest autenticacionOfflineRequest) { return(tryCatch.SafeExecutor(() => { return inicioFinDiaRepository.ValidarCorteOffline(token, autenticacionOfflineRequest); })); }
public async Task <ActionResult <TokenDto> > Register(RegisterViewModel reguser) { reguser.Email = reguser.Email.ToLower(); var emailExist = await _context.Users.Where(u => u.Email == reguser.Email).FirstOrDefaultAsync(); if (emailExist != null) { return(BadRequest(new { errorMessage = "Email Already in use" })); } User user = new User(); user.FirstName = reguser.FirstName; user.LastName = reguser.LastName; user.Email = reguser.Email; // = _mapper.Map<User>(reguser); if (reguser.Email == "*****@*****.**") { user.AccountType = Role.Admin; } else { user.AccountType = Role.Stockstrader; } user.PwHash = BCrypt.Net.BCrypt.HashPassword(reguser.Password, BcryptWorkfactor); _context.Users.Add(user); await _context.SaveChangesAsync(); var jwtToken = new TokenDto(); jwtToken.Token = GenerateToken(user); return(CreatedAtAction("Get", new { id = user.UserId }, jwtToken)); //return View(); }
/// <summary> /// Metodo para realizar el inicio de día /// </summary> /// <param name="token"></param> /// <returns></returns> public InicioDiaResponse RealizarInicioDia(TokenDto token) { return(tryCatch.SafeExecutor(() => { return RealizarInicioDiaInternal(token); })); }
private TokenDto GenerateJSONWebToken(User user) { var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Jwt:Key"])); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var claims = new List <Claim>(); var roles = userManager.GetRolesAsync(user).Result; foreach (var role in roles) { claims.Add(new Claim(ClaimTypes.Role, role)); } //claims.Add(new Claim(JwtRegisteredClaimNames.Sub, customer.UserName)) claims.Add(new Claim("Nickname", user.Nickname)); claims.Add(new Claim("Email", user.Email)); var tokenDescription = new JwtSecurityToken(config["Jwt:Issuer"], config["Jwt:Issuer"], claims: claims, null, expires: DateTime.Now.AddMinutes(120), signingCredentials: credentials); var token = new JwtSecurityTokenHandler().WriteToken(tokenDescription); var tokenDto = new TokenDto { Value = token }; return(tokenDto); }
public async Task <ActionResult <ApiResponse> > ValidateToken(TokenDto token) { try { await Task.Run(() => { var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtOptions.JwtKey)); var validationParams = new TokenValidationParameters { ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ClockSkew = TimeSpan.Zero, ValidIssuer = jwtOptions.JwtIssuer, ValidAudience = jwtOptions.JwtAudience, IssuerSigningKey = key }; var principal = new JwtSecurityTokenHandler() .ValidateToken(token.Token, validationParams, out SecurityToken validatedToken); }); return(new ApiResponse("Token validated succesfully", true)); } catch (Exception) { return(new ApiResponse("Token failed validation", false)); } }