Example #1
0
        public async Task When_Validating_Authorization_Parameter_With_Invalid_ClientId_Then_Exception_Is_Thrown()
        {
            const string state    = "state";
            const string clientId = "clientId";
            var          authorizationParameter = new AuthorizationParameter
            {
                State        = state,
                Scope        = "scope",
                ClientId     = clientId,
                RedirectUrl  = new Uri("http://localhost"),
                ResponseType = "code",
                Prompt       = "none"
            };

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

            var exception = await _authorizationCodeGrantTypeParameterAuthEdpValidator.Validate(
                authorizationParameter,
                CancellationToken.None)
                            .ConfigureAwait(false) as Option <Client> .Error;

            Assert.Equal(
                new Option <Client> .Error(
                    new ErrorDetails
            {
                Title  = ErrorCodes.InvalidRequest,
                Detail = string.Format(Strings.ClientIsNotValid, clientId)
            },
                    state),
                exception);
        }
Example #2
0
        public async Task When_Requesting_IdentityToken_JwsPayload_With_No_Authorization_Request_Then_MandatoriesClaims_Are_Returned()
        {
            // ARRANGE
            InitializeMockObjects();
            const string issuerName             = "IssuerName";
            const string subject                = "*****@*****.**";
            var          authorizationParameter = new AuthorizationParameter();
            var          claims = new List <Claim>
            {
                new Claim(Constants.StandardResourceOwnerClaimNames.Subject, subject)
            };

            _clientRepositoryStub.Setup(c => c.GetAllAsync()).Returns(Task.FromResult(FakeOpenIdAssets.GetClients()));

            // ACT
            var result = await _jwtGenerator.GenerateIdTokenPayloadForScopesAsync(claims, authorizationParameter, null);

            // ASSERT
            Assert.NotNull(result);
            Assert.True(result.ContainsKey(Constants.StandardResourceOwnerClaimNames.Subject));
            Assert.True(result.ContainsKey(StandardClaimNames.Audiences));
            Assert.True(result.ContainsKey(StandardClaimNames.ExpirationTime));
            Assert.True(result.ContainsKey(StandardClaimNames.Iat));
            Assert.True(result.GetClaimValue(Constants.StandardResourceOwnerClaimNames.Subject) == subject);
        }
        public async Task When_Resource_Owner_Cannot_Be_Authenticated_Then_Error_Message_Is_Returned()
        {
            var authenticateService = new Mock <IAuthenticateResourceOwnerService>();

            authenticateService.SetupGet(x => x.Amr).Returns("pwd");
            authenticateService
            .Setup(
                x => x.AuthenticateResourceOwner(
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    It.IsAny <CancellationToken>()))
            .ReturnsAsync((ResourceOwner)null);
            InitializeFakeObjects(authenticateService.Object);
            var localAuthenticationParameter = new LocalAuthenticationParameter();
            var authorizationParameter       = new AuthorizationParameter();

            var result = await _localUserAuthenticationAction !.Execute(
                localAuthenticationParameter,
                authorizationParameter,
                "",
                "",
                CancellationToken.None)
                         .ConfigureAwait(false);

            Assert.NotNull(result.ErrorMessage);
        }
        public async Task When_Validating_Authorization_Parameter_With_Not_Well_Formed_Uri_Then_Exception_Is_Thrown()
        {
            // The redirect_uri is considered well-formed according to the RFC-3986
            // ARRANGE
            InitializeFakeObjects();
            const string state = "state";
            var          authorizationParameter = new AuthorizationParameter
            {
                State        = state,
                Scope        = "scope",
                ClientId     = "clientId",
                RedirectUrl  = "not_well_formed_uri",
                ResponseType = "code",
                Prompt       = "none"
            };

            _parameterParserHelperFake.Setup(p => p.ParsePrompts(It.IsAny <string>()))
            .Returns(new List <PromptParameter>
            {
                PromptParameter.none
            });

            // ACT & ASSERT
            var exception = await Assert.ThrowsAsync <IdentityServerExceptionWithState>(
                () => _authorizationCodeGrantTypeParameterAuthEdpValidator.ValidateAsync(authorizationParameter));

            Assert.True(exception.Code == ErrorCodes.InvalidRequestCode);
            Assert.True(exception.Message == ErrorDescriptions.TheRedirectionUriIsNotWellFormed);
            Assert.True(exception.State == state);
        }
