public async Task When_Client_Doesnt_Support_GrantType_RefreshToken_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            var authenticateInstruction = new AuthenticateInstruction();

            _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>()))
            .Returns(authenticateInstruction);
            var parameter = new RefreshTokenGrantTypeParameter();

            _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.authorization_code
                }
            }, null)));

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

            Assert.True(ex.Code == ErrorCodes.InvalidClient);
            Assert.True(ex.Message == string.Format(ErrorDescriptions.TheClientDoesntSupportTheGrantType, "id", GrantType.refresh_token));
        }
        public Task <bool> Handle(AuthenticateInstruction authenticateInstruction, OAuthClient client, string expectedIssuer, CancellationToken cancellationToken)
        {
            if (authenticateInstruction == null)
            {
                throw new ArgumentNullException(nameof(authenticateInstruction));
            }

            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (client.Secrets == null)
            {
                return(Task.FromResult(false));
            }

            var clientSecret = client.Secrets.FirstOrDefault(s => s.Type == ClientSecretTypes.SharedSecret);

            if (clientSecret == null)
            {
                return(Task.FromResult(false));
            }

            var result = string.Compare(clientSecret.Value, authenticateInstruction.ClientSecretFromHttpRequestBody, StringComparison.CurrentCultureIgnoreCase) == 0;

            return(Task.FromResult(result));
        }
        public async Task When_A_Jws_Token_With_Invalid_Signature_Is_Passed_To_AuthenticateClientWithPrivateKeyJwt_Then_Null_Is_Returned()
        {
            // ARRANGE
            InitializeFakeObjects();
            var instruction = new AuthenticateInstruction
            {
                ClientAssertion = "invalid_header.invalid_payload"
            };
            var jwsPayload = new JwsPayload();

            _jwtParserFake.Setup(j => j.IsJwsToken(It.IsAny <string>()))
            .Returns(true);
            _jwsParserFake.Setup(j => j.GetPayload(It.IsAny <string>()))
            .Returns(jwsPayload);
            _jwtParserFake.Setup(j => j.UnSignAsync(It.IsAny <string>(),
                                                    It.IsAny <string>()))
            .Returns(() => Task.FromResult((JwsPayload)null));

            // ACT
            var result = await _clientAssertionAuthentication.AuthenticateClientWithPrivateKeyJwtAsync(instruction);

            // ASSERT
            Assert.Null(result.Client);
            Assert.True(result.ErrorMessage == ErrorDescriptions.TheSignatureIsNotCorrect);
        }
コード例 #4
0
        public void When_Trying_To_Authenticate_The_Client_And_ThereIsNoSharedSecret_Then_Null_Is_Returned()
        {
            var authenticateInstruction = new AuthenticateInstruction
            {
                ClientSecretFromAuthorizationHeader = "notCorrectClientSecret"
            };
            var firstClient = new Client
            {
                Secrets = null
            };
            var secondClient = new Client
            {
                Secrets = new []
                {
                    new ClientSecret
                    {
                        Type = ClientSecretTypes.X509Thumbprint
                    }
                }
            };


            Assert.Null(ClientSecretPostAuthentication.AuthenticateClient(authenticateInstruction, firstClient));
            Assert.Null(ClientSecretPostAuthentication.AuthenticateClient(authenticateInstruction, secondClient));
        }
        public void When_Trying_To_Authenticate_The_Client_And_Credentials_Are_Not_Correct_Then_Null_Is_Returned()
        {
            // ARRANGE
            InitializeFakeObjects();
            var authenticateInstruction = new AuthenticateInstruction
            {
                ClientSecretFromHttpRequestBody = "notCorrectClientSecret"
            };
            var client = new Client
            {
                Secrets = new List <ClientSecret>
                {
                    new ClientSecret
                    {
                        Type  = ClientSecretTypes.SharedSecret,
                        Value = "secret"
                    }
                }
            };

            _clientPasswordServiceStub.Setup(c => c.Encrypt(It.IsAny <string>())).Returns("notCorrectClientSecret");

            // ACT
            var result = _clientSecretPostAuthentication.AuthenticateClient(authenticateInstruction, client);

            // ASSERT
            Assert.Null(result);
        }
