Example #1
0
        public async Task When_Client_Cannot_Be_Authenticated_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientAssertion                 = "clientAssertion";
            const string clientAssertionType             = "clientAssertionType";
            const string clientId                        = "clientId";
            const string clientSecret                    = "clientSecret";
            var          resourceOwnerGrantTypeParameter = new ResourceOwnerGrantTypeParameter
            {
                ClientAssertion     = clientAssertion,
                ClientAssertionType = clientAssertionType,
                ClientId            = clientId,
                ClientSecret        = clientSecret
            };

            _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>()))
            .Returns(new AuthenticateInstruction());
            _authenticateClientFake.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>(), null))
            .Returns(() => Task.FromResult(new AuthenticationResult(null, "error")));
            _clientRepositoryStub.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(() => Task.FromResult((Core.Common.Models.Client)null));

            // ACT & ASSERTS
            var exception = await Assert.ThrowsAsync <IdentityServerException>(() => _getTokenByResourceOwnerCredentialsGrantTypeAction.Execute(resourceOwnerGrantTypeParameter, null, null, null));

            _oauthEventSource.Verify(s => s.Info("error"));
            Assert.True(exception.Code == ErrorCodes.InvalidClient);
            Assert.True(exception.Message == "error");
        }
Example #2
0
        public async Task <GrantedToken> GetTokenByResourceOwnerCredentialsGrantType(
            ResourceOwnerGrantTypeParameter resourceOwnerGrantTypeParameter,
            AuthenticationHeaderValue authenticationHeaderValue,
            X509Certificate2 certificate = null)
        {
            if (resourceOwnerGrantTypeParameter == null)
            {
                throw new ArgumentNullException(nameof(resourceOwnerGrantTypeParameter));
            }

            var processId = Guid.NewGuid().ToString();

            try
            {
                _eventPublisher.Publish(new GrantTokenViaResourceOwnerCredentialsReceived(Guid.NewGuid().ToString(), processId, _payloadSerializer.GetPayload(resourceOwnerGrantTypeParameter, authenticationHeaderValue), authenticationHeaderValue, 0));
                _simpleIdentityServerEventSource.StartGetTokenByResourceOwnerCredentials(resourceOwnerGrantTypeParameter.ClientId,
                                                                                         resourceOwnerGrantTypeParameter.UserName,
                                                                                         resourceOwnerGrantTypeParameter.Password);
                _resourceOwnerGrantTypeParameterValidator.Validate(resourceOwnerGrantTypeParameter);
                var result = await _getTokenByResourceOwnerCredentialsGrantType.Execute(resourceOwnerGrantTypeParameter,
                                                                                        authenticationHeaderValue, certificate);

                var accessToken   = result != null ? result.AccessToken : string.Empty;
                var identityToken = result != null ? result.IdToken : string.Empty;
                _simpleIdentityServerEventSource.EndGetTokenByResourceOwnerCredentials(accessToken, identityToken);
                _eventPublisher.Publish(new TokenGranted(Guid.NewGuid().ToString(), processId, _payloadSerializer.GetPayload(result), 1));
                return(result);
            }
            catch (IdentityServerException ex)
            {
                _eventPublisher.Publish(new OpenIdErrorReceived(Guid.NewGuid().ToString(), processId, ex.Code, ex.Message, 1));
                throw;
            }
        }
        public async Task When_AnonymousClient_Doesnt_Exist_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientAssertion                 = "clientAssertion";
            const string clientAssertionType             = "clientAssertionType";
            const string clientId                        = "clientId";
            const string clientSecret                    = "clientSecret";
            var          resourceOwnerGrantTypeParameter = new ResourceOwnerGrantTypeParameter
            {
                ClientAssertion     = clientAssertion,
                ClientAssertionType = clientAssertionType,
                ClientId            = clientId,
                ClientSecret        = clientSecret
            };

            _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>()))
            .Returns(new AuthenticateInstruction());
            _authenticateClientFake.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>()))
            .Returns(() => Task.FromResult(new AuthenticationResult(null, null)));
            _clientRepositoryStub.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(() => Task.FromResult((Client)null));

            // ACT & ASSERTS
            var exception = await Assert.ThrowsAsync <IdentityServerException>(() => _getTokenByResourceOwnerCredentialsGrantTypeAction.Execute(resourceOwnerGrantTypeParameter, null));

            _simpleIdentityServerEventSourceFake.Verify(s => s.Info(ErrorDescriptions.TheClientCannotBeAuthenticated));
            Assert.True(exception.Code == ErrorCodes.InternalError);
            Assert.True(exception.Message == string.Format(ErrorDescriptions.ClientIsNotValid, Constants.AnonymousClientId));
        }
 public GrantTokenViaResourceOwnerCredentialsReceived(string id, string processId, ResourceOwnerGrantTypeParameter parameter, AuthenticationHeaderValue authHeader, int order)
 {
     Id        = id;
     ProcessId = processId;
     Parameter = parameter;
     Order     = order;
 }
