Exemple #1
0
        public void ValidateTokenNotEffective()
        {
            TokenCreateRequest request = ttu.BuildTokenCreateRequest();

            // make effective and expiration time in the past
            request.EffectiveTime = DateTime.Now.AddDays(+20);

            TokenCreateResponse     createResult  = serviceUnderTest.CreateToken(request);
            JwtSecurityTokenHandler tokenHandler  = new JwtSecurityTokenHandler();
            JwtSecurityToken        receivedToken = tokenHandler.ReadJwtToken(createResult.JwtToken);
            // create validation request from the data used to create the token
            TokenValidateRequest validateThis = ttu.BuildTokenValidateRequest(createResult.JwtToken, request.ProtectedResource);

            try
            {
                // should fail as expired
                TokenValidateResponse response = serviceUnderTest.ValidateToken(validateThis);
                Assert.False(true, "Did not catch exception when token not yet effective");
            }
            catch (ViolationException e)
            {
                // TODO should validate the message or something...
                _output.WriteLine("Caught expected exception: " + e.Message + " " + e.ServiceResponse);
            }
        }
        /// <summary>
        /// Validates the passed in token should be honored
        /// Returns the response.
        /// Throws an exception containing a response if it fails
        /// Throws BadArgumentException if the request is bad
        /// FailedException if there was some other problem
        /// </summary>
        /// <param name="request"></param>
        /// <returns>context information from the token</returns>
        public TokenValidateResponse ValidateToken(TokenValidateRequest request)
        {
            ValidateRequest(request);
            string jwtEncodedString = request.JwtToken;
            string protectedUrl     = request.AccessedResource;
            // convert string to POCO
            JwtSecurityToken jwtToken       = new JwtSecurityToken(jwtEncodedString);
            TokenEntity      jwtTokenEntity = _repository.GetById(jwtToken.Id);

            if (jwtTokenEntity == null)
            {
                throw new NotFoundException(String.Format(
                                                "JWT TokenId={0} Token not found", jwtToken.Id));
            }
            ValidateTokenSignature(jwtEncodedString, jwtTokenEntity);
            // validate the basic token and the URL
            ValidateEncodedJwt(jwtToken, jwtTokenEntity);
            ValidateResourceAllowed(jwtToken, jwtTokenEntity, request.AccessedResource);
            TokenEntity postValidationEntity = ValidateExpirationPolicy(jwtTokenEntity);
            // assuming we validated and found it
            TokenValidateResponse response = new TokenValidateResponse()
            {
                ProtectedResource = jwtTokenEntity.ProtectedResource,
                Context           = jwtTokenEntity.Context
            };

            // save the updated usage count and any audit information
            _logger.LogDebug("Saving updated entity {0}", postValidationEntity);
            _repository.Update(postValidationEntity);
            return(response);
        }
