public ActionResult ValidateToken([FromBody] ValidateTokenRequest validateTokenRequest)
        {
            try
            {
                bool result = _logic.ValidateToken(validateTokenRequest.token);

                if (result == false)
                {
                    return(StatusCode((500), new Response <string>
                    {
                        Status = "ERROR",
                        ResponseMessage = "ERROR",
                        ResponseData = "Token Not Valid"
                    }));
                }
            }
            catch (Exception e)
            {
                return(StatusCode((500), new Response <string>
                {
                    Status = "ERROR",
                    ResponseMessage = "ERROR",
                    ResponseData = e.Message
                }));
            }
            return(StatusCode((200), new Response <bool>
            {
                Status = "Token Is Valid",
                ResponseMessage = "Token Is Valid",
                ResponseData = true
            }));
        }
Пример #2
0
        private async Task <bool> IsValidToken(string token, string deviceId)
        {
            HttpClient client = new HttpClient();
            var        values = new Dictionary <string, string>
            {
                { "Token", token },
                { "DeviceId", deviceId }
            };

            var requestParam = new ValidateTokenRequest()
            {
                Token = token, DeviceId = deviceId
            };
            var content = new StringContent(JsonConvert.SerializeObject(requestParam), System.Text.Encoding.UTF8, "application/json");

            var fullUrl      = $"{_apiUrl}/validatetoken";
            var responseTask = await client.PostAsync(fullUrl, content);

            var responseString = await responseTask.Content.ReadAsStringAsync();

            var response = JsonConvert.DeserializeObject <ValidateTokenResponse>(responseString);

            Log.Debug(this, $"ValidateToken result: {(ResultCode)response.Result}");
            return((ResultCode)response.Result == ResultCode.Success);
        }
Пример #3
0
 public void IsTokenExpired_Test()
 {
     ValidateTokenRequest request = new ValidateTokenRequest {
         Context = "NG", Token = "53287900d6a4850ebc395f67", Version = 1
     };
     ValidateTokenResponse response = SecurityManager.ValidateToken(request, "Engineer");
 }
Пример #4
0
        public async Task <IActionResult> RefreshToken([FromBody] ValidateTokenRequest request)
        {
            // Get rid of bearer if it is still there
            string token = request.Token.Replace("Bearer ", "");

            var validationParams = new TokenValidationParameters
            {
                IssuerSigningKey      = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(config.GetValue <string>("Security:SigningKey"))),
                RequireSignedTokens   = true,
                ValidateIssuer        = true,
                ValidIssuer           = config.GetValue <string>("Security:Issuer"),
                ValidateAudience      = true,
                ValidAudience         = config.GetValue <string>("Security:Audience"),
                RequireExpirationTime = true,
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.FromMinutes(5),
            };

            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            try
            {
                ClaimsPrincipal principal = handler.ValidateToken(token, validationParams, out SecurityToken validatedToken);
                if (principal != null)
                {
                    ClaimsIdentity identity = principal.Identities.First();
                    User           user     = await userService.Get(identity.FindFirst("username").Value);

                    if (user.RefreshTokenID.ToString().Equals(identity.FindFirst("refreshTokenID").Value))
                    {
                        var newIdentity = new ClaimsIdentity();

                        newIdentity.AddClaim(new Claim("username", user.Username));
                        string newToken = securityService.GenerateToken(newIdentity, SecurityService.TokenType.Access);

                        Guid refreshTokenID = Guid.NewGuid();
                        newIdentity.AddClaim(new Claim("refreshTokenID", refreshTokenID.ToString()));
                        var newRefreshToken = securityService.GenerateToken(newIdentity, SecurityService.TokenType.Refresh);

                        await userService.SetRefreshTokenID(user.Username, refreshTokenID);

                        return(new JsonResult(new { Token = newToken, RefreshToken = newRefreshToken }));
                    }
                    else
                    {
                        return(new BadRequestResult());
                    }
                }
            }
            catch (SecurityTokenValidationException)
            {
                return(new BadRequestResult());
            }
            catch (ArgumentException)
            {
                return(new BadRequestResult());
            }

            return(new BadRequestResult());
        }