Example #5
0
        public async Task When_Requesting_Token_Via_Resource_Owner_Credentials_Grant_Type_Then_Events_Are_Logged()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientId      = "clientId";
            const string userName      = "******";
            const string password      = "******";
            const string accessToken   = "accessToken";
            const string identityToken = "identityToken";
            var          parameter     = new ResourceOwnerGrantTypeParameter
            {
                ClientId = clientId,
                UserName = userName,
                Password = password
            };
            var grantedToken = new GrantedToken
            {
                AccessToken = accessToken,
                IdToken     = identityToken
            };

            _getTokenByResourceOwnerCredentialsGrantTypeActionFake.Setup(
                g => g.Execute(It.IsAny <ResourceOwnerGrantTypeParameter>(), It.IsAny <AuthenticationHeaderValue>(), It.IsAny <X509Certificate2>()))
            .Returns(Task.FromResult(grantedToken));

            // ACT
            await _tokenActions.GetTokenByResourceOwnerCredentialsGrantType(parameter, null);

            // ASSERTS
            _simpleIdentityServerEventSourceFake.Verify(s => s.StartGetTokenByResourceOwnerCredentials(clientId, userName, password));
            _simpleIdentityServerEventSourceFake.Verify(s => s.EndGetTokenByResourceOwnerCredentials(accessToken, identityToken));
        }
        public async Task When_Client_Cannot_Be_Authenticated_Then_Error_Is_Returned()
        {
            InitializeFakeObjects();
            const string clientAssertion                 = "clientAssertion";
            const string clientAssertionType             = "clientAssertionType";
            const string clientId                        = "clientId";
            const string clientSecret                    = "clientSecret";
            var          resourceOwnerGrantTypeParameter = new ResourceOwnerGrantTypeParameter
            {
                ClientAssertion     = clientAssertion,
                ClientAssertionType = clientAssertionType,
                ClientId            = clientId,
                ClientSecret        = clientSecret
            };

            var authenticationHeader = new AuthenticationHeaderValue(
                "Basic",
                $"{clientId}:{clientSecret}".Base64Encode());
            var result = await _getTokenByResourceOwnerCredentialsGrantTypeAction.Execute(
                resourceOwnerGrantTypeParameter,
                authenticationHeader,
                null,
                null,
                CancellationToken.None)
                         .ConfigureAwait(false) as Option <GrantedToken> .Error;

            Assert.Equal(ErrorCodes.InvalidClient, result.Details.Title);
            Assert.Equal(string.Format(SharedStrings.TheClientDoesntExist), result.Details.Detail);
        }
        public async Task When_The_Resource_Owner_Is_Not_Valid_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientAssertion                 = "clientAssertion";
            const string clientAssertionType             = "clientAssertionType";
            const string clientId                        = "clientId";
            const string clientSecret                    = "clientSecret";
            var          resourceOwnerGrantTypeParameter = new ResourceOwnerGrantTypeParameter
            {
                ClientAssertion     = clientAssertion,
                ClientAssertionType = clientAssertionType,
                ClientId            = clientId,
                ClientSecret        = clientSecret
            };
            var client = new AuthenticationResult(new Models.Client(), null);

            _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>()))
            .Returns(new AuthenticateInstruction());
            _authenticateClientFake.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>()))
            .Returns(() => Task.FromResult(client));
            _resourceOwnerValidatorFake.Setup(
                r => r.AuthenticateResourceOwnerAsync(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(() => Task.FromResult((ResourceOwner)null));

            // ACT & ASSERTS
            var exception = await Assert.ThrowsAsync <IdentityServerException>(() => _getTokenByResourceOwnerCredentialsGrantTypeAction.Execute(resourceOwnerGrantTypeParameter, null));

            Assert.True(exception.Code == ErrorCodes.InvalidGrant);
            Assert.True(exception.Message == ErrorDescriptions.ResourceOwnerCredentialsAreNotValid);
        }
        public async Task When_Passing_A_Not_Allowed_Scopes_Then_Exception_Is_Throw()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientAssertion                 = "clientAssertion";
            const string clientAssertionType             = "clientAssertionType";
            const string clientId                        = "clientId";
            const string clientSecret                    = "clientSecret";
            const string invalidScope                    = "invalidScope";
            var          resourceOwnerGrantTypeParameter = new ResourceOwnerGrantTypeParameter
            {
                ClientAssertion     = clientAssertion,
                ClientAssertionType = clientAssertionType,
                ClientId            = clientId,
                ClientSecret        = clientSecret,
                Scope = invalidScope
            };
            var client        = new AuthenticationResult(new Models.Client(), null);
            var resourceOwner = new ResourceOwner();

            _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>()))
            .Returns(new AuthenticateInstruction());
            _authenticateClientFake.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>()))
            .Returns(() => Task.FromResult(client));
            _resourceOwnerValidatorFake.Setup(
                r => r.AuthenticateResourceOwnerAsync(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(() => Task.FromResult(resourceOwner));
            _scopeValidatorFake.Setup(s => s.Check(It.IsAny <string>(), It.IsAny <Models.Client>()))
            .Returns(() => new ScopeValidationResult(false));

            // ACT & ASSERTS
            var exception = await Assert.ThrowsAsync <IdentityServerException>(() => _getTokenByResourceOwnerCredentialsGrantTypeAction.Execute(resourceOwnerGrantTypeParameter, null));

            Assert.True(exception.Code == ErrorCodes.InvalidScope);
        }
        public async Task When_Passing_A_Not_Allowed_Scopes_Then_Error_Is_Returned()
        {
            const string clientAssertion                 = "clientAssertion";
            const string clientAssertionType             = "clientAssertionType";
            const string clientId                        = "clientId";
            const string clientSecret                    = "clientSecret";
            const string invalidScope                    = "invalidScope";
            var          resourceOwnerGrantTypeParameter = new ResourceOwnerGrantTypeParameter
            {
                ClientAssertion     = clientAssertion,
                ClientAssertionType = clientAssertionType,
                ClientId            = clientId,
                ClientSecret        = clientSecret,
                Scope = invalidScope
            };
            var client = new Client
            {
                ClientId = "id",
                Secrets  = new[] { new ClientSecret {
                                       Type = ClientSecretTypes.SharedSecret, Value = clientSecret
                                   } },
                GrantTypes    = new[] { GrantTypes.Password },
                ResponseTypes = new[] { ResponseTypeNames.IdToken, ResponseTypeNames.Token }
            };

            var resourceOwner       = new ResourceOwner();
            var authenticateService = new Mock <IAuthenticateResourceOwnerService>();

            authenticateService
            .Setup(
                x => x.AuthenticateResourceOwner(
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    It.IsAny <CancellationToken>()))
            .ReturnsAsync(resourceOwner);
            authenticateService.Setup(x => x.Amr).Returns("pwd");
            InitializeFakeObjects(authenticateService.Object);
            _clientStore.Setup(x => x.GetById(It.IsAny <string>(), It.IsAny <CancellationToken>())).ReturnsAsync(client);

            var authenticationHeader = new AuthenticationHeaderValue(
                "Basic",
                $"{clientId}:{clientSecret}".Base64Encode());
            var result = await _getTokenByResourceOwnerCredentialsGrantTypeAction.Execute(
                resourceOwnerGrantTypeParameter,
                authenticationHeader,
                null,
                null,
                CancellationToken.None)
                         .ConfigureAwait(false) as Option <GrantedToken> .Error;

            Assert.Equal(ErrorCodes.InvalidScope, result.Details.Title);
        }
Example #10
0
        private AuthenticateInstruction CreateAuthenticateInstruction(
            ResourceOwnerGrantTypeParameter resourceOwnerGrantTypeParameter,
            AuthenticationHeaderValue authenticationHeaderValue,
            X509Certificate2 certificate)
        {
            var result = _authenticateInstructionGenerator.GetAuthenticateInstruction(authenticationHeaderValue);

            result.ClientAssertion                 = resourceOwnerGrantTypeParameter.ClientAssertion;
            result.ClientAssertionType             = resourceOwnerGrantTypeParameter.ClientAssertionType;
            result.ClientIdFromHttpRequestBody     = resourceOwnerGrantTypeParameter.ClientId;
            result.ClientSecretFromHttpRequestBody = resourceOwnerGrantTypeParameter.ClientSecret;
            result.Certificate = certificate;
            return(result);
        }
        public void Validate(ResourceOwnerGrantTypeParameter parameter)
        {
            if (string.IsNullOrWhiteSpace(parameter.UserName))
            {
                throw new IdentityServerException(
                          ErrorCodes.InvalidRequestCode,
                          string.Format(ErrorDescriptions.MissingParameter, Constants.StandardTokenRequestParameterNames.UserName));
            }

            if (string.IsNullOrWhiteSpace(parameter.Password))
            {
                throw new IdentityServerException(
                          ErrorCodes.InvalidRequestCode,
                          string.Format(ErrorDescriptions.MissingParameter, Constants.StandardTokenRequestParameterNames.PasswordName));
            }
        }
Example #12
0
        public void When_Passing_Empty_UserName_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObject();
            var parameter = new ResourceOwnerGrantTypeParameter
            {
                ClientId = "clientId",
                UserName = null
            };

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

            Assert.True(exception.Code == ErrorCodes.InvalidRequestCode);
            Assert.True(exception.Message == string.Format(ErrorDescriptions.MissingParameter, Constants.StandardTokenRequestParameterNames.UserName));
        }