Example #5
0
        public async Task When_Requesting_IdentityToken_JwsPayload_And_IndicateTheMaxAge_Then_TheJwsPayload_Contains_AuthenticationTime()
        {
            // ARRANGE
            InitializeMockObjects();
            const string subject = "*****@*****.**";
            var          currentDateTimeOffset = DateTimeOffset.UtcNow.ConvertToUnixTimestamp();
            var          claims = new List <Claim>
            {
                new Claim(ClaimTypes.AuthenticationInstant, currentDateTimeOffset.ToString()),
                new Claim(Constants.StandardResourceOwnerClaimNames.Subject, subject)
            };
            var authorizationParameter = new AuthorizationParameter
            {
                MaxAge = 2
            };

            _clientRepositoryStub.Setup(c => c.GetAllAsync()).Returns(Task.FromResult(FakeOpenIdAssets.GetClients()));

            // ACT
            var result = await _jwtGenerator.GenerateIdTokenPayloadForScopesAsync(claims, authorizationParameter, null, currentDateTimeOffset);

            // ASSERT
            Assert.NotNull(result);
            Assert.True(result.ContainsKey(Constants.StandardResourceOwnerClaimNames.Subject));
            Assert.True(result.ContainsKey(StandardClaimNames.AuthenticationTime));
            Assert.True(result[Constants.StandardResourceOwnerClaimNames.Subject].ToString().Equals(subject));
            Assert.NotEmpty(result[StandardClaimNames.AuthenticationTime].ToString());
        }
        public async Task When_No_Consent_Has_Been_Given_And_Client_Doesnt_Exist_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientId               = "clientId";
            const string state                  = "state";
            var          claimsIdentity         = new ClaimsIdentity();
            var          claimsPrincipal        = new ClaimsPrincipal(claimsIdentity);
            var          authorizationParameter = new AuthorizationParameter
            {
                ClientId = clientId,
                State    = state
            };

            _consentHelperFake.Setup(c => c.GetConfirmedConsentsAsync(It.IsAny <string>(),
                                                                      It.IsAny <AuthorizationParameter>()))
            .Returns(Task.FromResult((Models.Consent)null));
            _clientRepositoryFake.Setup(c => c.GetClientByIdAsync(It.IsAny <string>())).
            Returns(Task.FromResult((Client)null));

            // ACT & ASSERTS
            var exception = await Assert.ThrowsAsync <IdentityServerExceptionWithState>(() => _displayConsentAction.Execute(authorizationParameter,
                                                                                                                            claimsPrincipal));

            Assert.True(exception.Code == ErrorCodes.InvalidRequestCode);
            Assert.True(exception.Message == string.Format(ErrorDescriptions.ClientIsNotValid, clientId));
            Assert.True(exception.State == state);
        }
        public async Task When_A_Consent_Has_Been_Given_And_The_AuthorizationFlow_Is_Not_Supported_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientId               = "clientId";
            const string state                  = "state";
            var          claimsIdentity         = new ClaimsIdentity();
            var          claimsPrincipal        = new ClaimsPrincipal(claimsIdentity);
            var          responseTypes          = new List <ResponseType>();
            var          authorizationParameter = new AuthorizationParameter
            {
                ClientId     = clientId,
                State        = state,
                ResponseMode = ResponseMode.None // No response mode is defined
            };
            var consent = new Core.Models.Consent();

            _clientRepositoryFake.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(new Client()));
            _consentHelperFake.Setup(c => c.GetConfirmedConsentsAsync(It.IsAny <string>(),
                                                                      It.IsAny <AuthorizationParameter>()))
            .Returns(Task.FromResult(consent));
            _parameterParserHelperFake.Setup(p => p.ParseResponseTypes(It.IsAny <string>()))
            .Returns(responseTypes);

            // ACT & ASSERTS
            var exception = await Assert.ThrowsAsync <IdentityServerExceptionWithState>(() => _displayConsentAction.Execute(authorizationParameter,
                                                                                                                            claimsPrincipal));

            Assert.True(exception.Code == ErrorCodes.InvalidRequestCode);
            Assert.True(exception.Message == ErrorDescriptions.TheAuthorizationFlowIsNotSupported);
            Assert.True(exception.State == state);
        }
