コード例 #1
0
        public async Task <TokenCreateResponse> CreateToken(TokenCreateRequest request)
        {
            var response = new TokenCreateResponse();

            var integrationClient = await _integrationClientRepository.Select(x => x.ClientId == request.ClientId && x.ClientSecret == request.ClientSecret);

            if (integrationClient.IsNotExist())
            {
                response.SetInvalidBecauseNotFound("integration_client");
                return(response);
            }

            if (await _organizationRepository.Any(x => x.Id == integrationClient.OrganizationId && !x.IsActive) ||
                await _integrationRepository.Any(x => x.Id == integrationClient.IntegrationId && !x.IsActive))
            {
                response.SetInvalid();
                response.ErrorMessages.Add("integration_client_not_found");
                return(response);
            }

            var token = _tokenFactory.CreateEntityFromRequest(request, integrationClient);
            var id    = await _tokenRepository.Insert(integrationClient.Id, token);

            if (id > 0)
            {
                response.Item   = _tokenFactory.CreateDtoFromEntity(token);
                response.Status = ResponseStatus.Success;
                return(response);
            }

            response.SetFailed();
            return(response);
        }
コード例 #2
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);
            }
        }
コード例 #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);
            }
        }
コード例 #4
0
        public void ValidateEncodedJwtBadId()
        {
            TokenCreateRequest request = ttu.BuildTokenCreateRequest();

            // added this catch block in when we failed creating tokens because regex didn't fit in URL validation.
            // The tangled web we weave
            try
            {
                TokenCreateResponse createResult = serviceUnderTest.CreateToken(request);

                Assert.NotNull(createResult.JwtToken);
                JwtSecurityTokenHandler tokenHandler  = new JwtSecurityTokenHandler();
                JwtSecurityToken        receivedToken = tokenHandler.ReadJwtToken(createResult.JwtToken);
                TokenEntity             badEntity     = new TokenEntity(null, null)
                {
                    JwtUniqueIdentifier = "dogfood"
                };
                try
                {
                    serviceUnderTest.ValidateEncodedJwt(receivedToken, badEntity);
                    Assert.False(true, "Expected FailedException");
                }
                catch (ConsistencyException e)
                {
                    _output.WriteLine("Caught expected exception: " + e.Message);
                }
            }
            catch (BadArgumentException e)
            {
                Assert.False(true, "Caught unexpected exception: " + e.Message + " " + e.ServiceResponse);
            }
        }
コード例 #5
0
        public void CreateTokenHappyPath()
        {
            TokenController     controller = new TokenController(serviceUnderTest, serviceUnderTest, controllerLogger);
            TokenCreateRequest  request    = ttu.BuildTokenCreateRequest();
            CreatedResult       result     = controller.Create(request) as CreatedResult;
            TokenCreateResponse response   = result.Value as TokenCreateResponse;

            Assert.NotNull(response);
            Assert.Equal("1.0", response.ModelVersion);
            Assert.NotEmpty(response.JwtToken);
            // shouldn't be any messages
            Assert.Equal(0, response.Messages.Count);
        }
コード例 #6
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);
        }
コード例 #7
0
        public void CreateTokenForceValidationError()
        {
            TokenCreateRequest request = ttu.BuildTokenCreateRequest();

            request.ModelVersion = null;
            try
            {
                TokenCreateResponse createResult = serviceUnderTest.CreateToken(request);
                Assert.False(true, "Create Token should have failed model validation");
            }
            catch (BadArgumentException e)
            {
                _output.WriteLine("Received expected BadArgumentException when mandatory aTribute not set: " + e.ServiceResponse);
            }
        }
コード例 #8
0
        public void CreateTokenSuccess()
        {
            TokenCreateRequest  request      = ttu.BuildTokenCreateRequest();
            TokenCreateResponse createResult = serviceUnderTest.CreateToken(request);

            Assert.NotNull(createResult);
            Assert.NotNull(createResult.JwtToken);
            _output.WriteLine("Calculated Token Encoded : " + createResult.JwtToken);

            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken        foundToken   = tokenHandler.ReadJwtToken(createResult.JwtToken);

            Assert.NotNull(foundToken);
            Assert.Equal(ttu.bogusTestUrl, foundToken.Payload.Sub);
        }