Example #13
0
        public async Task <Option <GrantedToken> > GetTokenByResourceOwnerCredentialsGrantType(
            ResourceOwnerGrantTypeParameter resourceOwnerGrantTypeParameter,
            AuthenticationHeaderValue?authenticationHeaderValue,
            X509Certificate2?certificate,
            string issuerName,
            CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(resourceOwnerGrantTypeParameter.UserName))
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidRequest,
                    Detail = string.Format(Strings.MissingParameter, StandardTokenRequestParameterNames.UserName)
                });
            }

            if (string.IsNullOrWhiteSpace(resourceOwnerGrantTypeParameter.Password))
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidRequest,
                    Detail = string.Format(
                        Strings.MissingParameter,
                        StandardTokenRequestParameterNames.PasswordName)
                });
            }

            if (string.IsNullOrWhiteSpace(resourceOwnerGrantTypeParameter.Scope))
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidRequest,
                    Detail = string.Format(Strings.MissingParameter, StandardTokenRequestParameterNames.ScopeName)
                });
            }

            return(await _getTokenByResourceOwnerCredentialsGrantType.Execute(
                       resourceOwnerGrantTypeParameter,
                       authenticationHeaderValue,
                       certificate,
                       issuerName,
                       cancellationToken).ConfigureAwait(false));
        }
        public async Task When_Client_GrantType_Is_Not_Valid_Then_Error_Is_Returned()
        {
            InitializeFakeObjects();
            const string clientAssertion                 = "clientAssertion";
            const string clientAssertionType             = "clientAssertionType";
            const string clientId                        = "clientId";
            const string clientSecret                    = "clientSecret";
            var          resourceOwnerGrantTypeParameter = new ResourceOwnerGrantTypeParameter
            {
                ClientAssertion     = clientAssertion,
                ClientAssertionType = clientAssertionType,
                ClientId            = clientId,
                ClientSecret        = clientSecret
            };

            var client = new Client
            {
                ClientId = clientId,
                Secrets  = new[] { new ClientSecret {
                                       Type = ClientSecretTypes.SharedSecret, Value = clientSecret
                                   } },
                GrantTypes = new[] { GrantTypes.AuthorizationCode }
            };

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

            var authenticationHeader = new AuthenticationHeaderValue(
                "Basic",
                $"{clientId}:{clientSecret}".Base64Encode());
            var result = await _getTokenByResourceOwnerCredentialsGrantTypeAction.Execute(
                resourceOwnerGrantTypeParameter,
                authenticationHeader,
                null,
                null,
                CancellationToken.None)
                         .ConfigureAwait(false) as Option <GrantedToken> .Error;

            Assert.Equal(ErrorCodes.InvalidGrant, result.Details.Title);
            Assert.Equal(
                string.Format(Strings.TheClientDoesntSupportTheGrantType, clientId, GrantTypes.Password),
                result.Details.Detail);
        }
        public string GetPayload(ResourceOwnerGrantTypeParameter parameter, AuthenticationHeaderValue authenticationHeaderValue)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            var clientId = GetClientId(authenticationHeaderValue);

            if (string.IsNullOrWhiteSpace(clientId))
            {
                clientId = parameter.ClientId;
            }

            var result = new Payload
            {
                ClientId      = clientId,
                Authorization = BuildAuthHeader(authenticationHeaderValue),
                Content       = parameter
            };

            return(JsonConvert.SerializeObject(result));
        }
