private AuthenticateInstruction CreateAuthenticateInstruction(RefreshTokenGrantTypeParameter refreshTokenGrantTypeParameter, AuthenticationHeaderValue authenticationHeaderValue, X509Certificate2 certificate)
        {
            var result = _authenticateInstructionGenerator.GetAuthenticateInstruction(authenticationHeaderValue);

            result.ClientAssertion                 = refreshTokenGrantTypeParameter.ClientAssertion;
            result.ClientAssertionType             = refreshTokenGrantTypeParameter.ClientAssertionType;
            result.ClientIdFromHttpRequestBody     = refreshTokenGrantTypeParameter.ClientId;
            result.ClientSecretFromHttpRequestBody = refreshTokenGrantTypeParameter.ClientSecret;
            result.Certificate = certificate;
            return(result);
        }
        private async Task <GrantedToken> ValidateParameter(RefreshTokenGrantTypeParameter refreshTokenGrantTypeParameter)
        {
            var grantedToken = await _tokenStore.GetRefreshToken(refreshTokenGrantTypeParameter.RefreshToken);

            if (grantedToken == null)
            {
                throw new IdentityServerException(
                          ErrorCodes.InvalidGrant,
                          ErrorDescriptions.TheRefreshTokenIsNotValid);
            }

            return(grantedToken);
        }
        public void When_Passing_Correct_Request_Then_No_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            var parameter = new RefreshTokenGrantTypeParameter
            {
                RefreshToken = "refresh_token"
            };

            // ACT  & ASSERT
            var ex = Record.Exception(() => _refreshTokenGrantTypeParameterValidator.Validate(parameter));

            Assert.Null(ex);
        }
        public string GetPayload(RefreshTokenGrantTypeParameter parameter)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            var result = new Payload
            {
                Content = parameter
            };

            return(JsonConvert.SerializeObject(result));
        }
Exemplo n.º 5
0
        private async Task <GrantedToken> ValidateParameter(RefreshTokenGrantTypeParameter refreshTokenGrantTypeParameter)
        {
            // 1. Check refresh token exists
            var grantedToken = await _grantedTokenRepository.GetTokenByRefreshTokenAsync(refreshTokenGrantTypeParameter.RefreshToken);

            if (grantedToken == null)
            {
                throw new IdentityServerException(
                          ErrorCodes.InvalidGrant,
                          ErrorDescriptions.TheRefreshTokenIsNotValid);
            }

            return(grantedToken);
        }
        public async Task When_Passing_Invalid_Refresh_Token_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            var parameter = new RefreshTokenGrantTypeParameter();

            _grantedTokenRepositoryFake.Setup(g => g.GetTokenByRefreshTokenAsync(It.IsAny <string>()))
            .Returns(() => Task.FromResult((GrantedToken)null));

            // ACT & ASSERT
            var ex = await Assert.ThrowsAsync <IdentityServerException>(() => _getTokenByRefreshTokenGrantTypeAction.Execute(parameter));

            Assert.True(ex.Code == ErrorCodes.InvalidGrant);
            Assert.True(ex.Message == ErrorDescriptions.TheRefreshTokenIsNotValid);
        }
        public void When_Passing_No_Refresh_Token_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            var parameter = new RefreshTokenGrantTypeParameter
            {
                RefreshToken = string.Empty
            };

            // ACT  & ASSERT
            var exception = Assert.Throws <IdentityServerException>(() => _refreshTokenGrantTypeParameterValidator.Validate(parameter));

            Assert.True(exception.Code == ErrorCodes.InvalidRequestCode);
            Assert.True(exception.Message == string.Format(ErrorDescriptions.MissingParameter, Constants.StandardTokenRequestParameterNames.RefreshToken));
        }
        public async Task When_Client_Cannot_Be_Authenticated_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            var parameter = new RefreshTokenGrantTypeParameter();
            var authenticateInstruction = new AuthenticateInstruction();

            _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>()))
            .Returns(authenticateInstruction);
            _authenticateClientStub.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>(), null, It.IsAny <bool>())).Returns(Task.FromResult(new AuthenticationResult(null, "error")));

            // ACT & ASSERT
            var ex = await Assert.ThrowsAsync <IdentityServerException>(() => _getTokenByRefreshTokenGrantTypeAction.Execute(parameter, null, null, null));

            Assert.True(ex.Code == ErrorCodes.InvalidClient);
            Assert.True(ex.Message == "error");
        }
        public async Task When_Client_Cannot_Be_Authenticated_Then_Error_Is_Returned()
        {
            var parameter = new RefreshTokenGrantTypeParameter();

            _clientStore.Setup(x => x.GetById(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((Client)null);

            var result = await _getTokenByRefreshTokenGrantTypeAction.Execute(
                parameter,
                null,
                null,
                null,
                CancellationToken.None)
                         .ConfigureAwait(false) as Option <GrantedToken> .Error;

            Assert.Equal(ErrorCodes.InvalidClient, result.Details.Title);
            Assert.Equal(SharedStrings.TheClientDoesntExist, result.Details.Detail);
        }
        public async Task When_Requesting_Token_Then_New_One_Is_Generated()
        {
            // ARRANGE
            InitializeFakeObjects();
            var authenticateInstruction = new AuthenticateInstruction();

            _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>()))
            .Returns(authenticateInstruction);
            var parameter    = new RefreshTokenGrantTypeParameter();
            var grantedToken = new GrantedToken
            {
                IdTokenPayLoad = new JwsPayload(),
                ClientId       = "id"
            };

            _authenticateClientStub.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>(), null, It.IsAny <bool>())).Returns(Task.FromResult(new AuthenticationResult(new Client
            {
                ClientId   = "id",
                GrantTypes = new System.Collections.Generic.List <GrantType>
                {
                    GrantType.refresh_token
                }
            }, null)));
            _tokenStoreStub.Setup(g => g.GetRefreshToken(It.IsAny <string>()))
            .Returns(Task.FromResult(grantedToken));
            _grantedTokenGeneratorHelperStub.Setup(g => g.GenerateTokenAsync(
                                                       It.IsAny <string>(),
                                                       It.IsAny <string>(),
                                                       It.IsAny <string>(),
                                                       It.IsAny <JwsPayload>(),
                                                       It.IsAny <JwsPayload>())).Returns(Task.FromResult(grantedToken));

            // ACT
            await _getTokenByRefreshTokenGrantTypeAction.Execute(parameter, null, null, null);

            // ASSERT
            _tokenStoreStub.Verify(g => g.AddToken(It.IsAny <GrantedToken>()));
        }
        public async Task When_Requesting_Token_Then_New_One_Is_Generated()
        {
            // ARRANGE
            InitializeFakeObjects();
            var parameter    = new RefreshTokenGrantTypeParameter();
            var grantedToken = new GrantedToken
            {
                IdTokenPayLoad = new JwsPayload()
            };

            _grantedTokenRepositoryFake.Setup(g => g.GetTokenByRefreshTokenAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(grantedToken));
            _grantedTokenGeneratorHelperStub.Setup(g => g.GenerateTokenAsync(
                                                       It.IsAny <string>(),
                                                       It.IsAny <string>(),
                                                       It.IsAny <JwsPayload>(),
                                                       It.IsAny <JwsPayload>())).Returns(Task.FromResult(grantedToken));

            // ACT
            await _getTokenByRefreshTokenGrantTypeAction.Execute(parameter);

            // ASSERT
            _grantedTokenRepositoryFake.Verify(g => g.InsertAsync(It.IsAny <GrantedToken>()));
        }
