Beispiel #1
0
        public async Task <ExchangeRefreshTokenResponse?> Handle(ExchangeRefreshTokenRequest message)
        {
            var claimsPrincipal = _jwtValidator.GetPrincipalFromToken(message.AccessToken);

            if (claimsPrincipal == null)
            {
                // invalid token/signing key was passed and we can't extract user claims
                return(ReturnError(AuthenticationError.InvalidToken));
            }

            var id   = claimsPrincipal.Claims.First(x => x.Type == "id");
            var user = await _userRepository.FindById(id.Value);

            if (user == null)
            {
                return(ReturnError(AuthenticationError.UserNotFound));
            }

            if (!user.HasValidRefreshToken(message.RefreshToken))
            {
                return(ReturnError(AuthenticationError.InvalidToken));
            }

            var jwToken = await _jwtFactory.GenerateEncodedToken(user.Id, user.UserName);

            var refreshToken = _tokenFactory.GenerateToken();

            user.RemoveRefreshToken(message.RefreshToken);
            user.AddRefreshToken(refreshToken, message.RemoteIpAddress);

            await _userRepository.Update(user);

            return(new ExchangeRefreshTokenResponse(jwToken, refreshToken));
        }
        public async Task <bool> Handle(ExchangeRefreshTokenRequest message, IOutputPort <ExchangeRefreshTokenResponse> outputPort)
        {
            var cp = _jwtTokenValidator.GetPrincipalFromToken(message.AccessToken, message.SigningKey);

            // invalid token/signing key was passed and we can't extract user claims
            if (cp != null)
            {
                var id   = cp.Claims.First(c => c.Type == "id");
                var user = await _userRepository.GetSingleBySpec(new UserSpecification(id.Value));

                if (user.HasValidRefreshToken(message.RefreshToken))
                {
                    var jwtToken = await _jwtFactory.GenerateEncodedToken(user.IdentityId, user.UserName, new List <string> {
                        "ROLE_ADMINISTRADOR"
                    });

                    var refreshToken = _tokenFactory.GenerateToken();
                    user.RemoveRefreshToken(message.RefreshToken);   // delete the token we've exchanged
                    user.AddRefreshToken(refreshToken, user.Id, ""); // add the new one
                    await _userRepository.Update(user);

                    outputPort.Handle(new ExchangeRefreshTokenResponse(jwtToken, refreshToken, true));
                    return(true);
                }
            }
            outputPort.Handle(new ExchangeRefreshTokenResponse(false, "Invalid token."));
            return(false);
        }
        public async Task Handle(ExchangeRefreshTokenRequest message, IOutputPort <ExchangeRefreshTokenResponse> outputPort)
        {
            if (!message.IsValid())
            {
                NotifyValidationErrors(message);
                return;
            }

            var cp = _jwtTokenValidator.GetPrincipalFromToken(message.AccessToken, message.SigningKey);

            // invalid token/signing key was passed and we can't extract user claims
            if (cp != null)
            {
                var id   = cp.Claims.First(c => c.Type == "id");
                var user = await _userRepository.GetSingleBySpec(new UserSpecification(id.Value));

                if (user.HasValidRefreshToken(message.RefreshToken))
                {
                    var jwtToken = await _jwtFactory.GenerateEncodedToken(user.Id.ToString(), user.UserName);

                    var refreshToken = _tokenFactory.GenerateToken();
                    user.RemoveRefreshToken(message.RefreshToken);   // delete the token we've exchanged
                    user.AddRefreshToken(refreshToken, user.Id, ""); // add the new one
                    _userRepository.Update(user);

                    if (Commit())
                    {
                        outputPort.Handle(new ExchangeRefreshTokenResponse(jwtToken, refreshToken));
                        return;
                    }
                }
            }

            await Bus.RaiseEvent(new DomainNotification(message.MessageType, "Failed to refresh token"));
        }
        public async Task <ExchangeRefreshTokenResponse> ExchangeRefreshTokenAsync(ExchangeRefreshTokenRequest message)
        {
            var cp = _jwtTokenValidator.GetPrincipalFromToken(message.AccessToken, message.SigningKey);

            // invalid token/signing key was passed and we can't extract user claims
            if (cp == null)
            {
                return(new ExchangeRefreshTokenResponse(false, "Invalid token."));
            }

            var id   = cp.Claims.First(c => c.Type == "id");
            var user = await _userRepository.GetSingleBySpec(new UserSpecification(id.Value));

            if (!user.HasValidRefreshToken(message.RefreshToken))
            {
                return(new ExchangeRefreshTokenResponse(false, "Invalid token."));
            }

            var jwtToken = await _jwtFactory.GenerateEncodedToken(user.Id.ToString(), user.Username);

            var refreshToken = _tokenFactory.GenerateToken();

            user.RemoveRefreshToken(message.RefreshToken);   // delete the token we've exchanged
            user.AddRefreshToken(refreshToken, user.Id, ""); // add the new one
            await _userRepository.Update(user);

            return(new ExchangeRefreshTokenResponse(jwtToken, refreshToken, true));
        }
        //FINISH THIS
        public async Task <LoginResponse> RefreshToken(ExchangeRefreshTokenRequest refreshTokenRequest)
        {
            var claimPrincipal =
                this.jwtTokenValidator.GetPrincipalFromToken(refreshTokenRequest.AccessToken,
                                                             "ArminVanBuurenMottyzeRuleTheWorldForever2010");

            if (claimPrincipal != null)
            {
                var id   = claimPrincipal.Claims.First(c => c.Type == "id");
                var user = await this.repository.GetSingleBySpec(new UserSpecification(id.Value));

                var appUser = await this.userManager.FindByIdAsync(user.IdentityId).ConfigureAwait(false);

                if (user.HasValidRefreshToken(refreshTokenRequest.RefreshToken))
                {
                    var jwtToken = await this.jwtFactory.GenerateEncodedToken(user.IdentityId, appUser.Email);

                    var refreshToken = this.tokenFactory.GenerateToken();
                    user.RemoveRefreshToken(refreshTokenRequest.RefreshToken);                                                           // delete the token we've exchanged
                    user.AddRefreshToken(new RefreshToken(refreshToken, DateTime.UtcNow.AddDays(5), user.Identity.Email, string.Empty)); // add the new one
                    await this.repository.Update(user);

                    return(new LoginResponse(jwtToken, refreshToken, true));
                }
            }

            return(null);
        }