Example #16
0
        public async Task <Option <GrantedToken> > Execute(
            ResourceOwnerGrantTypeParameter resourceOwnerGrantTypeParameter,
            AuthenticationHeaderValue?authenticationHeaderValue,
            X509Certificate2?certificate,
            string issuerName,
            CancellationToken cancellationToken)
        {
            // 1. Try to authenticate the client
            var instruction = authenticationHeaderValue.GetAuthenticateInstruction(
                resourceOwnerGrantTypeParameter,
                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 !
                });
Example #17
0
        public async Task When_Client_GrantType_Is_Not_Valid_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientAssertion                 = "clientAssertion";
            const string clientAssertionType             = "clientAssertionType";
            const string clientId                        = "clientId";
            const string clientSecret                    = "clientSecret";
            var          resourceOwnerGrantTypeParameter = new ResourceOwnerGrantTypeParameter
            {
                ClientAssertion     = clientAssertion,
                ClientAssertionType = clientAssertionType,
                ClientId            = clientId,
                ClientSecret        = clientSecret
            };

            _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>()))
            .Returns(new AuthenticateInstruction());
            _authenticateClientFake.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>(), null))
            .Returns(() => Task.FromResult(new AuthenticationResult(new Core.Common.Models.Client
            {
                ClientId   = "id",
                GrantTypes = new List <GrantType>
                {
                    GrantType.authorization_code
                }
            }, null)));
            _clientRepositoryStub.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(() => Task.FromResult((Core.Common.Models.Client)null));

            // ACT & ASSERTS
            var exception = await Assert.ThrowsAsync <IdentityServerException>(() => _getTokenByResourceOwnerCredentialsGrantTypeAction.Execute(resourceOwnerGrantTypeParameter, null, null, null));

            Assert.True(exception.Code == ErrorCodes.InvalidClient);
            Assert.True(exception.Message == string.Format(ErrorDescriptions.TheClientDoesntSupportTheGrantType, "id", GrantType.password));
        }