コード例 #9
0
        public void CreateTokenInvalidObject()
        {
            // set no mandatory properties
            TokenCreateRequest request = new TokenCreateRequest(null);

            try
            {
                TokenCreateResponse response = serviceUnderTest.CreateToken(request);
                Assert.True(false, "Should have thrown an exception");
            }
            catch (BadArgumentException e)
            {
                Assert.NotNull(e.ServiceResponse);
                _output.WriteLine("validation messages included " + e.ServiceResponse);
            }
        }
コード例 #10
0
        private void DeserializeSerializeCompare(string jsonRep)
        {
            // convert the JSON to objects.  Convert the objects to JSON.
            TokenCreateResponse hydrated = JsonConvert.DeserializeObject <TokenCreateResponse>(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");
        }
コード例 #11
0
        /// <summary>
        /// Creates a token and returns it in the response.
        /// Throws an exception wrapping the response if there is an error.
        /// Throws BadArgumentException if the request is bad
        /// FailedException if there was some other problem
        /// </summary>
        /// <param name="request"></param>
        /// <returns>A response containing the token</returns>
        public TokenCreateResponse CreateToken(TokenCreateRequest request)
        {
            ValidateRequest(request);
            // yeah its circular because we store the JWT in the entity and JWT creation uses the entity fields.
            TokenEntity entity = CreateTokenEntity(request);
            string      newJwt = CreateJwt(entity);

            entity.JwtToken = newJwt;
            // save the entity, create a response and get out of here
            _repository.Create(entity);
            TokenCreateResponse response = new TokenCreateResponse()
            {
                JwtToken = newJwt,
            };

            return(response);
        }
コード例 #12
0
        public async Task <TokenCreateResponse> CreateToken(TokenGetRequest request)
        {
            var response = new TokenCreateResponse();

            var currentUser = _cacheManager.GetCachedCurrentUser(request.CurrentUserId);

            if (currentUser == null)
            {
                response.SetInvalid();
                return(response);
            }

            var integrationClient = await _integrationClientRepository.Select(x => x.OrganizationId == currentUser.OrganizationId && x.IsActive);

            if (integrationClient.IsNotExist())
            {
                response.SetInvalid();
                response.ErrorMessages.Add("integration_not_found");
                return(response);
            }

            if (await _organizationRepository.Any(x => x.Id == integrationClient.OrganizationId && !x.IsActive) ||
                await _integrationRepository.Any(x => x.Id == integrationClient.IntegrationId && !x.IsActive))
            {
                response.SetInvalid();
                response.ErrorMessages.Add("integration_client_not_found");
                return(response);
            }

            var token = _tokenFactory.CreateEntity(integrationClient);
            var id    = await _tokenRepository.Insert(integrationClient.Id, token);

            if (id > 0)
            {
                response.Item   = _tokenFactory.CreateDtoFromEntity(token);
                response.Status = ResponseStatus.Success;
                return(response);
            }

            response.SetFailed();
            return(response);
        }
コード例 #13
0
        public void ValidateProtectedExactMatch()
        {
            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);
            TokenEntity foundEntity = inMemoryRepo.GetById(receivedToken.Id);

            Assert.NotNull(foundEntity);
            try
            {
                serviceUnderTest.ValidateResourceAllowed(receivedToken, foundEntity, foundEntity.ProtectedResource);
            }
            catch (ViolationException e)
            {
                Assert.False(true, "Caught unexpected exception: " + e.Message + " " + e.ServiceResponse);
            }
        }
コード例 #14
0
        public void ValidateProtectedExtraSuffixFails()
        {
            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);
            TokenEntity foundEntity = inMemoryRepo.GetById(receivedToken.Id);

            Assert.NotNull(foundEntity);
            try
            {
                serviceUnderTest.ValidateResourceAllowed(receivedToken, foundEntity, foundEntity.ProtectedResource + "/some-suffix");
                Assert.False(true, "Expected FailedException");
            }
            catch (ViolationException e)
            {
                _output.WriteLine("Caught expected exception: " + e.Message);
            }
        }
コード例 #15
0
        public IActionResult Create([FromBody] TokenCreateRequest value)
        {
            TokenCreateResponse response = _creationService.CreateToken(value);

            return(Created("../Validate", response));
        }