public ActionResult Token(string username, string password) { //sleep timer to demonstrate the loading bar Thread.Sleep(2000); //get user from data store var user = userService.GetByName(username); //validate password if (user == null) { return(BadRequest("Invalid credentials")); } if (user.Active != true) { return(BadRequest("Account not active")); } if (hashingService.VerifyHashedPassword(user.PasswordHash, password) == PasswordVerificationResult.Failed) { return(BadRequest("Invalid credentials")); } //create claims var claims = new List <Claim> { new Claim("uid", user.Id.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Integer) }; //create tokens var accessToken = jwtTokenService.GenerateAccessToken(user.UserName, null, claims); var refreshToken = jwtTokenService.GenerateRefreshToken(); //store refresh token jwtTokenService.StoreRefreshToken(user.Id, refreshToken); return(Ok(new JwtToken { AccessToken = accessToken, RefreshToken = refreshToken, TokenType = "bearer" })); }
public async Task <IActionResult> Login(UserForLoginDto loginDto) { var userFromRepo = await _repo.Login(loginDto.Username, loginDto.Password); if (userFromRepo == null) { return(Unauthorized()); } return(Ok(new { token = _tokenService.GenerateAccessToken(userFromRepo, DateTime.UtcNow.AddDays(1)), refreshToken = _tokenService.GenerateRefreshToken(userFromRepo, DateTime.UtcNow.AddDays(30)) })); }
public async Task <ActionResult <TokenResponseDTO> > RefreshToken() { HttpContext.Request.Cookies.TryGetValue("MyKey", out var refreshToken); if (string.IsNullOrWhiteSpace(refreshToken)) { return(Unauthorized()); } var hasValidRefreshToken = await _tokenService.CheckForValidRefreshToken(new RefreshToken { Token = refreshToken }); if (!hasValidRefreshToken) { return(Unauthorized()); } var token = await _context.RefreshTokens.FirstOrDefaultAsync(t => t.Token == refreshToken); var user = await _userManager.FindByIdAsync(token.UserId); var accessToken = new TokenResponseDTO { Token = await _tokenService.GenerateAccessToken(user.Email) }; return(Ok(accessToken)); }
public async Task <AuthorizeTokenResponse> GetTokenAsync( AuthorizeTokenRequest request, CancellationToken cancellationToken) { var result = new AuthorizeTokenResponse(); if (!await _userService.IsValidUserAsync(request.UserName, request.Password, cancellationToken)) { return(result); } var claims = new[] { new Claim(ClaimTypes.Name, request.UserName) }; try { result.Success = true; result.AccessToken = _jwtTokenService.GenerateAccessToken(claims); result.ExpiresIn = DateTimeOffset.UtcNow.AddMinutes(_jwtTokenOptions.AccessExpiration).Ticks; result.RefreshToken = _jwtTokenService.GenerateRefreshToken(); await _userService.UpdateRefreshTokenAsync( request.UserName, result.RefreshToken, DateTime.Now.Add(TimeSpan.FromMinutes(_jwtTokenOptions.AccessExpiration)), cancellationToken); } catch { result.Success = false; } return(result); }