Example #18
0
        public async Task When_Requesting_An_AccessToken_For_An_Authenticated_User_Then_AccessToken_Is_Granted()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientAssertion                 = "clientAssertion";
            const string clientAssertionType             = "clientAssertionType";
            const string clientId                        = "clientId";
            const string clientSecret                    = "clientSecret";
            const string invalidScope                    = "invalidScope";
            const string accessToken                     = "accessToken";
            var          resourceOwnerGrantTypeParameter = new ResourceOwnerGrantTypeParameter
            {
                ClientAssertion     = clientAssertion,
                ClientAssertionType = clientAssertionType,
                ClientId            = clientId,
                ClientSecret        = clientSecret,
                Scope = invalidScope
            };
            var client = new AuthenticationResult(new Core.Common.Models.Client
            {
                ClientId   = clientId,
                GrantTypes = new List <GrantType>
                {
                    GrantType.password
                },
                ResponseTypes = new List <ResponseType>
                {
                    ResponseType.id_token,
                    ResponseType.token
                }
            }, null);
            var resourceOwner             = new ResourceOwner();
            var userInformationJwsPayload = new JwsPayload();
            var grantedToken = new GrantedToken
            {
                AccessToken    = accessToken,
                IdTokenPayLoad = new JwsPayload()
            };

            _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>()))
            .Returns(new AuthenticateInstruction());
            _authenticateClientFake.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>(), null))
            .Returns(() => Task.FromResult(client));
            _resourceOwnerAuthenticateHelperFake.Setup(
                r => r.Authenticate(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <IEnumerable <string> >()))
            .Returns(() => Task.FromResult(resourceOwner));
            _scopeValidatorFake.Setup(s => s.Check(It.IsAny <string>(), It.IsAny <Core.Common.Models.Client>()))
            .Returns(() => new ScopeValidationResult(true)
            {
                Scopes = new List <string> {
                    invalidScope
                }
            });
            _jwtGeneratorFake.Setup(
                j => j.GenerateIdTokenPayloadForScopesAsync(It.IsAny <ClaimsPrincipal>(), It.IsAny <AuthorizationParameter>(), It.IsAny <string>()))
            .Returns(() => Task.FromResult(userInformationJwsPayload));
            _grantedTokenHelperStub.Setup(g => g.GetValidGrantedTokenAsync(It.IsAny <string>(),
                                                                           It.IsAny <string>(),
                                                                           It.IsAny <JwsPayload>(),
                                                                           It.IsAny <JwsPayload>()))
            .Returns(Task.FromResult((GrantedToken)null));
            _grantedTokenGeneratorHelperFake.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
            await _getTokenByResourceOwnerCredentialsGrantTypeAction.Execute(resourceOwnerGrantTypeParameter, null, null, null);

            // ASSERT
            _tokenStoreStub.Verify(g => g.AddToken(grantedToken));
            _oauthEventSource.Verify(s => s.GrantAccessToClient(clientId, accessToken, invalidScope));
            _clientHelperStub.Verify(c => c.GenerateIdTokenAsync(It.IsAny <Core.Common.Models.Client>(), It.IsAny <JwsPayload>()));
        }
