public JsonResult Token([FromBody] Form form) { var username = form.UserName; var password = form.Password; var identity = GetIdentity(username, password); if (identity == null) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json("Invalid username or password.")); } var encodedJwt = JwtHelper.GenerateToken(identity.Claims); var refreshToken = RefreshTokenHelper.GenerateRefreshToken(); _refreshTokenRepository.Delete(username); _refreshTokenRepository.Save(username, refreshToken); var response = new AppTokenModel { AccessToken = encodedJwt, RefreshToken = refreshToken, Username = identity.Name }; return(Json(response)); }
public async Task <IActionResult> Login([FromBody] LoginFormResource credentials) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = await _userManager.Users.Include(u => u.Role).SingleOrDefaultAsync(u => u.NormalizedEmail == credentials.Email.ToUpper()); if (!await _userManager.CheckPasswordAsync(user, credentials.Password)) { return(Unauthorized()); } var identity = await GetClaimsIdentity(user); if (identity == null) { return(BadRequest(ModelState)); } var existingRefreshToken = await _refreshTokenRepository.GetByUserId(user.Id); if (existingRefreshToken == null) { var refreshToken = await _refreshTokenRepository.CreateToken(user.Id, ""); await _unitOfWork.CompleteAsync(); // TO DO: Create a response class with appropriate constructor var response = new { token = await _jwtFactory.GenerateEncodedToken(user.Id, credentials.Email, user.Role.Name), refreshToken = refreshToken, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds }; return(Ok(response)); } else { _refreshTokenRepository.Delete(existingRefreshToken); var token = await _refreshTokenRepository.CreateToken(user.Id, ""); await _unitOfWork.CompleteAsync(); // TO DO: Create a response class with appropriate constructor var response = new { token = await _jwtFactory.GenerateEncodedToken(user.Id, credentials.Email, user.Role.Name), refreshToken = token, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds }; return(Ok(response)); } }
public async Task <bool> RemoveRefreshToken(string refreshTokenId) { var refreshToken = await _context.RefreshTokens.FindAsync(refreshTokenId); if (refreshToken != null) { _refreshTokenRepository.Delete(refreshToken); return(await _unitOfWork.SaveChangesAsync() > 0); } return(false); }
public bool RemoveRefreshToken(string refreshTokenId) { var refreshToken = _refreshTokenRepository.GetById(refreshTokenId); if (refreshToken == null) { return(false); } _refreshTokenRepository.Delete(refreshToken); _unitOfWork.Commit(); return(true); }
public async Task <ActionResult <AuthTokenModel> > Refresh(RefreshTokenModel refreshTokenModel) { var principal = GetPrincipalFromExpiredToken(refreshTokenModel.Token); var userId = principal.GetLoggedInUserId();; if (string.IsNullOrEmpty(userId)) { throw new SecurityTokenException("Invalid refresh token"); } var user = await userRepository.Get(userId); var oldRefreshToken = await refreshTokenRepository.Get(userId, refreshTokenModel.RefreshToken); if (user == null || oldRefreshToken == null) { throw new SecurityTokenException("Invalid refresh token"); } await refreshTokenRepository.Delete(userId, oldRefreshToken.Id); var newToken = await GenerateToken(user); return(Ok(newToken)); }
public async Task <IActionResult> Refresh([FromBody] RefreshRequest refreshRequest) { if (!ModelState.IsValid) { return(BadRequestState()); } bool isValidRefreshToken = _refreshTokenValidator.Validate(refreshRequest.RefreshToken); if (!isValidRefreshToken) { return(BadRequest(new ErrorResponse("Invalid refresh token"))); } RefreshToken refreshTokenDTO = await _refreshTokenRepository.GetByToken(refreshRequest.RefreshToken); if (refreshTokenDTO == null) { return(NotFound(new ErrorResponse("Invalid refresh token"))); } _refreshTokenRepository.Delete(refreshTokenDTO.Id); User user = await _userRepository.GetById(refreshTokenDTO.UserId); if (user == null) { return(NotFound(new ErrorResponse("User not found"))); } AuthenticatedUserResponse response = await _authenticator.Authenticate(user); return(Ok(response)); }
public async Task <AuthenticatedUserDto> Handle(AuthWithRefreshToken request, CancellationToken cancellationToken) { if (request.Token == Guid.Empty) { throw new InvalidCredentialException("Invalid grant type"); } FilterDefinition <RefreshToken> filter = Builders <RefreshToken> .Filter .And(new FilterDefinition <RefreshToken>[] { Builders <RefreshToken> .Filter.Eq(x => x.Token, request.Token), Builders <RefreshToken> .Filter.Eq(x => x.IsActive, true), Builders <RefreshToken> .Filter.Lte(x => x.ExpirationDate, DateTime.UtcNow) }); RefreshToken refreshToken = await _refreshTokenRepository.Get(filter, cancellationToken); if (refreshToken == null) { throw new InvalidCredentialException("Invalid Credentials"); } User user = await _userRepository.Get(refreshToken.UserId, cancellationToken); if (user == null) { throw new InvalidCredentialException("Invalid Credentials"); } try { WebToken webToken = await _mediator.Send(new GenerateWebToken() { User = user }, cancellationToken); refreshToken.IsActive = false; await _refreshTokenRepository.Update(refreshToken, cancellationToken); await _refreshTokenRepository.Delete(Builders <RefreshToken> .Filter.Eq(x => x.IsActive, false), cancellationToken); return(new AuthenticatedUserDto { Token = webToken, User = _mapper.Map <UserDto>(user), }); } catch (Exception ex) { throw new InvalidCredentialException("", ex); } }
private async Task <Result> GetResult(DeleteRefreshTokenByTokenCommand command) { var token = _finder.All().Result.FirstOrDefault(t => t.TicketId == command.TicketId); if (token == null) { return(Result.Fail("Could not find token")); } await _repo.Delete(token); return(Result.Ok()); }
public bool Add(RefreshToken refreshToken) { var existingRefreshToken = _refreshTokenRepository .GetSingleByCondition(x => x.ClientId == refreshToken.ClientId && x.UserName == refreshToken.UserName); if (existingRefreshToken != null) { var resultRemove = _refreshTokenRepository.Delete(existingRefreshToken); if (resultRemove == null) { return(false); } } var entity = _refreshTokenRepository.Add(refreshToken); if (entity == null) { return(false); } _unitOfWork.Commit(); return(true); }
public void Delete(RefreshToken token) { using (var transaction = Connection.BeginTransaction()) { try { refreshTokenRepository.Delete(token); transaction.Commit(); } catch { transaction.Rollback(); throw; } } }
/// <summary> /// Deletes single refresh token /// </summary> /// <param name="entity">Token to delete</param> public void DeleteRefreshToken(RefreshToken entity) { //Validazione argomenti if (entity == null) { throw new ArgumentNullException(nameof(entity)); } //Esecuzione in transazione using (var t = DataSession.BeginTransaction()) { //Estrazione dati e commit _RefreshTokenRepository.Delete(entity); t.Commit(); } }
public bool RemoveRefreshToken(string refreshTokenId) { RefreshToken refreshToken = new RefreshToken(); refreshToken = _authService.FindRefreshToken(refreshTokenId); if (refreshToken == null) { return(false); } // _authService.RemoveRefreshToken(refreshToken); _refreshTokenRepository.Delete(refreshToken); return(true); }
public Task ReceiveAsync(AuthenticationTokenReceiveContext context) { var AllowedOrigin = context.OwinContext.Get <string>(GenericNames.OWIN_CONTEXT_CORS); context.OwinContext.Response.Headers.Remove(GenericNames.OWIN_CONTEXT_CORS_HEADER); context.OwinContext.Response.Headers.Add(GenericNames.OWIN_CONTEXT_CORS_HEADER, new[] { AllowedOrigin }); IDependencyScope Scope = context.OwinContext.Get <IDependencyScope>(); IRefreshTokenRepository refreshTokenRepository = Scope.GetService(typeof(IRefreshTokenRepository)) as IRefreshTokenRepository; var refreshToken = refreshTokenRepository.GetUniq(x => x.Id == context.Token); if (refreshToken != null) { context.DeserializeTicket(refreshToken.ProtectedTicket); refreshTokenRepository.Delete(refreshToken); } return(Task.FromResult <object>(null)); }
public async Task <string> GenerateRefreshToken(T user) { Guid refreshTokenGuid = Guid.NewGuid(); RefreshToken newToken = new RefreshToken { UserId = user.Id, Token = refreshTokenGuid, Expiry = DateTime.Now.AddYears(1) }; RefreshToken existingToken = this.refreshTokenRepository.GetAll().Where(x => x.UserId == user.Id).FirstOrDefault(); if (existingToken != null) { await refreshTokenRepository.Delete(existingToken); } await refreshTokenRepository.Add(newToken); return(refreshTokenGuid.ToString()); }
public async Task <AccessTokenDto> RefreshAccessTokenAsync(AccessTokenDto accessToken) { var principal = GetPrincipalFromExpiredToken(accessToken.Token); var userId = new Guid(principal.Identity.Name); var savedRefreshToken = await _refreshTokenRepository.GetByUserIdOrDefaultAsync(userId); if (savedRefreshToken.Token != accessToken.RefreshToken) { throw new SecurityTokenException($"Invalid refresh token for user with id {userId}"); } var newJwtToken = GenerateJwtToken(principal.Claims); var newRefreshToken = GenerateRefreshToken(); _refreshTokenRepository.Delete(savedRefreshToken); _refreshTokenRepository.Create(new RefreshToken { Token = newRefreshToken, UserId = userId }); await _saveProvider.SaveAsync(); return(new AccessTokenDto { RefreshToken = newRefreshToken, Token = newJwtToken }); }
public async Task DeleteRefreshToken(Expression <Func <RefreshToken, bool> > condition) { await _refreshTokenRepository.Delete(condition); }
public async Task <bool> Remove(string Id) { return(await _refreshRepository.Delete(Id)); }
public Task RevokeToken(int tokenId) { return(_refreshTokenRepository.Delete(tokenId)); }
public Task DeleteAsync(int id) { _tokenRepository.Delete(id); return(Task.FromResult <object>(null)); }
public bool RemoveRefreshToken(string id) { _refreshTokenRepository.Delete(GetAllRefreshTokens( ).FirstOrDefault(p => p.Id == id)); return(true); }
public Task RevokeRefreshToken(string token) { validationService.AssertNonNull(token, nameof(token)); return(refreshTokenRepo.Delete(token)); }