public async Task When_An_Exception_Is_Raised_While_Attempting_To_Create_A_Client_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            const string clientId = "client_id";
            const string code     = "code";
            const string message  = "message";
            var          client   = new SimpleIdentityServer.Core.Common.Models.Client
            {
                ClientId = clientId
            };
            var parameter = new UpdateClientParameter
            {
                ClientId = clientId
            };

            InitializeFakeObjects();
            _clientRepositoryStub.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(client));
            _generateClientFromRegistrationRequestStub.Setup(g => g.Execute(It.IsAny <UpdateClientParameter>()))
            .Callback(() =>
            {
                throw new IdentityServerException(code, message);
            });

            // ACT
            var exception = await Assert.ThrowsAsync <IdentityServerManagerException>(() => _updateClientAction.Execute(parameter));

            // ASSERTS
            Assert.True(exception.Code == code);
            Assert.True(exception.Message == message);
        }
Esempio n. 2
0
        public async Task <bool> Execute(UpdateClientParameter updateClientParameter)
        {
            if (updateClientParameter == null)
            {
                throw new ArgumentNullException(nameof(updateClientParameter));
            }

            if (string.IsNullOrWhiteSpace(updateClientParameter.ClientId))
            {
                throw new IdentityServerManagerException(ErrorCodes.InvalidParameterCode, string.Format(ErrorDescriptions.MissingParameter, "client_id"));
            }

            _managerEventSource.StartToUpdateClient(JsonConvert.SerializeObject(updateClientParameter));
            var existedClient = await _clientRepository.GetClientByIdAsync(updateClientParameter.ClientId);

            if (existedClient == null)
            {
                throw new IdentityServerManagerException(ErrorCodes.InvalidParameterCode, string.Format(ErrorDescriptions.TheClientDoesntExist, updateClientParameter.ClientId));
            }

            SimpleIdentityServer.Core.Common.Models.Client client = null;
            try
            {
                client = _generateClientFromRegistrationRequest.Execute(updateClientParameter);
            }
            catch (IdentityServerException ex)
            {
                throw new IdentityServerManagerException(ex.Code, ex.Message);
            }

            client.ClientId      = existedClient.ClientId;
            client.AllowedScopes = updateClientParameter.AllowedScopes == null
                ? new List <Scope>()
                : updateClientParameter.AllowedScopes.Select(s => new Scope
            {
                Name = s
            }).ToList();
            var existingScopes = await _scopeRepository.SearchByNamesAsync(client.AllowedScopes.Select(s => s.Name));

            var notSupportedScopes = client.AllowedScopes.Where(s => !existingScopes.Any(sc => sc.Name == s.Name)).Select(s => s.Name);

            if (notSupportedScopes.Any())
            {
                throw new IdentityServerManagerException(ErrorCodes.InvalidParameterCode, string.Format(ErrorDescriptions.TheScopesDontExist, string.Join(",", notSupportedScopes)));
            }

            var result = await _clientRepository.UpdateAsync(client);

            if (!result)
            {
                throw new IdentityServerManagerException(ErrorCodes.InternalErrorCode, ErrorDescriptions.TheClientCannotBeUpdated);
            }

            _managerEventSource.FinishToUpdateClient(JsonConvert.SerializeObject(updateClientParameter));
            return(result);
        }
        public static ClientResponse ToDto(this SimpleIdentityServer.Core.Common.Models.Client client)
        {
            IEnumerable <ResponseClientSecret> secrets = null;

            if (client.Secrets != null)
            {
                secrets = client.Secrets.Select(s => s.ToDto());
            }

            return(new ClientResponse
            {
                AllowedScopes = client.AllowedScopes == null ? new List <string>() : client.AllowedScopes.Select(c => c.Name).ToList(),
                ApplicationType = Enum.GetName(typeof(ApplicationTypes), client.ApplicationType),
                ClientId = client.ClientId,
                ClientName = client.ClientName,
                Secrets = secrets,
                ClientUri = client.ClientUri,
                Contacts = client.Contacts,
                DefaultAcrValues = client.DefaultAcrValues,
                DefaultMaxAge = client.DefaultMaxAge,
                GrantTypes = client.GrantTypes == null ? new List <string>() : client.GrantTypes.Select(g => Enum.GetName(typeof(GrantType), g)).ToList(),
                IdTokenEncryptedResponseAlg = client.IdTokenEncryptedResponseAlg,
                IdTokenEncryptedResponseEnc = client.IdTokenEncryptedResponseEnc,
                IdTokenSignedResponseAlg = client.IdTokenSignedResponseAlg,
                InitiateLoginUri = client.InitiateLoginUri,
                JsonWebKeys = client.JsonWebKeys,
                JwksUri = client.JwksUri,
                LogoUri = client.LogoUri,
                PolicyUri = client.PolicyUri,
                RedirectUris = client.RedirectionUrls,
                RequestObjectEncryptionAlg = client.RequestObjectEncryptionAlg,
                RequestObjectEncryptionEnc = client.RequestObjectEncryptionEnc,
                RequestObjectSigningAlg = client.RequestObjectSigningAlg,
                RequestUris = client.RequestUris,
                RequireAuthTime = client.RequireAuthTime,
                ResponseTypes = client.ResponseTypes == null ? new List <string>() : client.ResponseTypes.Select(g => Enum.GetName(typeof(ResponseType), g)).ToList(),
                SectorIdentifierUri = client.SectorIdentifierUri,
                SubjectType = client.SubjectType,
                TokenEndPointAuthMethod = Enum.GetName(typeof(TokenEndPointAuthenticationMethods), client.TokenEndPointAuthMethod),
                TokenEndPointAuthSigningAlg = client.TokenEndPointAuthSigningAlg,
                UserInfoEncryptedResponseAlg = client.UserInfoEncryptedResponseAlg,
                UserInfoEncryptedResponseEnc = client.UserInfoEncryptedResponseEnc,
                UserInfoSignedResponseAlg = client.UserInfoSignedResponseAlg,
                TosUri = client.TosUri,
                PostLogoutRedirectUris = client.PostLogoutRedirectUris,
                CreateDateTime = client.CreateDateTime,
                UpdateDateTime = client.UpdateDateTime
            });
        }