コード例 #6
0
        When_Trying_To_Authenticate_The_Client_Via_Secret_Basic_Then_Operation_Is_Called_Client_Is_Returned_And_Events_Are_Logged()
        {
            const string clientId = "clientId";
            const string secret   = "secret";
            var          authenticationInstruction = new AuthenticateInstruction
            {
                ClientIdFromAuthorizationHeader     = clientId,
                ClientSecretFromAuthorizationHeader = secret
            };
            var client = new Client
            {
                Secrets = new[] { new ClientSecret {
                                      Type = ClientSecretTypes.SharedSecret, Value = secret
                                  } },
                TokenEndPointAuthMethod = TokenEndPointAuthenticationMethods.ClientSecretBasic,
                ClientId = clientId
            };

            _clientRepositoryStub.Setup(c => c.GetById(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(client);

            var result = await _authenticateClient.Authenticate(authenticationInstruction, null, CancellationToken.None)
                         .ConfigureAwait(false);

            Assert.NotNull(result.Client);
        }
コード例 #7
0
        public Task <bool> Handle(AuthenticateInstruction authenticateInstruction, OAuthClient client, string expectedIssuer, CancellationToken cancellationToken)
        {
            var certificate = authenticateInstruction.Certificate;

            if (certificate == null)
            {
                throw new OAuthException(ErrorCodes.INVALID_CLIENT_AUTH, ErrorMessages.NO_CLIENT_CERTIFICATE);
            }

            if (!string.IsNullOrWhiteSpace(client.TlsClientAuthSubjectDN) && client.TlsClientAuthSubjectDN != certificate.Subject)
            {
                throw new OAuthException(ErrorCodes.INVALID_CLIENT_AUTH, ErrorMessages.CERTIFICATE_SUBJECT_INVALID);
            }

            var subjectAlternative = certificate.GetSubjectAlternativeName();

            if (!string.IsNullOrWhiteSpace(client.TlsClientAuthSanDNS) && !Check(client.TlsClientAuthSanDNS, SubjectAlternativeNameTypes.DNSNAME, subjectAlternative))
            {
                throw new OAuthException(ErrorCodes.INVALID_CLIENT_AUTH, ErrorMessages.CERTIFICATE_SAN_DNS_INVALID);
            }

            if (!string.IsNullOrWhiteSpace(client.TlsClientAuthSanEmail) && !Check(client.TlsClientAuthSanEmail, SubjectAlternativeNameTypes.EMAIL, subjectAlternative))
            {
                throw new OAuthException(ErrorCodes.INVALID_CLIENT_AUTH, ErrorMessages.CERTIFICATE_SAN_EMAIL_INVALID);
            }

            if (!string.IsNullOrWhiteSpace(client.TlsClientAuthSanIP) && !Check(client.TlsClientAuthSanIP, SubjectAlternativeNameTypes.IPADDRESS, subjectAlternative))
            {
                throw new OAuthException(ErrorCodes.INVALID_CLIENT_AUTH, ErrorMessages.CERTIFICATE_SAN_IP_INVALID);
            }

            return(Task.FromResult(true));
        }
コード例 #8
0
        public async Task When_Trying_To_Authenticate_The_Client_Via_Secret_Basic_But_Operation_Failed_Then_Event_Is_Not_Logged_And_Null_Is_Returned()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientId = "clientId";
            var          authenticationInstruction = new AuthenticateInstruction();
            var          client = new Core.Common.Models.Client
            {
                TokenEndPointAuthMethod = TokenEndPointAuthenticationMethods.client_secret_basic,
                ClientId = clientId
            };

            _clientAssertionAuthenticationFake.Setup(c => c.GetClientId(It.IsAny <AuthenticateInstruction>()))
            .Returns(clientId);
            _clientRepositoryStub.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(client));
            _clientSecretBasicAuthenticationFake.Setup(
                c => c.AuthenticateClient(It.IsAny <AuthenticateInstruction>(), It.IsAny <Core.Common.Models.Client>()))
            .Returns(() => null);

            // ACT
            var result = await _authenticateClient.AuthenticateAsync(authenticationInstruction);

            // ASSERTS
            Assert.Null(result.Client);
            _simpleIdentityServerEventSourceFake.Verify(s => s.StartToAuthenticateTheClient(clientId, "client_secret_basic"));
            _simpleIdentityServerEventSourceFake.Verify(s => s.FinishToAuthenticateTheClient(It.IsAny <string>(), It.IsAny <string>()), Times.Never);
        }
        public async Task When_ClientCredentialGrantType_Is_Not_Supported_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            var clientCredentialsGrantTypeParameter = new ClientCredentialsGrantTypeParameter
            {
                Scope = "scope"
            };
            var client = new AuthenticationResult(new Core.Common.Models.Client
            {
                GrantTypes = new List <GrantType>
                {
                    GrantType.password
                }
            }, null);
            var authenticateInstruction = new AuthenticateInstruction();

            _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>()))
            .Returns(authenticateInstruction);
            _authenticateClientStub.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>()))
            .Returns(Task.FromResult(client));

            // ACT & ASSERT
            var exception = await Assert.ThrowsAsync <IdentityServerException>(() => _getTokenByClientCredentialsGrantTypeAction.Execute(clientCredentialsGrantTypeParameter, null));

            Assert.NotNull(exception);
            Assert.True(exception.Code == ErrorCodes.InvalidGrant);
            Assert.True(exception.Message == string.Format(ErrorDescriptions.TheClientDoesntSupportTheGrantType, client.Client.ClientId, GrantType.client_credentials));
        }