Пример #5
0
        public async Task ValidateToken_ShouldReturnInvalid_WhenTokenIsIncorrect()
        {
            // Arrange
            const int  customerId = 1;
            const long cardNumber = 1234123412341234;
            const int  cvv        = 12345;

            var card = await CreateCardAsync(customerId, cardNumber, cvv);

            var url = $"/v1/cards/{card.CardId}";

            var request = new ValidateTokenRequest
            {
                CustomerId = customerId,
                Token      = Guid.NewGuid(),
                CVV        = cvv
            };

            var json    = JsonConvert.SerializeObject(request);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            // Act
            var response = await _testsFixture.Client.PostAsync(url, content);

            response.EnsureSuccessStatusCode();

            var responseContentString = await response.Content.ReadAsStringAsync();

            var validateTokenResponse = JsonConvert.DeserializeObject <ValidateTokenResponse>(responseContentString);

            // Assert
            validateTokenResponse.Validated.Should().BeFalse();
        }
Пример #6
0
        public ValidateTokenResponse Validate(ValidateTokenRequest request, string securityToken)
        {
            try
            {
                ValidateTokenResponse response = null;
                ObjectId tokenObjectId;

                if (request != null)
                {
                    if (ObjectId.TryParse(request.Token, out tokenObjectId))
                    {
                        MEAPISession session = _objectContext.APISessions.Collection.FindOneByIdAs <MEAPISession>(tokenObjectId);

                        if (session != null)
                        {
                            if (session.SecurityToken.ToUpper().Equals(securityToken.ToUpper()) &&
                                session.ContractNumber.ToUpper().Equals(request.ContractNumber.ToUpper()) &&
                                session.Product.ToUpper().Equals(request.Context.ToUpper()))
                            {
                                session.SessionTimeOut = DateTime.UtcNow.AddMinutes(session.SessionLengthInMinutes);
                                response = new ValidateTokenResponse
                                {
                                    SessionLengthInMinutes = session.SessionLengthInMinutes,
                                    SessionTimeOut         = session.SessionTimeOut,
                                    TokenId   = session.Id.ToString(),
                                    SQLUserId = session.SQLUserId,
                                    UserId    = session.UserId.ToString(),
                                    UserName  = session.UserName
                                };
                                _objectContext.APISessions.Collection.Save(session);
                            }
                            else
                            {
                                throw new UnauthorizedAccessException("SD:APISessionRepository:Validate():Invalid Security Authorization Request");
                            }

                            return(response);
                        }
                        else
                        {
                            throw new UnauthorizedAccessException("SD:APISessionRepository:Validate():Security Token does not exist");
                        }
                    }
                    else
                    {
                        throw new UnauthorizedAccessException("SD:APISessionRepository:Validate():Security Token is not in correct format.");
                    }
                }
                else
                {
                    throw new UnauthorizedAccessException("SD:APISessionRepository:Validate():Request is invalid");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #7
0
        public ActionResult <string> Post([FromBody] ValidateTokenRequest request)
        {
            var tokenResult = JwtUtil.IsValidToken(request.Token, request.DeviceId);
            var response    = new ValidateTokenResponse()
            {
                Result = (tokenResult == JwtUtil.ValidateTokenResult.Success) ? (int)ResultCode.Success : (int)ResultCode.InvalidToken
            };

            return(JsonConvert.SerializeObject(response));
        }
        public ActionResult <UserIdentity> ValidateToken(ValidateTokenRequest validateTokenRequest)
        {
            if (TokenAuthenticationFactory.TryValidateToken(validateTokenRequest.Token, out var claimsPrincipal))
            {
                UserIdentity user = new UserIdentity(claimsPrincipal.Claims);

                return(Ok(user));
            }

            return(BadRequest());
        }
Пример #9
0
        public static ValidateTokenResponse ValidateToken(ValidateTokenRequest request, string securityToken)
        {
            try
            {
                ISecurityRepository <AuthenticateResponse> securityRepo = SecurityRepositoryFactory <AuthenticateResponse> .GetSecurityRepository(request.Context);

                return(securityRepo.Validate(request, securityToken));
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task <User> ValidateToken([FromBody] ValidateTokenRequest token)
        {
            var validated = TtcAuthorizationFilterAttribute.ValidateToken(token.Token);

            if (validated == null)
            {
                return(null);
            }

            var userModel = await _service.GetUser(validated.PlayerId);

            userModel.Token = TtcAuthorizationFilterAttribute.CreateToken(userModel);
            return(userModel);
        }
Пример #11
0
        public async Task <ActionResult <string> > ValidateToken([FromBody] ValidateTokenRequest request, [FromHeader(Name = "X-Correlation-ID")] string correlationId, CancellationToken cancellationToken)
        {
            var result = await _mediator.Send(request, cancellationToken);

            if (!result.IsSuccess)
            {
                if (result.Error.Code == ErrorMessages.TokenNotFound.code)
                {
                    return(NotFound(result.Error));
                }

                return(BadRequest(result.Error));
            }

            return(Ok());
        }
        public IAuthenticationContext <ValidateTokenResponse> Handle(ValidateTokenRequest request)
        {
            var token = _tokenCache.Get();

            if (string.IsNullOrEmpty(token))
            {
                Context.AddMessage("W3");
                _applicationUserContext.Token.IsValidTokenProvided = false;
                return(Context);
            }

            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuer           = true,
                ValidateAudience         = true,
                ValidateLifetime         = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer      = "Fiver.Security.Bearer",
                ValidAudience    = "Fiver.Security.Bearer",
                IssuerSigningKey = JwtSecurityKey.Create("fiver-secret-key")
            };

            System.Security.Claims.ClaimsPrincipal principal = null;
            SecurityToken validatedToken = null;

            try
            {
                principal = new JwtSecurityTokenHandler()
                            .ValidateToken(token, validationParameters, out validatedToken);
            }
            catch (SecurityTokenValidationException)
            {
                Context.AddMessage("E3", "Invalid Token");
                return(Context);
            }

            var email = principal.Claims.ToList()[0].Value;

            _applicationUserContext.Token = new TokenDto(token, validatedToken.ValidTo);
            _applicationUserContext.Email = email;
            _applicationUserContext.Token.IsValidTokenProvided = true;

            return(Context);
        }
Пример #13
0
        public async Task <IActionResult> ValidateToken([FromBody] ValidateTokenRequest request)
        {
            var authResponse = await _userService.VerifyTokenAsync(request.Token);


            if (!authResponse.Success)
            {
                return(BadRequest(new AuthFailedResponse
                {
                    Error = authResponse.Error
                }));
            }

            return(Ok(new AuthSuccessResponse
            {
                Token = authResponse.Token,
                Message = "Token has been validated"
            }));
        }
Пример #14
0
        public async Task <object> Validate([FromBody] ValidateTokenRequest tokenRequest)
        {
            logger.LogInformation("Email addess : " + tokenRequest.UserName);
            var user = await userManager.FindByEmailAsync(tokenRequest.UserName);

            bool exists = user != null;

            if (!exists)
            {
                return(BadRequest("The user was not found."));
            }
            string tokenUsername = ValidateToken(tokenRequest.Token);

            if (tokenRequest.UserName.Equals(tokenUsername))
            {
                return(Ok());
            }
            return(BadRequest());
        }
        public async Task <IActionResult> ValidateToken([FromBody] ValidateTokenRequest validateToken)
        {
            var isValid = await _accountService.ValidateTokenAsync(validateToken.Token);

            if (isValid)
            {
                var principal = await _accountService.GetPrincipalFromExpiredTokenAsync(validateToken.Token);

                var userId = Convert.ToInt32(principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.UserData).Value);
                var user   = await _accountService.GetUserAsync(userId);

                var mapped = _mapper.Map <UserResponse>(user);
                return(Ok(new ApiOkResponse(mapped)));
            }
            else
            {
                return(Unauthorized());
            }
        }
Пример #16
0
        public async Task <IActionResult> ValidateToken([FromRoute] Guid cardId, [FromBody] ValidateTokenRequest request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                return(BadRequest());
            }

            var commandInput  = new ValidateCardTokenCommandInput(request.CustomerId, cardId, request.Token, request.CVV);
            var commandResult = await _mediator.Send(commandInput, cancellationToken);

            if (!commandResult.IsValid())
            {
                return(BadRequest());
            }

            var response = new ValidateTokenResponse(commandResult.Validated);

            return(Ok(response));
        }
Пример #17
0
        public async Task ValidateToken_ShouldReturnBadRequest_WhenPassWrongParameters(int customerId, string cardId, int cvv, string strToken)
        {
            // Arrange
            var url = $"/v1/cards/{cardId}";

            var request = new ValidateTokenRequest
            {
                CustomerId = customerId,
                Token      = Guid.Parse(strToken),
                CVV        = cvv
            };

            var json    = JsonConvert.SerializeObject(request);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            // Act
            var response = await _testsFixture.Client.PostAsync(url, content);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }
Пример #18
0
        public ValidateTokenResponse Post(ValidateTokenRequest request)
        {
            ValidateTokenResponse response = new ValidateTokenResponse();

            try
            {
                //pull token from request coming in to validate token
                string securityToken = HttpContext.Current.Request.Headers.Get(_phytelSecurityToken);

                // validate user against apiuser datastore
                response = SecurityManager.ValidateToken(request, securityToken);
            }
            catch (Exception ex)
            {
                CommonFormatter.FormatExceptionResponse(response, base.Response, ex);
                if ((ex is WebServiceException) == false)
                {
                    LogException(ex);
                }
            }
            return(response);
        }
Пример #19
0
        public IActionResult ValidateToken([FromBody] ValidateTokenRequest request)
        {
            // Get rid of bearer if it is still there
            string token = request.Token.Replace("Bearer ", "");

            var validationParams = new TokenValidationParameters
            {
                IssuerSigningKey      = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(config.GetValue <string>("Security:SigningKey"))),
                RequireSignedTokens   = true,
                ValidateIssuer        = true,
                ValidIssuer           = config.GetValue <string>("Security:Issuer"),
                ValidateAudience      = true,
                ValidAudience         = config.GetValue <string>("Security:Audience"),
                RequireExpirationTime = true,
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.FromMinutes(5),
            };

            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            try
            {
                var user = handler.ValidateToken(token, validationParams, out SecurityToken validatedToken);
                if (user != null)
                {
                    return(new JsonResult(new { Result = true }));
                }
            }
            catch (SecurityTokenValidationException)
            {
                return(new JsonResult(new { Result = false }));
            }
            catch (ArgumentException)
            {
                return(new BadRequestResult());
            }

            return(new JsonResult(new { Result = false }));
        }
Пример #20
0
        public ActionResult <ValidateTokenResponse> CheckToken(ValidateTokenRequest validateTokenRequest)
        {
            try
            {
                if (validateTokenRequest != null || validateTokenRequest.JWTToken != null)

                {
                    var tokenClaim = _TokenLibraryRepository.ValidateTokenClaim(validateTokenRequest.JWTToken);


                    if (tokenClaim == null)
                    {
                        var error = new Error()
                        {
                            ErrorMessage = "Token Expired or Invalid Key or Token Verification Failed"
                        };
                        return(Unauthorized(error));
                    }
                    return(Ok(tokenClaim));
                }
                else
                {
                    return(BadRequest());
                }
            }

            catch (Exception ex)

            {
                var error = new Error()
                {
                    ErrorMessage = "Token Expired or Invalid Key or Token Verification Failed"
                };
                return(Unauthorized(error));
            }
        }
Пример #21
0
        public IActionResult Validate([FromBody] ValidateTokenRequest requestBody)
        {
            var user = _userRepository.GetUser(requestBody.Username);

            if (user == null)
            {
                return(NotFound("The user was not found."));
            }

            var tokenUser = _tokenService.ValidateToken(requestBody.Token, out var invalidTokenReason);
            var userMatch =
                tokenUser.Username.Equals(requestBody.Username, StringComparison.InvariantCultureIgnoreCase);

            if (!userMatch || invalidTokenReason.HasValue)
            {
                return(BadRequest(new
                {
                    Reason = invalidTokenReason.ToString(),
                    UserMatch = userMatch
                }));
            }

            return(Ok(tokenUser));
        }
 public async Task <ValidateTokenResponse> ValidateToken(ValidateTokenRequest request)
 {
     return(new ValidateTokenResponse(validateToken(request.Token)));
 }
Пример #23
0
 public DTO.ValidateTokenResponse Validate(ValidateTokenRequest request, string securityToken)
 {
     throw new NotImplementedException();
 }