Example #8
0
        private static AuthorizationParameter GetAuthorizationParameter(
            AuthorizationParameter authorizationParameter, HttpResponseMessage message)
        {
            var wwwAuthenticateHeader = message.Headers.WwwAuthenticate.First();

            string   realm;
            string   domain;
            string   nonce;
            string   qop;
            string   cnonce;
            DateTime cnonceDate;

            ParseDigestAuthHeaderData(wwwAuthenticateHeader.Parameter, out realm, out domain, out nonce, out qop, out cnonce, out cnonceDate);

            // delete the old parameter first, this mostly the case, when the server requires a renewal of the parameter
            AuthorizationParameter oldAuthorizationParameter;

            _authorizationCache.TryRemove(
                domain, out oldAuthorizationParameter);

            authorizationParameter = new AuthorizationParameter
            {
                realm      = realm,
                nonce      = nonce,
                qop        = qop,
                cnonce     = cnonce,
                cnonceDate = cnonceDate
            };

            _authorizationCache.TryAdd(
                domain, authorizationParameter);

            return(authorizationParameter);
        }
        public async Task WhenClientRequirePKCEAndNoCodeChallengeIsPassedThenAnErrorIsReturned()
        {
            const string clientId = "clientId";
            const string scope    = OpenIdScope;

            var redirectUrl = new Uri(HttpsLocalhost);

            InitializeFakeObjects(
                new Client
            {
                ResponseTypes   = new[] { ResponseTypeNames.IdToken },
                ClientId        = clientId,
                RequirePkce     = true,
                RedirectionUrls = new[] { redirectUrl }
            });

            var authorizationParameter = new AuthorizationParameter
            {
                ClientId     = clientId,
                ResponseType = ResponseTypeNames.IdToken,
                Scope        = scope,
                RedirectUrl  = redirectUrl
            };

            var result = await _authorizationActions.GetAuthorization(
                authorizationParameter,
                new ClaimsPrincipal(),
                "",
                CancellationToken.None)
                         .ConfigureAwait(false);

            Assert.Equal(ActionResultType.BadRequest, result.Type);
        }
        public async Task When_The_Subject_Is_Not_Specified_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string subject = "subject";
            var          claims  = new List <Claim>
            {
                new Claim("invalid_subject", subject)
            };
            var authorizationParameter = new AuthorizationParameter();
            var code         = "code";
            var actionResult = new ActionResult
            {
                Type = TypeActionResult.None
            };

            _authenticateHelperStub.Setup(a => a.ProcessRedirection(It.IsAny <AuthorizationParameter>(),
                                                                    It.IsAny <string>(),
                                                                    It.IsAny <string>(),
                                                                    It.IsAny <List <Claim> >())).Returns(Task.FromResult(actionResult));

            // ACT & ASSERT
            var exception = await Assert.ThrowsAsync <IdentityServerException>(() => _externalOpenIdUserAuthenticationAction.Execute(claims, authorizationParameter, code));

            Assert.True(exception.Message == ErrorDescriptions.NoSubjectCanBeExtracted);
        }
Example #11
0
        public async Task WhenGrantTypeIsNotSupportedThenAnErrorIsReturned()
        {
            var redirectUrl            = new Uri("https://localhost");
            var authorizationParameter = new AuthorizationParameter
            {
                RedirectUrl  = redirectUrl,
                State        = "state",
                Nonce        = "nonce",
                Scope        = "openid",
                ResponseType = ResponseTypeNames.Code,
            };

            var client = new Client {
                RedirectionUrls = new[] { redirectUrl }, AllowedScopes = new[] { "openid" },
            };
            var ex = await _getAuthorizationCodeAndTokenViaHybridWorkflowOperation.Execute(
                authorizationParameter,
                new ClaimsPrincipal(),
                client,
                null,
                CancellationToken.None)
                     .ConfigureAwait(false);

            Assert.Equal(ActionResultType.BadRequest, ex.Type);
        }
Example #12
0
        public async Task When_Passing_Valid_Request_Then_Events_Are_Logged()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientId     = "clientId";
            const string scope        = "scope";
            var          actionResult = new ActionResult
            {
                Type = TypeActionResult.RedirectToAction,
                RedirectInstruction = new RedirectInstruction
                {
                    Action = IdentityServerEndPoints.FormIndex
                }
            };
            var client = new Client();
            var authorizationParameter = new AuthorizationParameter
            {
                ClientId = clientId,
                Scope    = scope,
                Claims   = null
            };
            var jsonAuthorizationParameter = JsonConvert.SerializeObject(authorizationParameter);

            _processAuthorizationRequestFake.Setup(p => p.ProcessAsync(
                                                       It.IsAny <AuthorizationParameter>(), It.IsAny <Client>(), null, null, null)).Returns(Task.FromResult(actionResult));
            _clientValidatorFake.Setup(c => c.CheckGrantTypes(It.IsAny <Client>(), It.IsAny <GrantType[]>()))
            .Returns(true);

            // ACT
            await _getAuthorizationCodeOperation.Execute(authorizationParameter, client, null);

            // ASSERTS
            _oauthEventSource.Verify(s => s.StartAuthorizationCodeFlow(clientId, scope, string.Empty));
            _oauthEventSource.Verify(s => s.EndAuthorizationCodeFlow(clientId, "RedirectToAction", "FormIndex"));
        }