コード例 #10
0
        public void When_Trying_To_Authenticate_The_Client_And_Credentials_Are_Correct_Then_Client_Is_Returned()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientSecret            = "clientSecret";
            var          authenticateInstruction = new AuthenticateInstruction
            {
                ClientSecretFromHttpRequestBody = clientSecret
            };
            var client = new Models.Client
            {
                Secrets = new List <ClientSecret>
                {
                    new ClientSecret
                    {
                        Type  = ClientSecretTypes.SharedSecret,
                        Value = clientSecret
                    }
                }
            };

            // ACT
            var result = _clientSecretPostAuthentication.AuthenticateClient(authenticateInstruction, client);

            // ASSERT
            Assert.NotNull(result);
        }
        public async Task When_A_Jws_Token_With_Invalid_Issuer_Is_Passed_To_AuthenticateClientWithPrivateKeyJwt_Then_Null_Is_Returned()
        {
            // ARRANGE
            InitializeFakeObjects();
            var instruction = new AuthenticateInstruction
            {
                ClientAssertion = "invalid_header.invalid_payload"
            };
            var jwsPayload = new JwsPayload
            {
                {
                    StandardClaimNames.Issuer, "issuer"
                }
            };

            _jwtParserFake.Setup(j => j.IsJwsToken(It.IsAny <string>()))
            .Returns(true);
            _jwsParserFake.Setup(j => j.GetPayload(It.IsAny <string>()))
            .Returns(jwsPayload);
            _jwtParserFake.Setup(j => j.UnSignAsync(It.IsAny <string>(),
                                                    It.IsAny <string>()))
            .Returns(Task.FromResult(jwsPayload));
            _clientRepositoryStub.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(() => Task.FromResult((Core.Common.Models.Client)null));

            // ACT
            var result = await _clientAssertionAuthentication.AuthenticateClientWithPrivateKeyJwtAsync(instruction);

            // ASSERT
            Assert.Null(result.Client);
            Assert.True(result.ErrorMessage == ErrorDescriptions.TheClientIdPassedInJwtIsNotCorrect);
        }