Exemple #3
0
        public void ValidateTokenCountExceeded()
        {
            TokenCreateRequest  request      = ttu.BuildTokenCreateRequest();
            TokenCreateResponse createResult = serviceUnderTest.CreateToken(request);

            Assert.NotNull(createResult.JwtToken);
            JwtSecurityTokenHandler tokenHandler  = new JwtSecurityTokenHandler();
            JwtSecurityToken        receivedToken = tokenHandler.ReadJwtToken(createResult.JwtToken);

            Assert.NotNull(receivedToken);
            // create validation request from the data used to create the token
            TokenValidateRequest validateThis = ttu.BuildTokenValidateRequest(createResult.JwtToken, request.ProtectedResource);

            // first one should succeed
            TokenValidateResponse response1 = serviceUnderTest.ValidateToken(validateThis);

            // Lets jam a context validation into this test also. probably should be broken out into its own test in the future
            Assert.NotNull(response1.Context);

            try
            {
                // usage count was set to one so should now fail
                TokenValidateResponse response2 = serviceUnderTest.ValidateToken(validateThis);
                // Lets jam a context validation into this test also. probably should be broken out into its own test in the future
                Assert.False(true, "Did not catch exception when usage count exceeded");
            }
            catch (ViolationException e)
            {
                _output.WriteLine("Caught expected exception: " + e.Message + " " + e.ServiceResponse);
            }
        }
        public async Task <IActionResult> AddLabel(Guid token, Guid projectUid, string labelKey)
        {
            var result = new CommonResult();

            if (token.IsEmptyGuid() ||
                projectUid.IsEmptyGuid() ||
                labelKey.IsEmpty())
            {
                result.Messages.Add("some parameters are missing! (token, projectUid, labelKey)");
                return(Json(result));
            }

            var request  = new TokenValidateRequest(projectUid, token);
            var response = await _integrationService.ValidateToken(request);

            if (response.Status.IsNotSuccess)
            {
                result.Messages = response.ErrorMessages;
                result.Messages.Add("unauthorized");
                return(StatusCode(401, result));
            }

            var labelCreateWithTokenRequest = new LabelCreateWithTokenRequest(token, projectUid, labelKey);
            var labelsResponse = await _labelService.CreateLabel(labelCreateWithTokenRequest);

            if (labelsResponse.Status.IsNotSuccess)
            {
                response.ErrorMessages = labelsResponse.ErrorMessages;
                return(Json(result));
            }

            result.IsOk = true;
            return(Json(result));
        }
        public async Task <IActionResult> GetLabels(Guid token, Guid projectUid)
        {
            var result = new CommonResult();

            if (token.IsEmptyGuid() ||
                projectUid.IsEmptyGuid())
            {
                result.Messages.Add("token or projectUid is missing!");
                return(StatusCode(401, result));
            }

            var labelReadListRequest = new AllLabelReadListRequest(token, projectUid);
            var request  = new TokenValidateRequest(projectUid, token);
            var response = await _integrationService.ValidateToken(request);

            if (response.Status.IsNotSuccess)
            {
                result.Messages = response.ErrorMessages;
                result.Messages.Add("unauthorized");
                return(StatusCode(401, result));
            }

            var labelsResponse = await _labelService.GetLabelsWithTranslations(labelReadListRequest);

            if (labelsResponse.Status.IsNotSuccess)
            {
                result.Messages = labelsResponse.ErrorMessages;
                return(Json(result));
            }

            return(Json(labelsResponse.Labels));
        }
        public async Task <TokenValidateResponse> ValidateAsync(TokenValidateRequest tokenValidateRequest)
        {
            try
            {
                var request = new RestRequest
                {
                    Resource = "tokens/validate",
                    Method   = Method.POST
                };
                tokenValidateRequest.Credential = _appSettingsService.InfrastructureCredential;
                request.AddJsonBody(tokenValidateRequest);

                _logService.LogInfoMessageAsync($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} | Sending Account-Token data to Token Micro-service");

                var response = await _restClient.ExecuteAsync <TokenValidateResponse>(request);

                if (response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == 0)
                {
                    _logService.LogErrorMessageAsync(
                        $"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} | Unable to connect to Token Micro-service | Status=NOT_FOUND"
                        );

                    return(null);
                }

                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    _logService.LogErrorMessageAsync(
                        $"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} | Error sending Account-Token data to Token Micro-service | Status=UNAUTHORIZED"
                        );

                    return(null);
                }

                if (!response.IsSuccessful)
                {
                    _logService.LogErrorMessageAsync(
                        $"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} | Error sending Account-Token data to Token Micro-service | Status=FAIL - Reason={response.Content}"
                        );

                    return(null);
                }

                _logService.LogInfoMessageAsync(
                    $"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} | Account-Token data sent to Token Micro-service | Status=OK"
                    );

                return(response.Data);
            }
            catch (Exception e)
            {
                _logService.LogErrorMessageAsync($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} | e.Message={e.Message} - e={e}");

                return(null);
            }
        }
Exemple #7
0
        internal TokenValidateRequest BuildTokenValidateRequest(string jwtToken, string protectedUrl)
        {
            // should we create a constructor in TokenValidateRequeste for this since there are so few properties
            TokenValidateRequest ourValidateRequest = new TokenValidateRequest()
            {
                JwtToken         = jwtToken,
                AccessedResource = protectedUrl
            };

            return(ourValidateRequest);
        }