Example #13
0
        public async Task When_Validating_Authorization_Parameter_With_Empty_RedirectUri_Then_Exception_Is_Thrown()
        {
            const string state = "state";
            var          authorizationParameter = new AuthorizationParameter
            {
                State = state, Scope = "scope", ClientId = "clientId"
            };

            var exception = await _authorizationCodeGrantTypeParameterAuthEdpValidator.Validate(
                authorizationParameter,
                CancellationToken.None)
                            .ConfigureAwait(false) as Option <Client> .Error;

            Assert.Equal(
                new Option <Client> .Error(
                    new ErrorDetails
            {
                Title  = ErrorCodes.InvalidRequest,
                Detail = string.Format(
                    Strings.MissingParameter,
                    CoreConstants.StandardAuthorizationRequestParameterNames.RedirectUriName)
            },
                    state),
                exception);
        }
Example #14
0
        When_Validating_Authorization_Parameter_With_RedirectUri_Not_Known_By_The_Client_Then_Exception_Is_Thrown()
        {
            const string state                  = "state";
            const string clientId               = "clientId";
            const string redirectUri            = "http://localhost/";
            var          authorizationParameter = new AuthorizationParameter
            {
                State        = state,
                Scope        = "scope",
                ClientId     = clientId,
                RedirectUrl  = new Uri(redirectUri),
                ResponseType = "code",
                Prompt       = "none"
            };
            var client = new Client();

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

            var exception = await _authorizationCodeGrantTypeParameterAuthEdpValidator.Validate(
                authorizationParameter,
                CancellationToken.None)
                            .ConfigureAwait(false);

            Assert.Equal(
                new Option <Client> .Error(
                    new ErrorDetails
            {
                Title  = ErrorCodes.InvalidRequest,
                Detail = string.Format(Strings.RedirectUrlIsNotValid, redirectUri)
            },
                    state),
                exception);
        }
        public async Task When_Client_Require_PKCE_And_NoCodeChallenge_Is_Passed_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            const string clientId     = "clientId";
            const string responseType = "id_token";
            const string scope        = "openid";

            InitializeFakeObjects();
            _authorizationCodeGrantTypeParameterAuthEdpValidatorFake.Setup(a => a.ValidateAsync(It.IsAny <AuthorizationParameter>()))
            .Returns(Task.FromResult(new Core.Common.Models.Client
            {
                RequirePkce = true,
                ClientId    = clientId
            }));

            var authorizationParameter = new AuthorizationParameter
            {
                ClientId     = clientId,
                ResponseType = responseType,
                Scope        = scope,
            };

            // ACT & ASSERT
            var result = await Assert.ThrowsAsync <IdentityServerExceptionWithState>(() => _authorizationActions.GetAuthorization(authorizationParameter, null, null));

            Assert.True(result.Code == ErrorCodes.InvalidRequestCode);
            Assert.True(result.Message == string.Format(ErrorDescriptions.TheClientRequiresPkce, clientId));
        }