コード例 #12
0
        public void When_Trying_To_Authenticate_The_Client_And_Credentials_Are_Not_Correct_Then_Null_Is_Returned()
        {
            // ARRANGE
            InitializeFakeObjects();
            var authenticateInstruction = new AuthenticateInstruction
            {
                ClientSecretFromAuthorizationHeader = "notCorrectClientSecret"
            };
            var client = new Core.Common.Models.Client
            {
                Secrets = new List <ClientSecret>
                {
                    new ClientSecret
                    {
                        Type  = ClientSecretTypes.SharedSecret,
                        Value = "not_correct"
                    }
                }
            };

            // ACT
            var result = _clientSecretBasicAuthentication.AuthenticateClient(authenticateInstruction, client);

            // ASSERT
            Assert.Null(result);
        }
コード例 #13
0
        public void When_Trying_To_Authenticate_The_Client_And_ThereIsNoSharedSecret_Then_Null_Is_Returned()
        {
            // ARRANGE
            InitializeFakeObjects();
            var authenticateInstruction = new AuthenticateInstruction
            {
                ClientSecretFromAuthorizationHeader = "notCorrectClientSecret"
            };
            var firstClient = new Client
            {
                Secrets = null
            };
            var secondClient = new Client
            {
                Secrets = new List <ClientSecret>
                {
                    new ClientSecret
                    {
                        Type = ClientSecretTypes.X509Thumbprint
                    }
                }
            };

            _clientPasswordServiceStub.Setup(c => c.Encrypt(It.IsAny <string>())).Returns(string.Empty);

            // ACTS & ASSERTS
            Assert.Null(_clientSecretBasicAuthentication.AuthenticateClient(authenticateInstruction, firstClient));
            Assert.Null(_clientSecretBasicAuthentication.AuthenticateClient(authenticateInstruction, secondClient));
        }
        public async Task When_RefreshToken_Is_Not_Issued_By_The_Same_Client_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            var authenticateInstruction = new AuthenticateInstruction();

            _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>()))
            .Returns(authenticateInstruction);
            var parameter = new RefreshTokenGrantTypeParameter();

            _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(new GrantedToken
            {
                ClientId = "differentId"
            }));

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

            Assert.True(ex.Code == ErrorCodes.InvalidGrant);
            Assert.True(ex.Message == ErrorDescriptions.TheRefreshTokenCanBeUsedOnlyByTheSameIssuer);
        }
        public async Task When_Decrypt_Client_Secret_Jwt_And_Cannot_Extract_Jws_PayLoad_Then_Null_Is_Returned()
        {
            // ARRANGE
            InitializeFakeObjects();
            var instruction = new AuthenticateInstruction
            {
                ClientAssertion = "valid_header.valid.valid.valid.valid"
            };

            _jwtParserFake.Setup(j => j.IsJweToken(It.IsAny <string>()))
            .Returns(true);
            _jwtParserFake.Setup(j => j.DecryptWithPasswordAsync(It.IsAny <string>(),
                                                                 It.IsAny <string>(),
                                                                 It.IsAny <string>()))
            .Returns(Task.FromResult("jws"));
            _jwtParserFake.Setup(j => j.IsJwsToken(It.IsAny <string>()))
            .Returns(true);
            _jwtParserFake.Setup(j => j.UnSignAsync(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(() => Task.FromResult((JwsPayload)null));

            // ACT
            var result = await _clientAssertionAuthentication.AuthenticateClientWithClientSecretJwtAsync(instruction, string.Empty);

            // ASSERT
            Assert.Null(result.Client);
            Assert.True(result.ErrorMessage == ErrorDescriptions.TheJwsPayloadCannotBeExtracted);
        }
        public async Task When_Decrypt_Client_Secret_Jwt_And_Its_Not_A_Jws_Token_Then_Null_Is_Returned()
        {
            // ARRANGE
            InitializeFakeObjects();
            var instruction = new AuthenticateInstruction
            {
                ClientAssertion = "valid_header.valid.valid.valid.valid"
            };

            _jwtParserFake.Setup(j => j.IsJweToken(It.IsAny <string>()))
            .Returns(true);
            _jwtParserFake.Setup(j => j.DecryptWithPasswordAsync(It.IsAny <string>(),
                                                                 It.IsAny <string>(),
                                                                 It.IsAny <string>()))
            .Returns(Task.FromResult("jws"));
            _jwtParserFake.Setup(j => j.IsJwsToken(It.IsAny <string>()))
            .Returns(false);

            // ACT
            var result = await _clientAssertionAuthentication.AuthenticateClientWithClientSecretJwtAsync(instruction, string.Empty, null);

            // ASSERT
            Assert.Null(result.Client);
            Assert.True(result.ErrorMessage == ErrorDescriptions.TheClientAssertionIsNotAJwsToken);
        }
コード例 #17
0
        public async Task When_Trying_To_Authenticate_The_Client_Via_Secret_Basic_Then_Operation_Is_Called_Client_Is_Returned_And_Events_Are_Logged()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientId = "clientId";
            var          authenticationInstruction = new AuthenticateInstruction();
            var          client = new Client
            {
                TokenEndPointAuthMethod = TokenEndPointAuthenticationMethods.client_secret_basic,
                ClientId = clientId
            };

            _clientAssertionAuthenticationFake.Setup(c => c.GetClientId(It.IsAny <AuthenticateInstruction>()))
            .Returns(clientId);
            _clientRepositoryStub.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(client));
            _clientSecretBasicAuthenticationFake.Setup(
                c => c.AuthenticateClient(It.IsAny <AuthenticateInstruction>(), It.IsAny <Client>()))
            .Returns(client);

            // ACT
            var result = await _authenticateClient.AuthenticateAsync(authenticationInstruction, null);

            // ASSERTS
            Assert.NotNull(result.Client);
            _oauthEventSource.Verify(s => s.StartToAuthenticateTheClient(clientId, "client_secret_basic"));
            _oauthEventSource.Verify(s => s.FinishToAuthenticateTheClient(clientId, "client_secret_basic"));
        }