Esempio n. 4
0
        public async Task <GrantedToken> GenerateTokenAsync(SimpleIdentityServer.Core.Common.Models.Client client, IEnumerable <TicketLine> ticketLines, string scope, string issuerName)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

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

            if (string.IsNullOrWhiteSpace(scope))
            {
                throw new ArgumentNullException(nameof(scope));
            }

            var expiresIn = await _configurationService.GetRptLifeTime();                                   // 1. Retrieve the expiration time of the granted token.

            var jwsPayload = await _jwtGenerator.GenerateAccessToken(client, scope.Split(' '), issuerName); // 2. Construct the JWT token (client).

            var jArr = new JArray();

            foreach (var ticketLine in ticketLines)
            {
                var jObj = new JObject();
                jObj.Add(Constants.RptClaims.ResourceSetId, ticketLine.ResourceSetId);
                jObj.Add(Constants.RptClaims.Scopes, string.Join(" ", ticketLine.Scopes));
                jArr.Add(jObj);
            }

            jwsPayload.Add(Constants.RptClaims.Ticket, jArr);
            var accessToken = await _clientHelper.GenerateIdTokenAsync(client, jwsPayload);

            var refreshTokenId = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); // 3. Construct the refresh token.

            return(new GrantedToken
            {
                AccessToken = accessToken,
                RefreshToken = Convert.ToBase64String(refreshTokenId),
                ExpiresIn = expiresIn,
                TokenType = SimpleIdentityServer.Core.Constants.StandardTokenTypes.Bearer,
                CreateDateTime = DateTime.UtcNow,
                Scope = scope,
                ClientId = client.ClientId
            });
        }
        public async Task When_Passing_Correct_Parameter_Then_Update_Operation_Is_Called()
        {
            // ARRANGE
            const string clientId = "client_id";
            var          client   = new SimpleIdentityServer.Core.Common.Models.Client
            {
                ClientId = clientId
            };
            var parameter = new UpdateClientParameter
            {
                ClientId      = clientId,
                AllowedScopes = new List <string>
                {
                    "scope"
                }
            };

            InitializeFakeObjects();
            _clientRepositoryStub.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(client));
            _generateClientFromRegistrationRequestStub.Setup(g => g.Execute(It.IsAny <UpdateClientParameter>()))
            .Returns(client);
            _scopeRepositoryStub.Setup(s => s.SearchByNamesAsync(It.IsAny <IEnumerable <string> >())).Returns(Task.FromResult((ICollection <Scope>) new List <Scope>
            {
                new Scope
                {
                    Name = "scope"
                }
            }));
            _clientRepositoryStub.Setup(c => c.UpdateAsync(It.IsAny <SimpleIdentityServer.Core.Common.Models.Client>())).Returns(Task.FromResult(true));

            // ACT
            await _updateClientAction.Execute(parameter);

            // ASSERTS
            _clientRepositoryStub.Verify(c => c.UpdateAsync(client));
        }
        public async Task When_Scope_Are_Not_Supported_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            const string clientId = "client_id";
            var          client   = new SimpleIdentityServer.Core.Common.Models.Client
            {
                ClientId = clientId
            };
            var parameter = new UpdateClientParameter
            {
                ClientId      = clientId,
                AllowedScopes = new List <string>
                {
                    "not_supported_scope"
                }
            };

            InitializeFakeObjects();
            _clientRepositoryStub.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(client));
            _generateClientFromRegistrationRequestStub.Setup(g => g.Execute(It.IsAny <UpdateClientParameter>()))
            .Returns(client);
            _scopeRepositoryStub.Setup(s => s.SearchByNamesAsync(It.IsAny <IEnumerable <string> >())).Returns(Task.FromResult((ICollection <Scope>) new List <Scope>
            {
                new Scope
                {
                    Name = "scope"
                }
            }));

            // ACT
            var exception = await Assert.ThrowsAsync <IdentityServerManagerException>(() => _updateClientAction.Execute(parameter));

            // ASSERTS
            Assert.Equal("invalid_parameter", exception.Code);
            Assert.Equal("the scopes 'not_supported_scope' don't exist", exception.Message);
        }