Example #16
0
        public async Task When_Resource_Owner_Credentials_Are_Correct_Then_Event_Is_Logged_And_Claims_Are_Returned()
        {
            // ARRANGE
            const string subject = "subject";

            InitializeFakeObjects();
            var localAuthenticationParameter = new LocalAuthenticationParameter();
            var authorizationParameter       = new AuthorizationParameter();
            var resourceOwner = new ResourceOwner
            {
                Id = subject
            };

            _authenticateResourceOwnerServiceStub.Setup(r => r.AuthenticateResourceOwnerAsync(It.IsAny <string>(), It.IsAny <string>())).Returns(Task.FromResult(resourceOwner));

            // ACT
            var result = await _localUserAuthenticationAction.Execute(localAuthenticationParameter,
                                                                      authorizationParameter,
                                                                      null);

            // Specify the resource owner authentication date
            Assert.NotNull(result);
            Assert.NotNull(result.Claims);
            Assert.True(result.Claims.Any(r => r.Type == ClaimTypes.AuthenticationInstant ||
                                          r.Type == Jwt.Constants.StandardResourceOwnerClaimNames.Subject));
        }
        public async Task <ActionResult> ProcessRedirection(
            AuthorizationParameter authorizationParameter,
            string code,
            string subject,
            List <Claim> claims, string issuerName)
        {
            if (authorizationParameter == null)
            {
                throw new ArgumentNullException(nameof(authorizationParameter));
            }

            var client = await _clientRepository.GetClientByIdAsync(authorizationParameter.ClientId);

            if (client == null)
            {
                throw new InvalidOperationException(string.Format(ErrorDescriptions.TheClientIdDoesntExist,
                                                                  authorizationParameter.ClientId));
            }

            // Redirect to the consent page if the prompt parameter contains "consent"
            ActionResult result;
            var          prompts = _parameterParserHelper.ParsePrompts(authorizationParameter.Prompt);

            if (prompts != null &&
                prompts.Contains(PromptParameter.consent))
            {
                result = _actionResultFactory.CreateAnEmptyActionResultWithRedirection();
                result.RedirectInstruction.Action = IdentityServerEndPoints.ConsentIndex;
                result.RedirectInstruction.AddParameter("code", code);
                return(result);
            }

            var assignedConsent = await _consentHelper.GetConfirmedConsentsAsync(subject, authorizationParameter);

            // If there's already one consent then redirect to the callback
            if (assignedConsent != null)
            {
                result = _actionResultFactory.CreateAnEmptyActionResultWithRedirectionToCallBackUrl();
                var claimsIdentity  = new ClaimsIdentity(claims, "simpleIdentityServer");
                var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
                await _generateAuthorizationResponse.ExecuteAsync(result, authorizationParameter, claimsPrincipal, client, issuerName);

                var responseMode = authorizationParameter.ResponseMode;
                if (responseMode == ResponseMode.None)
                {
                    var responseTypes     = _parameterParserHelper.ParseResponseTypes(authorizationParameter.ResponseType);
                    var authorizationFlow = GetAuthorizationFlow(responseTypes, authorizationParameter.State);
                    responseMode = GetResponseMode(authorizationFlow);
                }

                result.RedirectInstruction.ResponseMode = responseMode;
                return(result);
            }

            // If there's no consent & there's no consent prompt then redirect to the consent screen.
            result = _actionResultFactory.CreateAnEmptyActionResultWithRedirection();
            result.RedirectInstruction.Action = IdentityServerEndPoints.ConsentIndex;
            result.RedirectInstruction.AddParameter("code", code);
            return(result);
        }
        public async Task When_Redirected_To_Callback_And_Resource_Owner_Is_Not_Authenticated_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            var authorizationParameter = new AuthorizationParameter
            {
                State = "state"
            };

            var actionResult = new ActionResult
            {
                Type = TypeActionResult.RedirectToCallBackUrl
            };

            _processAuthorizationRequestFake.Setup(p => p.ProcessAsync(It.IsAny <AuthorizationParameter>(),
                                                                       It.IsAny <ClaimsPrincipal>(), It.IsAny <Core.Common.Models.Client>(), null))
            .Returns(Task.FromResult(actionResult));
            _clientValidatorFake.Setup(c => c.CheckGrantTypes(It.IsAny <Core.Common.Models.Client>(), It.IsAny <GrantType[]>()))
            .Returns(true);

            // ACT & ASSERT
            var ex = await Assert.ThrowsAsync <IdentityServerExceptionWithState>(
                () => _getAuthorizationCodeOperation.Execute(authorizationParameter, null, new Core.Common.Models.Client(), null));

            Assert.True(ex.Code == ErrorCodes.InvalidRequestCode);
            Assert.True(ex.Message ==
                        ErrorDescriptions.TheResponseCannotBeGeneratedBecauseResourceOwnerNeedsToBeAuthenticated);
            Assert.True(ex.State == authorizationParameter.State);
        }
        public async Task When_A_Consent_Has_Been_Given_Then_Redirect_To_Callback()
        {
            // ARRANGE
            InitializeFakeObjects();
            var claimsIdentity  = new ClaimsIdentity();
            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            var actionResult    = new ActionResult
            {
                RedirectInstruction = new RedirectInstruction()
            };
            var authorizationParameter = new AuthorizationParameter
            {
                ResponseMode = ResponseMode.fragment
            };
            var consent = new Core.Models.Consent();

            _clientRepositoryFake.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(new Client()));
            _consentHelperFake.Setup(c => c.GetConfirmedConsentsAsync(It.IsAny <string>(),
                                                                      It.IsAny <AuthorizationParameter>()))
            .Returns(Task.FromResult(consent));
            _actionResultFactoryFake.Setup(a => a.CreateAnEmptyActionResultWithRedirectionToCallBackUrl())
            .Returns(actionResult);

            // ACT
            var result = await _displayConsentAction.Execute(authorizationParameter, claimsPrincipal);

            // ASSERT
            _actionResultFactoryFake.Verify(a => a.CreateAnEmptyActionResultWithRedirectionToCallBackUrl());
            Assert.True(result.ActionResult.RedirectInstruction.ResponseMode == ResponseMode.fragment);
        }