コード例 #18
0
        private AuthenticateInstruction CreateAuthenticateInstruction(
            IntrospectionParameter introspectionParameter,
            AuthenticationHeaderValue authenticationHeaderValue)
        {
            var result = new AuthenticateInstruction
            {
                ClientAssertion                 = introspectionParameter.ClientAssertion,
                ClientAssertionType             = introspectionParameter.ClientAssertionType,
                ClientIdFromHttpRequestBody     = introspectionParameter.ClientId,
                ClientSecretFromHttpRequestBody = introspectionParameter.ClientSecret
            };

            if (authenticationHeaderValue != null &&
                !string.IsNullOrWhiteSpace(authenticationHeaderValue.Parameter))
            {
                var parameters = GetParameters(authenticationHeaderValue.Parameter);
                if (parameters != null && parameters.Count() == 2)
                {
                    result.ClientIdFromAuthorizationHeader     = parameters[0];
                    result.ClientSecretFromAuthorizationHeader = parameters[1];
                }
            }

            return(result);
        }
        public Task <bool> Handle(AuthenticateInstruction authenticateInstruction, OAuthClient client, string expectedIssuer)
        {
            if (authenticateInstruction == null)
            {
                throw new ArgumentNullException(nameof(authenticateInstruction));
            }

            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (client.Secrets == null)
            {
                return(Task.FromResult(false));
            }

            var clientSecret = client.Secrets.FirstOrDefault(s => s.Type == ClientSecretTypes.SharedSecret);

            if (clientSecret == null)
            {
                return(Task.FromResult(false));
            }

            var result = string.Compare(clientSecret.Value, PasswordHelper.ComputeHash(authenticateInstruction.ClientSecretFromAuthorizationHeader), StringComparison.CurrentCultureIgnoreCase) == 0;

            return(Task.FromResult(true));
        }