Beispiel #6
0
        public async Task <ActionResult> RfrshTkn([FromBody] ExchangeRefreshTokenRequest loginUser)
        {
            _logger.LogInfo($"refresh token.");

            if (!ModelState.IsValid)
            {
                _logger.LogInfo("All required");
                return(BadRequest(ModelState));
            }
        }
Beispiel #7
0
        public async Task <ActionResult> RefreshToken([FromBody] ExchangeRefreshTokenRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            await exchangeRefreshTokenUseCase.Handle(
                new Core.Dto.UseCaseRequests.ExchangeRefreshTokenRequest(request.AccessToken, request.RefreshToken,
                                                                         authSettings.SecretKey), exchangeRefreshTokenPresenter);

            return(exchangeRefreshTokenPresenter.ContentResult);
        }
        private async Task ExchangeRefreshTokenAsync(string accessToken, string refreshToken, CancellationToken cancellationToken)
        {
            var exchangeRefreshTokenRequest = new ExchangeRefreshTokenRequest {
                AccessToken = accessToken, RefreshToken = refreshToken
            };

            _settingsService.AuthAccessToken = string.Empty;
            var result = await PostAsync <ExchangeRefreshTokenRequest, ExchangeRefreshTokenResponse>($"{MiscConstants.StockAlertsApiBaseUri}refresh-tokens", exchangeRefreshTokenRequest);

            _settingsService.AuthAccessToken  = result.AccessToken.Token;
            _settingsService.AuthRefreshToken = result.RefreshToken;
        }
Beispiel #9
0
        public async Task <ActionResult> RefreshToken([FromBody] ExchangeRefreshTokenRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var response = await _authService.ExchangeRefreshTokenAsync(
                new ExchangeRefreshTokenRequest(request.AccessToken, request.RefreshToken, _authSettings.SecretKey));

            return(Ok(response));
        }
        public async Task <ActionResult <AuthTokenResult> > RefreshToken(
            [FromBody] ExchangeRefreshTokenRequest request)
        {
            var userName = _jwtFactory.DecodeToken(request.AccessToken);

            if (userName == null)
            {
                return(BadRequest("No user with that auth token"));
            }

            var user = await _userManager
                       .Users
                       .Include(u => u.RefreshTokens)
                       .SingleOrDefaultAsync(
                r => r.UserName == userName &&
                r.RefreshTokens.Any(p =>
                                    p.Token.Equals(request.RefreshToken) &&
                                    p.CreateDate >= System.DateTime.Now.AddDays(-28)));

            if (user == null)
            {
                return(BadRequest("Cannot find your refresh token"));
            }

            var roles = await _userManager.GetRolesAsync(user);

            var identity = _jwtFactory.GenerateClaimsIdentity(userName, user.Id);

            try {
                var(token, refresh) = await _getTokenAndRefresh(identity, userName, roles.ToArray <string>(), user);

                return(Ok(new AuthTokenResult {
                    Id = user.Id,
                    Slug = user.Slug,
                    Name = user.GetBestGuessName(),
                    Auth = refresh
                }));
            } catch (DbUpdateConcurrencyException e) {
                _logger.LogError($"Error updating user's token.\n{e.Message}");
                return(StatusCode(503));
            }
        }