Example #20
0
        public async Task When_No_Consent_Has_Been_Given_Then_Create_And_Insert_A_New_One()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string subject = "subject";
            var          authorizationParameter = new AuthorizationParameter
            {
                Claims       = null,
                Scope        = "profile",
                ResponseMode = ResponseMode.None
            };
            var claims = new List <Claim>
            {
                new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, subject)
            };
            var claimsIdentity  = new ClaimsIdentity(claims, "SimpleIdentityServer");
            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            var client          = new Models.Client
            {
                ClientId = "clientId"
            };
            var resourceOwner = new ResourceOwner
            {
                Id = subject
            };
            var actionResult = new ActionResult
            {
                Type = TypeActionResult.RedirectToCallBackUrl,
                RedirectInstruction = new RedirectInstruction
                {
                }
            };
            ICollection <Scope> scopes = new List <Scope>();

            _consentHelperFake.Setup(c => c.GetConfirmedConsentsAsync(It.IsAny <string>(),
                                                                      It.IsAny <AuthorizationParameter>()))
            .Returns(Task.FromResult((Models.Consent)null));
            _clientRepositoryFake.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(client));
            _parameterParserHelperFake.Setup(p => p.ParseScopes(It.IsAny <string>()))
            .Returns(new List <string>());
            _scopeRepositoryFake.Setup(s => s.SearchByNamesAsync(It.IsAny <IEnumerable <string> >()))
            .Returns(Task.FromResult(scopes));
            _authenticateResourceOwnerServiceStub.Setup(r => r.AuthenticateResourceOwnerAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(resourceOwner));
            _actionResultFactoryFake.Setup(a => a.CreateAnEmptyActionResultWithRedirectionToCallBackUrl())
            .Returns(actionResult);
            _parameterParserHelperFake.Setup(p => p.ParseResponseTypes(It.IsAny <string>()))
            .Returns(new List <ResponseType> {
                ResponseType.code
            });

            // ACT
            var result = await _confirmConsentAction.Execute(authorizationParameter, claimsPrincipal);

            // ASSERT
            _consentRepositoryFake.Verify(c => c.InsertAsync(It.IsAny <Models.Consent>()));
            _actionResultFactoryFake.Verify(a => a.CreateAnEmptyActionResultWithRedirectionToCallBackUrl());
            Assert.True(result.RedirectInstruction.ResponseMode == ResponseMode.query);
        }
        public async Task When_Validating_Authorization_Parameter_With_NoneLoginPromptParameter_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string state = "state";
            var          authorizationParameter = new AuthorizationParameter
            {
                State        = state,
                Scope        = "scope",
                ClientId     = "clientId",
                RedirectUrl  = "redirectUrl",
                ResponseType = "code",
                Prompt       = "none login"
            };

            _parameterParserHelperFake.Setup(p => p.ParsePrompts(It.IsAny <string>()))
            .Returns(new List <PromptParameter>
            {
                PromptParameter.none,
                PromptParameter.login
            });

            // ACT & ASSERT
            var exception = await Assert.ThrowsAsync <IdentityServerExceptionWithState>(
                () => _authorizationCodeGrantTypeParameterAuthEdpValidator.ValidateAsync(authorizationParameter));

            Assert.True(exception.Code == ErrorCodes.InvalidRequestCode);
            Assert.True(exception.Message == ErrorDescriptions.PromptParameterShouldHaveOnlyNoneValue);
            Assert.True(exception.State == state);
        }