コード例 #20
0
        public void When_Trying_To_Authenticate_The_Client_And_ThereIsNoSharedSecret_Then_Null_Is_Returned()
        {
            // ARRANGE
            InitializeFakeObjects();
            var authenticateInstruction = new AuthenticateInstruction
            {
                ClientSecretFromAuthorizationHeader = "notCorrectClientSecret"
            };
            var firstClient = new Models.Client
            {
                Secrets = null
            };
            var secondClient = new Models.Client
            {
                Secrets = new List <ClientSecret>
                {
                    new ClientSecret
                    {
                        Type = ClientSecretTypes.X509Thumbprint
                    }
                }
            };

            // ACTS & ASSERTS
            Assert.Null(_clientSecretPostAuthentication.AuthenticateClient(authenticateInstruction, firstClient));
            Assert.Null(_clientSecretPostAuthentication.AuthenticateClient(authenticateInstruction, secondClient));
        }
コード例 #21
0
        public void When_Trying_To_Authenticate_The_Client_And_Credentials_Are_Correct_Then_Client_Is_Returned()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientSecret            = "clientSecret";
            var          authenticateInstruction = new AuthenticateInstruction
            {
                ClientSecretFromAuthorizationHeader = clientSecret
            };
            var client = new Client
            {
                Secrets = new List <ClientSecret>
                {
                    new ClientSecret
                    {
                        Type  = ClientSecretTypes.SharedSecret,
                        Value = clientSecret
                    }
                }
            };

            _clientPasswordServiceStub.Setup(c => c.Encrypt(It.IsAny <string>())).Returns(clientSecret);

            // ACT
            var result = _clientSecretBasicAuthentication.AuthenticateClient(authenticateInstruction, client);

            // ASSERT
            Assert.NotNull(result);
        }
        public async Task When_Access_Is_Granted_Then_Token_Is_Returned()
        {
            // ARRANGE
            const string scope       = "valid_scope";
            const string clientId    = "client_id";
            const string accessToken = "access_token";
            var          scopes      = new List <string> {
                scope
            };

            InitializeFakeObjects();
            var clientCredentialsGrantTypeParameter = new ClientCredentialsGrantTypeParameter
            {
                Scope = scope
            };
            var client = new AuthenticationResult(new Core.Common.Models.Client
            {
                GrantTypes = new List <GrantType>
                {
                    GrantType.client_credentials
                },
                ResponseTypes = new List <ResponseType>
                {
                    ResponseType.token
                },
                ClientId = clientId
            }, null);
            var grantedToken = new GrantedToken
            {
                ClientId       = clientId,
                AccessToken    = accessToken,
                IdTokenPayLoad = new JwsPayload()
            };
            var authenticateInstruction = new AuthenticateInstruction();

            _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>()))
            .Returns(authenticateInstruction);
            _authenticateClientStub.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>(), null))
            .Returns(Task.FromResult(client));
            _scopeValidatorStub.Setup(s => s.Check(It.IsAny <string>(), It.IsAny <Core.Common.Models.Client>()))
            .Returns(() => new ScopeValidationResult(true)
            {
                Scopes = scopes
            });
            _grantedTokenGeneratorHelperStub.Setup(g => g.GenerateTokenAsync(It.IsAny <Core.Common.Models.Client>(),
                                                                             It.IsAny <string>(),
                                                                             It.IsAny <string>(),
                                                                             It.IsAny <JwsPayload>(),
                                                                             It.IsAny <JwsPayload>()))
            .Returns(Task.FromResult(grantedToken));

            // ACT
            var result = await _getTokenByClientCredentialsGrantTypeAction.Execute(clientCredentialsGrantTypeParameter, null, null, null);

            // ASSERTS
            _oauthEventSource.Verify(s => s.GrantAccessToClient(clientId, accessToken, scope));
            Assert.NotNull(result);
            Assert.True(result.ClientId == clientId);
        }
        public async Task <bool> Handle(AuthenticateInstruction authenticateInstruction, OAuthClient client, string expectedIssuer)
        {
            if (authenticateInstruction == null)
            {
                throw new ArgumentNullException(nameof(authenticateInstruction));
            }

            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (client.Secrets == null)
            {
                throw new ArgumentNullException(nameof(client.Secrets));
            }

            var clientSecret = client.Secrets.FirstOrDefault(s => s.Type == ClientSecretTypes.SharedSecret);

            if (clientSecret == null)
            {
                throw new OAuthException(ErrorCodes.INVALID_CLIENT_AUTH, ErrorMessages.NO_CLIENT_SECRET);
            }

            var clientAssertion = authenticateInstruction.ClientAssertion;
            var isJweToken      = _jwtParser.IsJweToken(clientAssertion);

            if (!isJweToken)
            {
                throw new OAuthException(ErrorCodes.INVALID_CLIENT_AUTH, ErrorMessages.BAD_CLIENT_ASSERTION_FORMAT);
            }

            var clientId = authenticateInstruction.ClientIdFromHttpRequestBody;
            var jws      = await _jwtParser.Decrypt(clientAssertion, clientId, clientSecret.Value).ConfigureAwait(false);

            if (string.IsNullOrWhiteSpace(jws))
            {
                throw new OAuthException(ErrorCodes.INVALID_CLIENT_AUTH, ErrorMessages.BAD_CLIENT_ASSERTION_DECRYPTION);
            }

            var isJwsToken = _jwtParser.IsJwsToken(jws);

            if (!isJwsToken)
            {
                throw new OAuthException(ErrorCodes.INVALID_CLIENT_AUTH, ErrorMessages.BAD_CLIENT_ASSERTION_FORMAT);
            }

            var payload = await _jwtParser.Unsign(clientAssertion, clientId).ConfigureAwait(false);

            if (payload == null)
            {
                throw new OAuthException(ErrorCodes.INVALID_CLIENT_AUTH, ErrorMessages.BAD_CLIENT_ASSERTION_SIGNATURE);
            }

            return(ValidateJwsPayLoad(payload, expectedIssuer));
        }