Example #19
0
        public async Task <GrantedToken> Execute(ResourceOwnerGrantTypeParameter resourceOwnerGrantTypeParameter, AuthenticationHeaderValue authenticationHeaderValue, X509Certificate2 certificate, string issuerName)
        {
            if (resourceOwnerGrantTypeParameter == null)
            {
                throw new ArgumentNullException(nameof(resourceOwnerGrantTypeParameter));
            }

            // 1. Try to authenticate the client
            var instruction = CreateAuthenticateInstruction(resourceOwnerGrantTypeParameter, authenticationHeaderValue, certificate);
            var authResult  = await _authenticateClient.AuthenticateAsync(instruction, issuerName);

            var client = authResult.Client;

            if (authResult.Client == null)
            {
                _oauthEventSource.Info(authResult.ErrorMessage);
                throw new IdentityServerException(ErrorCodes.InvalidClient, authResult.ErrorMessage);
            }

            // 2. Check the client.
            if (client.GrantTypes == null || !client.GrantTypes.Contains(GrantType.password))
            {
                throw new IdentityServerException(ErrorCodes.InvalidClient,
                                                  string.Format(ErrorDescriptions.TheClientDoesntSupportTheGrantType, client.ClientId, GrantType.password));
            }

            if (client.ResponseTypes == null || !client.ResponseTypes.Contains(ResponseType.token) || !client.ResponseTypes.Contains(ResponseType.id_token))
            {
                throw new IdentityServerException(ErrorCodes.InvalidClient, string.Format(ErrorDescriptions.TheClientDoesntSupportTheResponseType, client.ClientId, "token id_token"));
            }

            // 3. Try to authenticate a resource owner
            var resourceOwner = await _resourceOwnerAuthenticateHelper.Authenticate(resourceOwnerGrantTypeParameter.UserName,
                                                                                    resourceOwnerGrantTypeParameter.Password,
                                                                                    resourceOwnerGrantTypeParameter.AmrValues);

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

            // 4. Check if the requested scopes are valid
            var allowedTokenScopes = string.Empty;

            if (!string.IsNullOrWhiteSpace(resourceOwnerGrantTypeParameter.Scope))
            {
                var scopeValidation = _scopeValidator.Check(resourceOwnerGrantTypeParameter.Scope, client);
                if (!scopeValidation.IsValid)
                {
                    throw new IdentityServerException(ErrorCodes.InvalidScope, scopeValidation.ErrorMessage);
                }

                allowedTokenScopes = string.Join(" ", scopeValidation.Scopes);
            }

            // 5. Generate the user information payload and store it.
            var claims                 = resourceOwner.Claims;
            var claimsIdentity         = new ClaimsIdentity(claims, "simpleIdentityServer");
            var claimsPrincipal        = new ClaimsPrincipal(claimsIdentity);
            var authorizationParameter = new AuthorizationParameter
            {
                Scope = resourceOwnerGrantTypeParameter.Scope
            };
            var payload = await _jwtGenerator.GenerateIdTokenPayloadForScopesAsync(claimsPrincipal, authorizationParameter, issuerName);

            var generatedToken = await _grantedTokenHelper.GetValidGrantedTokenAsync(allowedTokenScopes, client.ClientId, payload, payload);

            if (generatedToken == null)
            {
                generatedToken = await _grantedTokenGeneratorHelper.GenerateTokenAsync(client, allowedTokenScopes, issuerName, payload, payload);

                if (generatedToken.IdTokenPayLoad != null)
                {
                    await _jwtGenerator.UpdatePayloadDate(generatedToken.IdTokenPayLoad);

                    generatedToken.IdToken = await _clientHelper.GenerateIdTokenAsync(client, generatedToken.IdTokenPayLoad);
                }

                await _tokenStore.AddToken(generatedToken);

                _oauthEventSource.GrantAccessToClient(client.ClientId, generatedToken.AccessToken, allowedTokenScopes);
            }

            return(generatedToken);
        }
        public async Task When_Requesting_An_AccessToken_For_An_Authenticated_User_Then_AccessToken_Is_Granted()
        {
            const string clientAssertion     = "clientAssertion";
            const string clientAssertionType = "clientAssertionType";
            const string clientId            = "clientId";
            const string clientSecret        = "clientSecret";
            const string invalidScope        = "invalidScope";
            //const string accessToken = "accessToken";
            var resourceOwnerGrantTypeParameter = new ResourceOwnerGrantTypeParameter
            {
                ClientAssertion     = clientAssertion,
                ClientAssertionType = clientAssertionType,
                ClientId            = clientId,
                ClientSecret        = clientSecret,
                Scope = invalidScope
            };
            var client = new Client
            {
                AllowedScopes = new[] { invalidScope },
                ClientId      = clientId,
                Secrets       = new[] { new ClientSecret {
                                            Type = ClientSecretTypes.SharedSecret, Value = clientSecret
                                        } },
                JsonWebKeys =
                    TestKeys.SecretKey.CreateJwk(JsonWebKeyUseNames.Sig, KeyOperations.Sign, KeyOperations.Verify)
                    .ToSet(),
                IdTokenSignedResponseAlg = SecurityAlgorithms.HmacSha256,
                GrantTypes    = new[] { GrantTypes.Password },
                ResponseTypes = new[] { ResponseTypeNames.IdToken, ResponseTypeNames.Token }
            };
            var resourceOwner = new ResourceOwner {
                Subject = "tester"
            };
            var authenticateService = new Mock <IAuthenticateResourceOwnerService>();

            authenticateService
            .Setup(
                x => x.AuthenticateResourceOwner(
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    It.IsAny <CancellationToken>()))
            .ReturnsAsync(resourceOwner);
            authenticateService.SetupGet(x => x.Amr).Returns("pwd");
            InitializeFakeObjects(authenticateService.Object);
            _clientStore.Setup(x => x.GetById(It.IsAny <string>(), It.IsAny <CancellationToken>())).ReturnsAsync(client);
            _scopeRepository.Setup(x => x.SearchByNames(It.IsAny <CancellationToken>(), It.IsAny <string[]>()))
            .ReturnsAsync(new[] { new Scope {
                                      Name = invalidScope
                                  } });

            var authenticationHeader = new AuthenticationHeaderValue(
                "Basic",
                $"{clientId}:{clientSecret}".Base64Encode());
            await _getTokenByResourceOwnerCredentialsGrantTypeAction.Execute(
                resourceOwnerGrantTypeParameter,
                authenticationHeader,
                null,
                "issuer",
                CancellationToken.None)
            .ConfigureAwait(false);

            _tokenStoreStub.Verify(g => g.AddToken(It.IsAny <GrantedToken>(), It.IsAny <CancellationToken>()));
            _eventPublisher.Verify(s => s.Publish(It.IsAny <TokenGranted>()));
        }
