コード例 #1
0
        public async Task <Result <ValidateTokenResult> > Handle(ValidateTokenCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var validate = _jwtService.ValidateToken(request.AccessToken);

                if (validate == null)
                {
                    return(Result <ValidateTokenResult> .Fail(new Error(nameof(JwtService.ValidateToken), "Token is not valid")));
                }

                var userSession = await _userSessionRepository.FindByAccessTokenAsync(request.AccessToken);

                if (userSession == null || !userSession.IsActive(request.AccessToken))
                {
                    return(Result <ValidateTokenResult> .Fail(new Error(nameof(UserSession.IsActive), "Token is not active")));
                }

                return(Result <ValidateTokenResult> .Success(new ValidateTokenResult()));
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);

                return(Result <ValidateTokenResult> .Fail(Error.Default()));
            }
        }
コード例 #2
0
        public async Task ShoudNotReset_TokenExpiration_WhenToken_IsExpired(
            long id, string username, string password, int minutes)
        {
            var testToken      = new Token(id, username, password, TimeSpan.FromMinutes(minutes));
            var initialValidTo = testToken.ValidTo;

            var spec = TokenSpecification.GetNotExpiredByValue(testToken.Value);

            _fixture.Data
            .Setup(x => x.Tokens.SingleOrDefaultAsync(It.IsAny <TokenSpecification>()))
            .Returns(Task.FromResult(testToken));

            _fixture.Configuration
            .Setup(x => x.ValidDurationInMinutes)
            .Returns(minutes);

            var command = new ValidateTokenCommand
            {
                Value = testToken.Value
            };

            var resultToken = await _fixture.Handler.Handle(command, CancellationToken.None);

            Assert.True(initialValidTo == resultToken.ValidTo);
        }
コード例 #3
0
        public async Task ShoudNotThrow_Exception_WhenValidToken(
            long id, string username, string password, int minutes)
        {
            var testToken = new Token(id, username, password, TimeSpan.FromMinutes(minutes));

            var spec = TokenSpecification.GetNotExpiredByValue(testToken.Value);

            _fixture.Data
            .Setup(x => x.Tokens.SingleOrDefaultAsync(It.IsAny <TokenSpecification>()))
            .Returns(Task.FromResult(testToken));

            _fixture.Configuration
            .Setup(x => x.ValidDurationInMinutes)
            .Returns(minutes);

            var command = new ValidateTokenCommand
            {
                Value = testToken.Value
            };

            var exception = await Record.ExceptionAsync(
                () => _fixture.Handler.Handle(command, CancellationToken.None));

            Assert.True(exception == null);
        }
コード例 #4
0
        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            try
            {
                var validateTokenCommand = new ValidateTokenCommand
                {
                    Value = securityToken
                };
                var token = _mediator.Send(validateTokenCommand).GetAwaiter().GetResult();

                var getUserQuery = new GetUserQuery
                {
                    Id = token.UserId
                };
                var user = _mediator.Send(getUserQuery).GetAwaiter().GetResult();

                var identity = new ClaimsIdentity("Custom");
                identity.AddClaim(new Claim(ClaimTypes.Name, user.Name));
                identity.AddClaim(new Claim("Id", user.Id.ToString()));

                var result = new ClaimsPrincipal(identity);
                validatedToken = new AuthenticationToken(token.Id.ToString(), token.ValidFrom, token.ValidTo);
                return(result);
            }
            catch (AuthenticationApplicationException ex)
            {
            }

            validatedToken = null;
            return(null);
        }
コード例 #5
0
        public async Task <IActionResult> ValidateToken([FromBody] ValidateTokenCommand authData, CancellationToken token = default(CancellationToken))
        {
            ModelState.ThrowValidationExceptionIfInvalid <Account.Errors>();

            await commandFactory.Execute(authData);

            return(Ok());
        }
コード例 #6
0
        public async Task ShoudThrow_AuthenticationApplicationException_WhenInvalidToken(string value)
        {
            Token token = null;

            _fixture.Data
            .Setup(x => x.Tokens.SingleOrDefaultAsync(It.IsAny <TokenSpecification>()))
            .Returns(Task.FromResult(token));

            var command = new ValidateTokenCommand
            {
                Value = value
            };

            await Assert.ThrowsAsync <AuthenticationApplicationException>(
                () => _fixture.Handler.Handle(command, CancellationToken.None));
        }
コード例 #7
0
        public void OnActionExecuting(ActionExecutingContext actionContext)
        {
            var tokenValue = actionContext
                             .HttpContext
                             .Request
                             .Headers
                             .Where(x => x.Key == "Bearer")
                             .Select(x => x.Value.FirstOrDefault())
                             .FirstOrDefault();

            var command = new ValidateTokenCommand
            {
                Value = tokenValue
            };

            var token = _mediator.Send(command).GetAwaiter().GetResult();

            _currentUser.Id = token.UserId;
        }
コード例 #8
0
        public async Task <IActionResult> Validate([FromBody] ValidateTokenCommand validateTokenCommand)
        {
            var result = await _mediator.Send(validateTokenCommand);

            return(result ? Json(new { HttpStatusCode.OK }) : (IActionResult)BadRequest());
        }