Esempio n. 7
0
        public Models.Client Execute(RegistrationParameter registrationParameter)
        {
            if (registrationParameter == null)
            {
                throw new ArgumentNullException(nameof(registrationParameter));
            }

            // Validate the parameters
            _registrationParameterValidator.Validate(registrationParameter);
            // Generate the client
            var client = new Models.Client
            {
                RedirectionUrls = registrationParameter.RedirectUris,
                Contacts        = registrationParameter.Contacts,
                // TODO : should support different languages for the client_name
                ClientName          = registrationParameter.ClientName,
                ClientUri           = registrationParameter.ClientUri,
                PolicyUri           = registrationParameter.PolicyUri,
                TosUri              = registrationParameter.TosUri,
                JwksUri             = registrationParameter.JwksUri,
                SectorIdentifierUri = registrationParameter.SectorIdentifierUri,
                // TODO : should support both subject types
                SubjectType      = Constants.SubjectTypeNames.Public,
                DefaultMaxAge    = registrationParameter.DefaultMaxAge,
                DefaultAcrValues = registrationParameter.DefaultAcrValues,
                RequireAuthTime  = registrationParameter.RequireAuthTime,
                InitiateLoginUri = registrationParameter.InitiateLoginUri,
                RequestUris      = registrationParameter.RequestUris,
                LogoUri          = registrationParameter.LogoUri,
                ScimProfile      = registrationParameter.ScimProfile
            };

            // If omitted then the default value is authorization code response type
            if (registrationParameter.ResponseTypes == null ||
                !registrationParameter.ResponseTypes.Any())
            {
                client.ResponseTypes = new List <ResponseType>
                {
                    ResponseType.code
                };
            }
            else
            {
                client.ResponseTypes = registrationParameter.ResponseTypes;
            }

            // If omitted then the default value is authorization code grant type
            if (registrationParameter.GrantTypes == null ||
                !registrationParameter.GrantTypes.Any())
            {
                client.GrantTypes = new List <GrantType>
                {
                    GrantType.authorization_code
                };
            }
            else
            {
                client.GrantTypes = registrationParameter.GrantTypes;
            }

            client.ApplicationType = registrationParameter.ApplicationType == null ? ApplicationTypes.web
                : registrationParameter.ApplicationType.Value;

            if (registrationParameter.Jwks != null)
            {
                var jsonWebKeys = _jsonWebKeyConverter.ExtractSerializedKeys(registrationParameter.Jwks);
                if (jsonWebKeys != null &&
                    jsonWebKeys.Any())
                {
                    client.JsonWebKeys = jsonWebKeys.ToList();
                }
            }

            if (!string.IsNullOrWhiteSpace(registrationParameter.IdTokenSignedResponseAlg) &&
                Constants.Supported.SupportedJwsAlgs.Contains(registrationParameter.IdTokenSignedResponseAlg))
            {
                client.IdTokenSignedResponseAlg = registrationParameter.IdTokenSignedResponseAlg;
            }
            else
            {
                client.IdTokenSignedResponseAlg = Jwt.Constants.JwsAlgNames.RS256;
            }

            if (!string.IsNullOrWhiteSpace(registrationParameter.IdTokenEncryptedResponseAlg) &&
                Constants.Supported.SupportedJweAlgs.Contains(registrationParameter.IdTokenEncryptedResponseAlg))
            {
                client.IdTokenEncryptedResponseAlg = registrationParameter.IdTokenEncryptedResponseAlg;
            }
            else
            {
                client.IdTokenEncryptedResponseAlg = string.Empty;
            }

            if (!string.IsNullOrWhiteSpace(client.IdTokenEncryptedResponseAlg))
            {
                if (!string.IsNullOrWhiteSpace(registrationParameter.IdTokenEncryptedResponseEnc) &&
                    Constants.Supported.SupportedJweEncs.Contains(registrationParameter.IdTokenEncryptedResponseEnc))
                {
                    client.IdTokenEncryptedResponseEnc = registrationParameter.IdTokenEncryptedResponseEnc;
                }
                else
                {
                    client.IdTokenEncryptedResponseEnc = Jwt.Constants.JweEncNames.A128CBC_HS256;
                }
            }

            if (!string.IsNullOrWhiteSpace(registrationParameter.UserInfoSignedResponseAlg) &&
                Constants.Supported.SupportedJwsAlgs.Contains(registrationParameter.UserInfoSignedResponseAlg))
            {
                client.UserInfoSignedResponseAlg = registrationParameter.UserInfoSignedResponseAlg;
            }
            else
            {
                client.UserInfoSignedResponseAlg = Jwt.Constants.JwsAlgNames.NONE;
            }

            if (!string.IsNullOrWhiteSpace(registrationParameter.UserInfoEncryptedResponseAlg) &&
                Constants.Supported.SupportedJweAlgs.Contains(registrationParameter.UserInfoEncryptedResponseAlg))
            {
                client.UserInfoEncryptedResponseAlg = registrationParameter.UserInfoEncryptedResponseAlg;
            }
            else
            {
                client.UserInfoEncryptedResponseAlg = string.Empty;
            }

            if (!string.IsNullOrWhiteSpace(client.UserInfoEncryptedResponseAlg))
            {
                if (!string.IsNullOrWhiteSpace(registrationParameter.UserInfoEncryptedResponseEnc) &&
                    Constants.Supported.SupportedJweEncs.Contains(registrationParameter.UserInfoEncryptedResponseEnc))
                {
                    client.UserInfoEncryptedResponseEnc = registrationParameter.UserInfoEncryptedResponseEnc;
                }
                else
                {
                    client.UserInfoEncryptedResponseEnc = Jwt.Constants.JweEncNames.A128CBC_HS256;
                }
            }

            if (!string.IsNullOrWhiteSpace(registrationParameter.RequestObjectSigningAlg) &&
                Constants.Supported.SupportedJwsAlgs.Contains(registrationParameter.RequestObjectSigningAlg))
            {
                client.RequestObjectSigningAlg = registrationParameter.RequestObjectSigningAlg;
            }
            else
            {
                client.RequestObjectSigningAlg = string.Empty;
            }

            if (!string.IsNullOrWhiteSpace(registrationParameter.RequestObjectEncryptionAlg) &&
                Constants.Supported.SupportedJweAlgs.Contains(registrationParameter.RequestObjectEncryptionAlg))
            {
                client.RequestObjectEncryptionAlg = registrationParameter.RequestObjectEncryptionAlg;
            }
            else
            {
                client.RequestObjectEncryptionAlg = string.Empty;
            }

            if (!string.IsNullOrWhiteSpace(client.RequestObjectEncryptionAlg))
            {
                if (!string.IsNullOrWhiteSpace(registrationParameter.RequestObjectEncryptionEnc) &&
                    Constants.Supported.SupportedJweEncs.Contains(registrationParameter.RequestObjectEncryptionEnc))
                {
                    client.RequestObjectEncryptionEnc = registrationParameter.RequestObjectEncryptionEnc;
                }
                else
                {
                    client.RequestObjectEncryptionEnc = Jwt.Constants.JweEncNames.A128CBC_HS256;
                }
            }

            TokenEndPointAuthenticationMethods tokenEndPointAuthenticationMethod;

            if (string.IsNullOrWhiteSpace(registrationParameter.TokenEndPointAuthMethod) ||
                !Enum.TryParse(registrationParameter.TokenEndPointAuthMethod, out tokenEndPointAuthenticationMethod))
            {
                tokenEndPointAuthenticationMethod = TokenEndPointAuthenticationMethods.client_secret_basic;
            }

            client.TokenEndPointAuthMethod = tokenEndPointAuthenticationMethod;

            if (!string.IsNullOrWhiteSpace(registrationParameter.TokenEndPointAuthSigningAlg) &&
                Constants.Supported.SupportedJwsAlgs.Contains(registrationParameter.TokenEndPointAuthSigningAlg))
            {
                client.TokenEndPointAuthSigningAlg = registrationParameter.TokenEndPointAuthSigningAlg;
            }
            else
            {
                client.TokenEndPointAuthSigningAlg = string.Empty;
            }

            return(client);
        }