Example #21
0
        public async Task <GrantedToken> Execute(ResourceOwnerGrantTypeParameter resourceOwnerGrantTypeParameter, AuthenticationHeaderValue authenticationHeaderValue, X509Certificate2 certificate = null)
        {
            if (resourceOwnerGrantTypeParameter == null)
            {
                throw new ArgumentNullException(nameof(resourceOwnerGrantTypeParameter));
            }

            // 1. Try to authenticate the client
            var instruction = CreateAuthenticateInstruction(resourceOwnerGrantTypeParameter, authenticationHeaderValue, certificate);
            var authResult  = await _authenticateClient.AuthenticateAsync(instruction);

            var client = authResult.Client;

            if (authResult.Client == null)
            {
                _simpleIdentityServerEventSource.Info(ErrorDescriptions.TheClientCannotBeAuthenticated);
                client = await _clientRepository.GetClientByIdAsync(Constants.AnonymousClientId);

                if (client == null)
                {
                    throw new IdentityServerException(ErrorCodes.InternalError, string.Format(ErrorDescriptions.ClientIsNotValid, Constants.AnonymousClientId));
                }
            }

            // 2. Try to authenticate a resource owner
            var resourceOwner = await _authenticateResourceOwnerService.AuthenticateResourceOwnerAsync(resourceOwnerGrantTypeParameter.UserName, resourceOwnerGrantTypeParameter.Password);

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

            // 3. Check if the requested scopes are valid
            var allowedTokenScopes = string.Empty;

            if (!string.IsNullOrWhiteSpace(resourceOwnerGrantTypeParameter.Scope))
            {
                var scopeValidation = _scopeValidator.Check(resourceOwnerGrantTypeParameter.Scope, client);
                if (!scopeValidation.IsValid)
                {
                    throw new IdentityServerException(ErrorCodes.InvalidScope, scopeValidation.ErrorMessage);
                }

                allowedTokenScopes = string.Join(" ", scopeValidation.Scopes);
            }

            // 4. Generate the user information payload and store it.
            var claims                 = resourceOwner.Claims;
            var claimsIdentity         = new ClaimsIdentity(claims, "simpleIdentityServer");
            var claimsPrincipal        = new ClaimsPrincipal(claimsIdentity);
            var authorizationParameter = new AuthorizationParameter
            {
                Scope = resourceOwnerGrantTypeParameter.Scope
            };
            var payload = await _jwtGenerator.GenerateUserInfoPayloadForScopeAsync(claimsPrincipal, authorizationParameter);

            var generatedToken = await _grantedTokenHelper.GetValidGrantedTokenAsync(allowedTokenScopes, client.ClientId, payload, payload);

            if (generatedToken == null)
            {
                generatedToken = await _grantedTokenGeneratorHelper.GenerateTokenAsync(client.ClientId, allowedTokenScopes, payload, payload);

                await _grantedTokenRepository.InsertAsync(generatedToken);

                // Fill-in the id-token
                if (generatedToken.IdTokenPayLoad != null)
                {
                    generatedToken.IdToken = await _clientHelper.GenerateIdTokenAsync(client, generatedToken.IdTokenPayLoad);
                }

                _simpleIdentityServerEventSource.GrantAccessToClient(client.ClientId, generatedToken.AccessToken, allowedTokenScopes);
            }

            return(generatedToken);
        }