Example #22
0
        private async Task FillInResourceOwnerClaimsFromScopes(
            JwsPayload jwsPayload,
            AuthorizationParameter authorizationParameter,
            ClaimsPrincipal claimsPrincipal)
        {
            // 1. Fill-in the subject claim
            var subject = claimsPrincipal.GetSubject();

            jwsPayload.Add(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, subject);

            if (authorizationParameter == null ||
                string.IsNullOrWhiteSpace(authorizationParameter.Scope))
            {
                return;
            }

            // 2. Fill-in the other claims
            var scopes = _parameterParserHelper.ParseScopes(authorizationParameter.Scope);
            var claims = await GetClaimsFromRequestedScopes(scopes, claimsPrincipal);

            foreach (var claim in claims)
            {
                if (claim.Key == Jwt.Constants.StandardResourceOwnerClaimNames.Subject)
                {
                    continue;
                }

                jwsPayload.Add(claim.Key, claim.Value);
            }
        }
        public async Task When_Validating_Authorization_Parameter_With_RedirectUri_Not_Known_By_The_Client_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string state                  = "state";
            const string clientId               = "clientId";
            const string redirectUri            = "http://localhost";
            var          authorizationParameter = new AuthorizationParameter
            {
                State        = state,
                Scope        = "scope",
                ClientId     = clientId,
                RedirectUrl  = redirectUri,
                ResponseType = "code",
                Prompt       = "none"
            };
            var client = new Models.Client();

            _parameterParserHelperFake.Setup(p => p.ParsePrompts(It.IsAny <string>()))
            .Returns(new List <PromptParameter>
            {
                PromptParameter.none
            });
            _clientRepository.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(client));
            _clientValidatorFake.Setup(c => c.GetRedirectionUrls(It.IsAny <Models.Client>(), It.IsAny <string[]>()))
            .Returns(() => new string[0]);

            // ACT & ASSERT
            var exception = await Assert.ThrowsAsync <IdentityServerExceptionWithState>(() => _authorizationCodeGrantTypeParameterAuthEdpValidator.ValidateAsync(authorizationParameter));

            Assert.True(exception.Code == ErrorCodes.InvalidRequestCode);
            Assert.True(exception.Message == string.Format(ErrorDescriptions.RedirectUrlIsNotValid, redirectUri));
            Assert.True(exception.State == state);
        }
        public async Task When_Requesting_Authorization_With_Valid_Request_Then_ReturnsRedirectInstruction()
        {
            const string clientId = "clientId";
            const string scope    = "openid";
            var          authorizationParameter = new AuthorizationParameter
            {
                ResponseType = ResponseTypeNames.Token,
                State        = "state",
                Nonce        = "nonce",
                ClientId     = clientId,
                Scope        = scope,
                Claims       = null,
                RedirectUrl  = new Uri("https://localhost")
            };

            var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim("sub", "test") }, "fake"));

            var client = new Client
            {
                ResponseTypes   = ResponseTypeNames.All,
                RedirectionUrls = new[] { new Uri("https://localhost"), },
                GrantTypes      = new[] { GrantTypes.Implicit },
                AllowedScopes   = new[] { "openid" }
            };
            var result = await _getTokenViaImplicitWorkflowOperation.Execute(
                authorizationParameter,
                claimsPrincipal,
                client,
                null,
                CancellationToken.None)
                         .ConfigureAwait(false);

            Assert.NotNull(result.RedirectInstruction);
        }
Example #25
0
        public async Task When_Requesting_IdentityToken_JwsPayload_And_ThereNoClient_Then_Azp_Should_Be_Returned()
        {
            // ARRANGE
            InitializeMockObjects();
            const string issuerName = "IssuerName";
            const string clientId   = "clientId";
            const string subject    = "*****@*****.**";
            var          claims     = new List <Claim>
            {
                new Claim(Constants.StandardResourceOwnerClaimNames.Subject, subject)
            };
            var authorizationParameter = new AuthorizationParameter
            {
                ClientId = clientId
            };

            _clientRepositoryStub.Setup(c => c.GetAllAsync()).Returns(Task.FromResult((IEnumerable <Client>) new List <Client>()));

            // ACT
            var result = await _jwtGenerator.GenerateIdTokenPayloadForScopesAsync(claims, authorizationParameter, issuerName);

            // ASSERT
            Assert.NotNull(result);
            Assert.True(result.ContainsKey(Constants.StandardResourceOwnerClaimNames.Subject));
            Assert.True(result.Audiences.Count() == 1);
            Assert.True(result.Azp == clientId);
        }
        public async Task WhenTheClientGrantTypeIsNotSupportedThenAnErrorIsReturned()
        {
            const string clientId = "clientId";
            const string scope    = "scope";
            var          authorizationParameter = new AuthorizationParameter
            {
                ResponseType = ResponseTypeNames.Code,
                RedirectUrl  = new Uri(HttpsLocalhost),
                ClientId     = clientId,
                Scope        = scope,
                Claims       = new ClaimsParameter()
            };

            var client = new Client
            {
                GrantTypes      = new[] { GrantTypes.ClientCredentials },
                AllowedScopes   = new[] { scope },
                RedirectionUrls = new[] { new Uri(HttpsLocalhost), }
            };
            var result = await _getAuthorizationCodeOperation.Execute(
                authorizationParameter,
                new ClaimsPrincipal(),
                client,
                "",
                CancellationToken.None)
                         .ConfigureAwait(false);

            Assert.NotNull(result);
            Assert.Equal(ErrorCodes.InvalidRequest, result.Error !.Title);
            Assert.Equal(
                string.Format(Strings.TheClientDoesntSupportTheGrantType, clientId, "authorization_code"),
                result.Error.Detail);
        }
