示例#1
0
        public async Task <IActionResult> Create(Guid clientId, Guid clientSecret)
        {
            var result = new CommonResult();

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

            var request  = new TokenCreateRequest(clientId, clientSecret, HttpContext.Connection.RemoteIpAddress);
            var response = await _integrationService.CreateToken(request);

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

            var model = new TokenResult
            {
                IsOk      = true,
                Token     = response.Item.AccessToken,
                CreatedAt = GetDateTimeAsString(response.Item.CreatedAt),
                ExpiresAt = GetDateTimeAsString(response.Item.ExpiresAt)
            };

            return(Json(model));
        }
示例#2
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);
            }
        }
示例#3
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);
            }
        }
示例#4
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);
        }
示例#5
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);
            }
        }
示例#6
0
        public Token CreateEntityFromRequest(TokenCreateRequest request, IntegrationClient integrationClient)
        {
            var entity = CreateEntity(integrationClient);

            entity.Ip = request.IP.ToString();

            return(entity);
        }
示例#7
0
        public Task <TokenCreateResponse> CreateAsync(TokenCreateRequest tokenCreateRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (tokenCreateRequest == null)
            {
                throw new ArgumentNullException(nameof(tokenCreateRequest));
            }

            return(InternalCreateAsync(tokenCreateRequest, cancellationToken));
        }
示例#8
0
        internal TokenCreateRequest BuildTokenCreateRequest()
        {
            TokenIdentity      obo     = new TokenIdentity(null, "testid");
            TokenCreateRequest request = new TokenCreateRequest(obo)
            {
                MaxUsageCount     = 1,
                ProtectedResource = bogusTestUrl,
                Context           = JObject.Parse(@"{ ""x"":""value""}"),
            };

            return(request);
        }
示例#9
0
        private async Task <TokenCreateResponse> InternalCreateAsync(TokenCreateRequest tokenCreateRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            //TODO business rule: should we receive a deviceId to "connect" the token with that device?
            var generatedToken = _tokenGenerator.Generate(new Card(tokenCreateRequest.CardNumber, tokenCreateRequest.Cvv), _tokenGeneratorClock.Now());

            var tokenRegistration = new TokenRegistration(generatedToken.Value, tokenCreateRequest.CardNumber, generatedToken.GeneratedAt);

            _databaseContext.TokenRegistrations.Add(tokenRegistration);
            await _databaseContext.SaveChangesAsync(cancellationToken);

            return(new TokenCreateResponse(generatedToken.GeneratedAt, generatedToken.Value));
        }
示例#10
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);
        }
示例#11
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);
        }
示例#12
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);
        }
示例#13
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);
            }
        }
示例#14
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);
            }
        }
示例#15
0
        private void DeserializeSerializeCompare(string jsonRep)
        {
            // convert the JSON to objects.  Convert the objects to JSON.
            TokenCreateRequest hydrated = JsonConvert.DeserializeObject <TokenCreateRequest>(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");
        }
        /// <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);
        }
示例#17
0
        public async Task <TokenCreateResponse> Create([FromBody] TokenCreateRequest request)
        {
            var identity = await GetIdentityAsync(request.UserId);

            var claims = new[] {
                new Claim("sub", request.UserId),
                new Claim("given_name", identity.FirstName),
                new Claim("family_name", identity.LastName),
                new Claim("iat", DateTimeOffset.Now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
            };
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256);

            var token = new JwtSecurityToken(claims: claims, signingCredentials: signingCredentials);

            return(new TokenCreateResponse
            {
                Token = new JwtSecurityTokenHandler().WriteToken(token),
            });
        }
        /// <summary>
        /// Creates an entity from a submitted requests.  The entity is not complete until a JWT has been added to it.
        /// This means the entity must be muta)ble :-(
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        internal TokenEntity CreateTokenEntity(TokenCreateRequest request)
        {
            DateTime now = DateTime.Now;
            // TODO create initiator for this constructor. Get initiator from request or security context. We set obo as property below.
            // Consumed by is initially empty and updated by Validate()
            TokenEntity entity = new TokenEntity(new TokenIdentityEntity(request.OnBehalfOf.ProviderName, request.OnBehalfOf.UserName), null)
            {
                Context               = request.Context,
                MaxUseCount           = request.MaxUsageCount,
                EffectiveTime         = request.EffectiveTime,
                ExpirationIntervalSec = request.ExpirationIntervalSeconds,
                ExpirationTime        = request.EffectiveTime.AddSeconds(request.ExpirationIntervalSeconds),
                InitiationTime        = now,
                JwtUniqueIdentifier   = Guid.NewGuid().ToString(),
                JwtSecret             = SecretKey(),
                ProtectedResource     = request.ProtectedResource,
            };

            return(entity);
        }