Exemple #8
0
        public void ValidateTokenHappyPath()
        {
            TokenController     controller = new TokenController(serviceUnderTest, serviceUnderTest, controllerLogger);
            TokenCreateRequest  request    = ttu.BuildTokenCreateRequest();
            CreatedResult       result     = controller.Create(request) as CreatedResult;
            TokenCreateResponse response   = result.Value as TokenCreateResponse;

            // assume CreateTokenHappyPath() validates the create path so now lets run the validate path
            TokenValidateRequest validateThis = ttu.BuildTokenValidateRequest(response.JwtToken, request.ProtectedResource);

            Assert.Equal(validateThis.JwtToken, response.JwtToken);
            // shouldn't be any messages
            Assert.Equal(0, response.Messages.Count);
        }
Exemple #9
0
        private void DeserializeSerializeCompare(string jsonRep)
        {
            // convert the JSON to objects.  Convert the objects to JSON.
            TokenValidateRequest hydrated = JsonConvert.DeserializeObject <TokenValidateRequest>(jsonRep);

            Assert.NotNull(hydrated);
            output.WriteLine("Original=" + jsonRep);
            string serialized = JsonConvert.SerializeObject(hydrated, Formatting.Indented);

            output.WriteLine("Serialized=" + serialized);
            // compare original JSON with results of deserialize / serialize
            var nodeSet1 = JsonConvert.DeserializeObject <JObject>(jsonRep);
            var nodeSet2 = JsonConvert.DeserializeObject <JObject>(serialized);

            Assert.True(JToken.DeepEquals(nodeSet1, nodeSet2),
                        "Original JSON and results of deserialize,serialize are different token graphs");
        }
Exemple #10
0
        public void ValidateRequestInvalid()
        {
            // set none of mandatory properties
            TokenValidateRequest request = new TokenValidateRequest();

            try
            {
                TokenValidateResponse response = serviceUnderTest.ValidateToken(request);
                Assert.True(false, "Should have thrown an exception");
            }
            catch (BadArgumentException e)
            {
                // TODO should assert all the properties called out
                Assert.NotNull(e.ServiceResponse);
                _output.WriteLine("validation messages included " + e.ServiceResponse);
            }
        }
Exemple #11
0
        public async Task <IActionResult> VerifyToken(TokenValidateRequest request)
        {
            try
            {
                var response = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(request.Token);

                if (response != null)
                {
                    return(Ok("JWT - Valid"));
                }
            }
            catch (FirebaseException ex)
            {
                return(BadRequest(ex.Message.ToString()));
            }

            return(BadRequest());
        }
Exemple #12
0
        public async Task <IActionResult> RevokeToken(TokenValidateRequest request)
        {
            try
            {
                var response = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(request.Token);

                await FirebaseAuth.DefaultInstance.RevokeRefreshTokensAsync(response.Uid);

                var user = await FirebaseAuth.DefaultInstance.GetUserAsync(response.Uid);

                if (user != null)
                {
                    return(Ok("Tokens revoked at: " + user.TokensValidAfterTimestamp));
                }
            }
            catch (FirebaseException ex)
            {
                return(BadRequest(ex.Message.ToString()));
            }

            return(BadRequest());
        }
Exemple #13
0
        public async Task <TokenValidateResponse> ValidateToken(TokenValidateRequest request)
        {
            var response = new TokenValidateResponse();

            var project = await _projectRepository.Select(x => x.Uid == request.ProjectUid && x.IsActive);

            if (project.IsNotExist())
            {
                response.SetInvalid();
                response.ErrorMessages.Add("project_not_found");
                return(response);
            }

            var now   = DateTime.UtcNow;
            var token = await _tokenRepository.Select(x => x.AccessToken == request.Token && x.ExpiresAt > now);

            if (token.IsNotExist())
            {
                response.SetInvalid();
                return(response);
            }

            if (token.OrganizationId != project.OrganizationId)
            {
                response.SetInvalid();
                return(response);
            }

            if (await _organizationRepository.Any(x => x.Id == project.OrganizationId && !x.IsActive))
            {
                response.SetInvalid();
                return(response);
            }

            response.Status = ResponseStatus.Success;
            return(response);
        }
        public IActionResult Validate([FromBody] TokenValidateRequest value)
        {
            TokenValidateResponse response = _validationService.ValidateToken(value);

            return(Ok(response));
        }