Example #27
0
        public async Task When_Requesting_UserInformation_JwsPayload_For_Scopes_Then_The_JwsPayload_Is_Correct()
        {
            // ARRANGE
            InitializeMockObjects();
            const string subject = "*****@*****.**";
            const string name    = "Habart Thierry";
            var          claims  = new List <Claim>
            {
                new Claim(Constants.StandardResourceOwnerClaimNames.Name, name),
                new Claim(Constants.StandardResourceOwnerClaimNames.Subject, subject)
            };
            var authorizationParameter = new AuthorizationParameter
            {
                Scope = "profile"
            };
            ICollection <Scope> scopes = FakeOpenIdAssets.GetScopes().Where(s => s.Name == "profile").ToList();

            _clientRepositoryStub.Setup(c => c.GetAllAsync()).Returns(Task.FromResult(FakeOpenIdAssets.GetClients()));
            _scopeRepositoryStub.Setup(s => s.SearchByNamesAsync(It.IsAny <IEnumerable <string> >()))
            .Returns(Task.FromResult(scopes));

            // ACT
            var result = await _jwtGenerator.GenerateUserInfoPayloadForScopeAsync(authorizationParameter, claims);

            // ASSERT
            Assert.NotNull(result);
            Assert.True(result.ContainsKey(Constants.StandardResourceOwnerClaimNames.Subject));
            Assert.True(result.ContainsKey(Constants.StandardResourceOwnerClaimNames.Name));
            Assert.True(result[Constants.StandardResourceOwnerClaimNames.Subject].ToString().Equals(subject));
            Assert.True(result[Constants.StandardResourceOwnerClaimNames.Name].ToString().Equals(name));
        }
        public async Task When_Passing_Valid_Request_Then_ReturnsRedirectInstruction()
        {
            const string clientId = "clientId";
            const string scope    = "scope";

            var client = new Client
            {
                ResponseTypes   = new[] { ResponseTypeNames.Code },
                AllowedScopes   = new[] { scope },
                RedirectionUrls = new[] { new Uri(HttpsLocalhost), }
            };
            var authorizationParameter = new AuthorizationParameter
            {
                ResponseType = ResponseTypeNames.Code,
                RedirectUrl  = new Uri(HttpsLocalhost),
                ClientId     = clientId,
                Scope        = scope,
                Claims       = null
            };

            var result = await _getAuthorizationCodeOperation
                         .Execute(authorizationParameter, new ClaimsPrincipal(), client, null, CancellationToken.None)
                         .ConfigureAwait(false);

            Assert.NotNull(result.RedirectInstruction);
        }
        When_Redirecting_To_Callback_And_There_Is_No_Response_Mode_Specified_Then_The_Response_Mode_Is_Set()
        {
            //const string idToken = "idToken";
            const string clientId               = "clientId";
            const string scope                  = "scope";
            const string responseType           = "id_token";
            var          claimsPrincipal        = new ClaimsPrincipal(new ClaimsIdentity("fake"));
            var          authorizationParameter = new AuthorizationParameter
            {
                ClientId     = clientId,
                Scope        = scope,
                ResponseType = responseType,
                ResponseMode = ResponseModes.None
            };

            var actionResult = await _generateAuthorizationResponse.Generate(
                new EndpointResult
            {
                RedirectInstruction = new RedirectInstruction(),
                Type = ActionResultType.RedirectToCallBackUrl
            },
                authorizationParameter,
                claimsPrincipal,
                new Client(),
                null,
                CancellationToken.None)
                               .ConfigureAwait(false);

            Assert.Equal(ResponseModes.Fragment, actionResult.RedirectInstruction !.ResponseMode);
        }
Example #30
0
        When_Validating_Authorization_Parameter_With_NoneLoginPromptParameter_Then_Exception_Is_Thrown()
        {
            const string state = "state";
            var          authorizationParameter = new AuthorizationParameter
            {
                State        = state,
                Scope        = "scope",
                ClientId     = "clientId",
                RedirectUrl  = new Uri("https://redirectUrl"),
                ResponseType = "code",
                Prompt       = "none login"
            };

            var exception = await _authorizationCodeGrantTypeParameterAuthEdpValidator.Validate(
                authorizationParameter,
                CancellationToken.None)
                            .ConfigureAwait(false);

            Assert.Equal(
                new Option <Client> .Error(
                    new ErrorDetails
            {
                Title = ErrorCodes.InvalidRequest, Detail = Strings.PromptParameterShouldHaveOnlyNoneValue
            },
                    state),
                exception);
        }