示例#19
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);
            }
        }
示例#20
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);
            }
        }
        public IActionResult Create([FromBody] TokenCreateRequest value)
        {
            TokenCreateResponse response = _creationService.CreateToken(value);

            return(Created("../Validate", response));
        }
示例#22
0
 public async Task <TokenCreateResponse> Post([FromBody] TokenCreateRequest tokenCreateRequest, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(await _tokenCreateService.CreateAsync(tokenCreateRequest, cancellationToken));
 }
示例#23
0
        public ActionResult <Token> CreateToken([FromForm] TokenCreateRequest request)
        {
            if (request.GrantType == GrantTypes.AuthorizationCode)
            {
                if (string.IsNullOrEmpty(request.ClientId))
                {
                    return(ErrorObjectResultFactory.InvalidClient());
                }

                var application = _authorizeService.GetApplication(request.ClientId);

                if (application == null)
                {
                    return(ErrorObjectResultFactory.InvalidClient());
                }

                if (!application.GrantTypes.Contains(GrantTypes.AuthorizationCode))
                {
                    return(ErrorObjectResultFactory.InvalidGrantType());
                }

                if (string.IsNullOrEmpty(request.Code))
                {
                    return(ErrorObjectResultFactory.InvalidCode());
                }

                var authorizationCode = _authorizeService.GetAuthorizationCode(request.Code);

                if (authorizationCode == null)
                {
                    return(ErrorObjectResultFactory.InvalidCode());
                }

                if (application.ApplicationId != authorizationCode.ApplicationId)
                {
                    return(ErrorObjectResultFactory.InvalidCode());
                }

                var accessToken = _authorizeService.CreateAccessToken(
                    application.ApplicationId,
                    authorizationCode.AccountId,
                    null);

                _authorizeService.UseAuthorizationCode(request.Code);

                return(new Token
                {
                    AccessToken = accessToken.TokenId,
                    ExpiresIn = _appSetgings.AccessTokenExpiresIn,
                    Scope = string.Join(' ', accessToken.Scopes),
                    TokenType = "Bearer",
                });
            }
            else if (request.GrantType == GrantTypes.ClientCredentials)
            {
                if (string.IsNullOrEmpty(request.ClientId))
                {
                    return(ErrorObjectResultFactory.InvalidClient());
                }

                var application = _authorizeService.GetApplication(request.ClientId);

                if (application == null || application.ClientSecret != request.ClientSecret)
                {
                    return(ErrorObjectResultFactory.InvalidClient());
                }

                if (!application.GrantTypes.Contains(GrantTypes.ClientCredentials))
                {
                    return(ErrorObjectResultFactory.InvalidGrantType());
                }

                IList <string> scopes = new List <string>();

                if (!string.IsNullOrEmpty(request.Scope))
                {
                    scopes = request.Scope.Split(' ', ',');

                    foreach (string scope in scopes)
                    {
                        if (!application.Scopes.Contains(scope))
                        {
                            return(ErrorObjectResultFactory.InvalidScope());
                        }
                    }
                }

                var accessToken = _authorizeService.CreateAccessToken(application.ApplicationId, scopes);

                return(new Token
                {
                    AccessToken = accessToken.TokenId,
                    ExpiresIn = _appSetgings.AccessTokenExpiresIn,
                    Scope = string.Join(' ', accessToken.Scopes),
                    TokenType = "Bearer",
                });
            }
            else
            {
                throw new NotImplementedException();
            }
        }