コード例 #24
0
        public void When_Trying_To_Authenticate_The_Client_And_OneParameter_Is_Null_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            var authenticateInstruction = new AuthenticateInstruction();

            // ACT & ASSERTS
            Assert.Throws <ArgumentNullException>(() => _clientSecretPostAuthentication.AuthenticateClient(null, null));
            Assert.Throws <ArgumentNullException>(() => _clientSecretPostAuthentication.AuthenticateClient(authenticateInstruction, null));
        }
コード例 #25
0
        public async Task When_The_ClientId_Cannot_Be_Fetch_Then_Message_Error_Is_Returned_And_Result_Is_Null()
        {
            var authenticationInstruction = new AuthenticateInstruction();

            var result = await _authenticateClient.Authenticate(authenticationInstruction, null, CancellationToken.None)
                         .ConfigureAwait(false);

            Assert.Null(result.Client);
            Assert.Equal(SharedStrings.TheClientDoesntExist, result.ErrorMessage);
        }
コード例 #26
0
        public async Task <bool> Handle(AuthenticateInstruction authenticateInstruction, BaseClient client, string expectedIssuer, CancellationToken cancellationToken, string errorCode = ErrorCodes.INVALID_CLIENT)
        {
            var certificate = authenticateInstruction.Certificate;

            if (certificate == null)
            {
                throw new OAuthException(errorCode, ErrorMessages.NO_CLIENT_CERTIFICATE);
            }

            await CheckCertificate(certificate, client, errorCode);

            return(true);
        }