Exemplo n.º 12
0
        public async Task <Option <GrantedToken> > Execute(
            RefreshTokenGrantTypeParameter refreshTokenGrantTypeParameter,
            AuthenticationHeaderValue?authenticationHeaderValue,
            X509Certificate2?certificate,
            string issuerName,
            CancellationToken cancellationToken)
        {
            // 1. Try to authenticate the client
            var instruction = authenticationHeaderValue.GetAuthenticateInstruction(
                refreshTokenGrantTypeParameter,
                certificate);
            var authResult = await _authenticateClient.Authenticate(instruction, issuerName, cancellationToken)
                             .ConfigureAwait(false);

            var client = authResult.Client;

            if (client == null)
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidClient,
                    Detail = authResult.ErrorMessage !
                });
        public async Task When_Requesting_Token_Then_New_One_Is_Generated()
        {
            var parameter = new RefreshTokenGrantTypeParameter {
                ClientId = "id", RefreshToken = "abc"
            };
            var grantedToken = new GrantedToken {
                IdTokenPayLoad = new JwtPayload(), ClientId = "id", Scope = "scope"
            };
            var client = new Client
            {
                ClientId    = "id",
                JsonWebKeys =
                    TestKeys.SecretKey.CreateJwk(JsonWebKeyUseNames.Sig, KeyOperations.Sign, KeyOperations.Verify)
                    .ToSet(),
                IdTokenSignedResponseAlg = SecurityAlgorithms.HmacSha256,
                Secrets = new[] { new ClientSecret {
                                      Type = ClientSecretTypes.SharedSecret, Value = "secret"
                                  } },
                GrantTypes = new[] { GrantTypes.RefreshToken }
            };

            _clientStore.Setup(x => x.GetById(It.IsAny <string>(), It.IsAny <CancellationToken>())).ReturnsAsync(client);
            _tokenStoreStub.Setup(g => g.GetRefreshToken(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(grantedToken);

            var authenticationHeader = new AuthenticationHeaderValue("Basic", "id:secret".Base64Encode());
            await _getTokenByRefreshTokenGrantTypeAction.Execute(
                parameter,
                authenticationHeader,
                null,
                "issuer",
                CancellationToken.None)
            .ConfigureAwait(false);

            _tokenStoreStub.Verify(g => g.AddToken(It.IsAny <GrantedToken>(), It.IsAny <CancellationToken>()));
        }