Beispiel #11
0
    public async Task <bool> Handle(ExchangeRefreshTokenRequest message, IOutputPort <ExchangeRefreshTokenResponse> outputPort)
    {
        var cp = _jwtTokenValidator.GetPrincipalFromToken(message.AccessToken, message.SigningKey);

        // invalid token/signing key was passed and we can't extract user claims
        if (cp != null)
        {
            Claim claim = cp.Claims.First(c => c.Type == "id");
            var   user  = await _userRepository.GetSingleBySpec(new UserSpecification(claim.Value));

            if (user != null && user.HasValidRefreshToken(message.RefreshToken))
            {
                var jwtToken = await _jwtFactory.GenerateEncodedToken(user.IdentityId, user.UserName);

                var refreshToken = _tokenFactory.GenerateToken();
                user.RemoveRefreshToken(message.RefreshToken); // delete the token we've exchanged
                user.AddRefreshToken(refreshToken, "");        // add the new one
                await _userRepository.Update(user);

                outputPort.Handle(new ExchangeRefreshTokenResponse(jwtToken, refreshToken, true));
                return(true);
            }
            else if (user == null)
            {
                outputPort.Handle(new ExchangeRefreshTokenResponse(new List <Error>()
                {
                    new Error(HttpStatusCode.BadRequest.ToString(), "Invalid user!")
                }));
            }
        }
        outputPort.Handle(new ExchangeRefreshTokenResponse(new List <Error>()
        {
            new Error(HttpStatusCode.BadRequest.ToString(), "Invalid token!")
        }));
        return(false);
    }
Beispiel #12
0
        public async Task <ActionResult <ExchangeRefreshTokenResponseModel> > RefreshToken([FromBody] ExchangeRefreshTokenRequest request)
        {
            if (request == null)
            {
                ModelState.AddModelError("Message", "Unable to locate payload for refresh token request");
                return(BadRequest(ModelState));
            }

            var userName        = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userFromManager = await _userManager.FindByNameAsync(userName);

            var userFromRepo = await _userRepository.GetAsync(u => u.UserName == userName);

            if (userFromManager != null && userFromRepo != null)
            {
                if (userFromManager.Active == false)
                {
                    return(StatusCode(401, "User no longer active"));
                }

                if (userFromRepo.HasValidRefreshToken(request.RefreshToken))
                {
                    var jwtToken = await _jwtFactory.GenerateEncodedToken(userFromRepo, await _userManager.GetRolesAsync(userFromManager));

                    // delete existing refresh token
                    _refreshTokenRepository.Delete(userFromRepo.RefreshTokens.Single(a => a.Token == request.RefreshToken));

                    // generate refresh token
                    var refreshToken = _tokenFactory.GenerateToken();
                    userFromRepo.AddRefreshToken(refreshToken, HttpContext?.Connection?.RemoteIpAddress?.ToString());

                    _userRepository.Update(userFromRepo);
                    await _unitOfWork.CompleteAsync();

                    return(new ExchangeRefreshTokenResponseModel()
                    {
                        AccessToken = jwtToken, RefreshToken = refreshToken
                    });
                }
            }

            return(StatusCode(404, "User does not have valid refresh token"));
        }
        public async Task <IActionResult> ExchangeRefreshTokenAsync([FromBody] ExchangeRefreshTokenRequest exchangeRefreshTokenRequest, CancellationToken cancellationToken)
        {
            var result = await _authService.ExchangeRefreshTokenAsync(exchangeRefreshTokenRequest.AccessToken, exchangeRefreshTokenRequest.RefreshToken, cancellationToken);

            return(new OkObjectResult(result));
        }