コード例 #27
0
        public async Task When_The_ClientId_Is_Not_Valid_Then_Message_Error_Is_Returned_And_Result_Is_Null()
        {
            var authenticationInstruction = new AuthenticateInstruction();

            _clientRepositoryStub.Setup(c => c.GetById(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult((Client)null));

            var result = await _authenticateClient.Authenticate(authenticationInstruction, null, CancellationToken.None)
                         .ConfigureAwait(false);

            Assert.Null(result.Client);
            Assert.Equal(SharedStrings.TheClientDoesntExist, result.ErrorMessage);
        }
        public async Task <bool> Handle(AuthenticateInstruction authenticateInstruction, BaseClient client, string expectedIssuer, CancellationToken cancellationToken, string errorCode = ErrorCodes.INVALID_CLIENT)
        {
            if (authenticateInstruction == null)
            {
                throw new ArgumentNullException(nameof(authenticateInstruction));
            }

            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (string.IsNullOrWhiteSpace(client.ClientSecret))
            {
                throw new OAuthException(errorCode, ErrorMessages.NO_CLIENT_SECRET);
            }

            var clientAssertion = authenticateInstruction.ClientAssertion;
            var isJweToken      = _jwtParser.IsJweToken(clientAssertion);

            if (!isJweToken)
            {
                throw new OAuthException(errorCode, ErrorMessages.BAD_CLIENT_ASSERTION_FORMAT);
            }

            var clientId = authenticateInstruction.ClientIdFromHttpRequestBody;
            var jws      = await _jwtParser.Decrypt(clientAssertion, clientId, client.ClientSecret, cancellationToken);

            if (string.IsNullOrWhiteSpace(jws))
            {
                throw new OAuthException(errorCode, ErrorMessages.BAD_CLIENT_ASSERTION_DECRYPTION);
            }

            var isJwsToken = _jwtParser.IsJwsToken(jws);

            if (!isJwsToken)
            {
                throw new OAuthException(errorCode, ErrorMessages.BAD_CLIENT_ASSERTION_FORMAT);
            }

            JwsPayload payload = await _jwtParser.Unsign(clientAssertion, clientId, cancellationToken, errorCode);

            if (payload == null)
            {
                throw new OAuthException(errorCode, ErrorMessages.BAD_CLIENT_ASSERTION_SIGNATURE);
            }

            return(ValidateJwsPayLoad(payload, expectedIssuer, errorCode));
        }
        public async Task When_Decrypt_Valid_Client_Secret_Jwt_Then_Client_Is_Returned()
        {
            // ARRANGE
            InitializeFakeObjects();
            var instruction = new AuthenticateInstruction
            {
                ClientAssertion = "valid_header.valid.valid.valid.valid"
            };
            var jwsPayload = new JwsPayload
            {
                {
                    StandardClaimNames.Issuer, "issuer"
                },
                {
                    Jwt.Constants.StandardResourceOwnerClaimNames.Subject, "issuer"
                },
                {
                    StandardClaimNames.Audiences, new []
                    {
                        "audience"
                    }
                },
                {
                    StandardClaimNames.ExpirationTime, DateTime.Now.AddDays(2).ConvertToUnixTimestamp()
                }
            };
            var client = new Core.Common.Models.Client();

            _jwtParserFake.Setup(j => j.IsJweToken(It.IsAny <string>()))
            .Returns(true);
            _jwtParserFake.Setup(j => j.DecryptWithPasswordAsync(It.IsAny <string>(),
                                                                 It.IsAny <string>(),
                                                                 It.IsAny <string>()))
            .Returns(Task.FromResult("jws"));
            _jwtParserFake.Setup(j => j.IsJwsToken(It.IsAny <string>()))
            .Returns(true);
            _jwtParserFake.Setup(j => j.UnSignAsync(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(Task.FromResult(jwsPayload));
            _clientRepositoryStub.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(client));
            _simpleIdentityServerConfiguratorFake.Setup(s => s.GetIssuerNameAsync())
            .Returns(Task.FromResult("audience"));

            // ACT
            var result = await _clientAssertionAuthentication.AuthenticateClientWithClientSecretJwtAsync(instruction, string.Empty);

            // ASSERT
            Assert.NotNull(result);
        }
コード例 #30
0
        public void When_Requesting_ClientId_Then_ClientId_Is_Returned()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientId    = "clientId";
            var          instruction = new AuthenticateInstruction
            {
                ClientIdFromHttpRequestBody = clientId
            };

            // ACT
            var result = _clientSecretPostAuthentication.GetClientId(instruction);

            // ASSERT
            Assert.True(clientId == result);
        }