Example #1
0
        private void ApplyClientSecrets(IdentityServer4.EntityFramework.Entities.Client client, Oauth2ClientSubmit oauth2ClientSubmit)
        {
            client.ClientSecrets = new List <ClientSecret>();

            if (oauth2ClientSubmit.HashedClientSecrets != null && oauth2ClientSubmit.HashedClientSecrets.Count > 0)
            {
                foreach (var hashedClientSecret in oauth2ClientSubmit.HashedClientSecrets)
                {
                    client.ClientSecrets.Add(new ClientSecret
                    {
                        Client = client,
                        Value  = hashedClientSecret
                    });
                }
            }
            else
            {
                foreach (var clientSecret in oauth2ClientSubmit.ClientSecrets)
                {
                    client.ClientSecrets.Add(new ClientSecret
                    {
                        Client = client,
                        Value  = clientSecret.Sha256()
                    });
                }
            }
        }
Example #2
0
        private async Task RemoveClientRelationsAsync(Client client)
        {
            //Remove old allowed scopes
            var clientScopes = await _dbContext.ClientScopes.Where(x => x.Client.Id == client.Id).ToListAsync();

            _dbContext.ClientScopes.RemoveRange(clientScopes);

            //Remove old grant types
            var clientGrantTypes = await _dbContext.ClientGrantTypes.Where(x => x.Client.Id == client.Id).ToListAsync();

            _dbContext.ClientGrantTypes.RemoveRange(clientGrantTypes);

            //Remove old redirect uri
            var clientRedirectUris = await _dbContext.ClientRedirectUris.Where(x => x.Client.Id == client.Id).ToListAsync();

            _dbContext.ClientRedirectUris.RemoveRange(clientRedirectUris);

            //Remove old client cors
            var clientCorsOrigins = await _dbContext.ClientCorsOrigins.Where(x => x.Client.Id == client.Id).ToListAsync();

            _dbContext.ClientCorsOrigins.RemoveRange(clientCorsOrigins);

            //Remove old client id restrictions
            var clientIdPRestrictions = await _dbContext.ClientIdPRestrictions.Where(x => x.Client.Id == client.Id).ToListAsync();

            _dbContext.ClientIdPRestrictions.RemoveRange(clientIdPRestrictions);

            //Remove old client post logout redirect
            var clientPostLogoutRedirectUris = await _dbContext.ClientPostLogoutRedirectUris.Where(x => x.Client.Id == client.Id).ToListAsync();

            _dbContext.ClientPostLogoutRedirectUris.RemoveRange(clientPostLogoutRedirectUris);
        }
Example #3
0
 public async Task <int> RemoveClientAsync(Client client)
 {
     using (var dbContext = ConnectionDatabase.Get(_configuration))
     {
         return(await dbContext.ExecuteAsync("delete from Clients where Id=@Id;", new { client.Id }));
     }
 }
Example #4
0
        public async Task <ActionResult> CreateCors(int id, ClientUriInputModel model)
        {
            if (ModelState.IsValid)
            {
                IdentityServer4.EntityFramework.Entities.Client client = _context.Clients.Include(x => x.AllowedCorsOrigins).FirstOrDefaultAsync(n => n.Id == model.ClientId).Result;
                if (client == null)
                {
                    TempData["ErrorMessage"] = "Neznámý klient.";
                    return(RedirectToAction(nameof(Index)));
                }
                client.AllowedCorsOrigins.Add(new ClientCorsOrigin
                {
                    ClientId = model.ClientId,
                    Origin   = model.Uri
                });
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Details", new { id = model.ClientId }));
                }
                catch (Exception)
                {
                    TempData["ErrorMessage"] = "Aktualizace klienta se nepodařila.";
                    return(RedirectToAction("Details", new { id = model.ClientId }));
                }
            }
            return(View(model));
        }
Example #5
0
        public async Task Create(ClientDto clientDto)
        {
            ValidateClientDto(clientDto);

            await AddApiResourceIfMissing(clientDto.AllowedScopes);

            var grantType = GetGrantType(clientDto);

            var client = new Client
            {
                ClientId          = clientDto.Username,
                AllowedGrantTypes = new List <ClientGrantType>
                {
                    new ClientGrantType {
                        GrantType = grantType
                    }
                },
                ClientSecrets = new List <ClientSecret>
                {
                    new ClientSecret {
                        Value = clientDto.Password.Sha256()
                    }
                },
                AllowedScopes = clientDto.AllowedScopes.Select(x => new ClientScope {
                    Scope = x.Name
                }).ToList()
            };

            await _clientRepository.Add(client);
        }
        private static ClientDto MapClientEntityToDto(Client client)
        {
            var result = new ClientDto
            {
                Id                  = client.Id,
                ClientId            = client.ClientId,
                Name                = client.ClientName ?? "No Name Assigned",
                Uri                 = client.ClientUri ?? "No Url Assigned",
                RequireConsent      = client.RequireConsent,
                AllowOfflineAccess  = client.AllowOfflineAccess,
                IsEnabled           = client.Enabled,
                ProtocolType        = client.ProtocolType ?? "No Protocol Assigned",
                AccessTokenLifetime = client.AccessTokenLifetime.ToString()
            };

            if (client.ClientSecrets != null)
            {
                result.ClientSecret = new ClientSecretDto
                {
                    Value          = client.ClientSecrets.First().Value,
                    ExpirationDate = client.ClientSecrets.First().Expiration
                };
            }
            if (client.AllowedGrantTypes != null)
            {
                result.AllowedGrantTypes = client.AllowedGrantTypes.Select(clientGrantType => clientGrantType.GrantType)
                                           .ToList();
            }
            return(result);
        }
Example #7
0
        private static void AddOrUpdateClientSecret(Client currentClient, string modelClientSecretDescription)
        {
            // Ensure the client secrets collection is not null
            if (currentClient.ClientSecrets == null)
            {
                currentClient.ClientSecrets = new List <ClientSecret>();
            }

            var currentClientSecret = currentClient.ClientSecrets.FirstOrDefault();

            // Add new secret
            if ((currentClientSecret != null && currentClientSecret.Description != modelClientSecretDescription) ||
                currentClientSecret == null)
            {
                // Remove all secrets as we may have only one valid.
                currentClient.ClientSecrets.Clear();

                currentClient.ClientSecrets.Add(new ClientSecret
                {
                    Client      = currentClient,
                    Value       = modelClientSecretDescription.Sha256(),
                    Type        = IdentityServerConstants.ParsedSecretTypes.SharedSecret,
                    Description = modelClientSecretDescription
                });
            }
        }
Example #8
0
        private void ApplyClientAllowedCorsOrigins(IdentityServer4.EntityFramework.Entities.Client client, Oauth2ClientSubmit oauth2ClientSubmit, bool dryRun, SecurityContractDryRunResult securityContractDryRunResult)
        {
            client.AllowedCorsOrigins = new List <ClientCorsOrigin>();

            if (oauth2ClientSubmit.AllowedCorsOrigins != null && oauth2ClientSubmit.AllowedCorsOrigins.Any())
            {
                foreach (var corsOrigin in oauth2ClientSubmit.AllowedCorsOrigins)
                {
                    if (string.IsNullOrWhiteSpace(corsOrigin))
                    {
                        var errMessage = $"[client.clientId: '{oauth2ClientSubmit.ClientId}']: Empty or null 'allowedCorsOrigin' element declared for client: '{oauth2ClientSubmit.ClientId}'";

                        if (dryRun)
                        {
                            securityContractDryRunResult.ValidationErrors.Add(errMessage);
                        }
                        else
                        {
                            throw new InvalidFormatException(errMessage);
                        }
                    }

                    client.AllowedCorsOrigins.Add(new ClientCorsOrigin
                    {
                        Client = client,
                        Origin = corsOrigin
                    });
                }
            }
        }
Example #9
0
        private static void SetMvcBasedClient(Client client)
        {
            // Ensure the client redirect url collection is not null
            if (client.AllowedGrantTypes == null)
            {
                client.AllowedGrantTypes = new List <ClientGrantType>();
            }

            client.AllowedGrantTypes.Clear();
            client.AllowedGrantTypes = new List <ClientGrantType>
            {
                new ClientGrantType
                {
                    Client    = client,
                    GrantType = OidcConstants.GrantTypes.AuthorizationCode
                },
                new ClientGrantType
                {
                    Client    = client,
                    GrantType = OidcConstants.GrantTypes.RefreshToken
                },
                new ClientGrantType
                {
                    Client    = client,
                    GrantType = OidcConstants.GrantTypes.JwtBearer
                }
            };
        }
Example #10
0
        /// <summary>
        /// Add new client, this method doesn't save client secrets, client claims, client properties
        /// </summary>
        /// <param name="client"></param>
        /// <returns>This method return new client id</returns>
        public async Task <int> AddClientAsync(Client client)
        {
            _dbContext.Clients.Add(client);

            await AutoSaveChangesAsync();

            return(client.Id);
        }
Example #11
0
        public static ClientModel FromEntity(IdentityServer4.EntityFramework.Entities.Client client)
        {
            var config = new MapperConfiguration(cfg => cfg.CreateMap <IdentityServer4.Models.Client, ClientModel>());
            var mapper = config.CreateMapper();
            var model  = mapper.Map <ClientModel>(client.ToModel());

            model.Id = client.Id;
            return(model);
        }
Example #12
0
        public void UpdatePostLogoutRedirectUris(
            IdentityServer4.EntityFramework.Entities.Client client,
            List <string> postLogoutRedirectUris)
        {
            IdentityServer4.Models.Client clientModel = new IdentityServer4.Models.Client();
            clientModel.PostLogoutRedirectUris = postLogoutRedirectUris;

            client.PostLogoutRedirectUris = clientModel.ToEntity().PostLogoutRedirectUris;
        }
Example #13
0
        public virtual async Task <int> UpdateClientAsync(Client client, bool updateClientClaims = false, bool updateClientProperties = false)
        {
            //Remove old relations
            await RemoveClientRelationsAsync(client, updateClientClaims, updateClientProperties);

            //Update with new data
            DbContext.Clients.Update(client);

            return(await AutoSaveChangesAsync());
        }
Example #14
0
        public async Task UpdateClient(Client client)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            _configurationDbContext.Clients.Update(client);
            await _configurationDbContext.SaveChangesAsync();
        }
Example #15
0
        public void UpdateRedirectUris(
            IdentityServer4.EntityFramework.Entities.Client client,
            List <string> redirectUris
            )
        {
            IdentityServer4.Models.Client clientModel = new IdentityServer4.Models.Client();
            clientModel.RedirectUris = redirectUris;

            client.RedirectUris = clientModel.ToEntity().RedirectUris;
        }
Example #16
0
        public void UpdateClient(SharedModels.Client client)
        {
            IdentityServer4.EntityFramework.Entities.Client clientModel = MapBllToDal(client);

            var deleteobj = _applicationClientRepository.GetClientByClientId(clientModel.ClientId);

            _applicationClientRepository.DeleteClient(deleteobj);
            _applicationClientRepository.AddClient(clientModel);
            //_applicationClientRepository.UpdateClient(clientModel);
        }
Example #17
0
        public async Task <int> UpdateClientAsync(Client client)
        {
            //Remove old relations
            await RemoveClientRelationsAsync(client);

            //Update with new data
            _dbContext.Clients.Update(client);

            return(await AutoSaveChangesAsync());
        }
Example #18
0
        public void UpdateAllowedScopes(
            IdentityServer4.EntityFramework.Entities.Client client,
            List <string> allowedScopes
            )
        {
            IdentityServer4.Models.Client clientModel = new IdentityServer4.Models.Client();
            clientModel.AllowedScopes = allowedScopes;

            client.AllowedScopes = clientModel.ToEntity().AllowedScopes;
        }
Example #19
0
 public void AddClient(SharedModels.Client client)
 {
     IdentityServer4.EntityFramework.Entities.Client clientModel = MapBllToDal(client);
     try {
         _applicationClientRepository.AddClient(clientModel);
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Example #20
0
 private async Task RemoveClientRelationsAsync(Client client)
 {
     using (var dbContext = ConnectionDatabase.Get(_configuration))
     {
         await dbContext.ExecuteAsync(@"delete from ClientScopes where ClientId=@Id;
                                        delete from ClientGrantTypes where ClientId=@Id;
                                        delete from ClientRedirectUris where ClientId=@Id;
                                        delete from ClientCorsOrigins where ClientId=@Id;
                                        delete from ClientIdPRestrictions where ClientId=@Id;
                                        delete from ClientPostLogoutRedirectUris where ClientId=@Id;", new { client.Id });
     }
 }
Example #21
0
        public void RemoveClient(
            int id
            )
        {
            IdentityServer4.EntityFramework.Entities.Client client = _repository.FirstOrDefault(id);
            if (client == null)
            {
                throw new Exception("不存在的客户端");
            }

            _repository.Remove(client);
        }
Example #22
0
        public async Task <Oauth2Client> ApplyClientDefinitionAsync(Oauth2ClientSubmit oauth2ClientSubmit, bool dryRun, SecurityContractDryRunResult securityContractDryRunResult)
        {
            logger.Debug($"[client.clientId: '{oauth2ClientSubmit.ClientId}']: Applying client definition for client: '{oauth2ClientSubmit.ClientId}'.");
            IdentityServer4.EntityFramework.Entities.Client client = await identityClientRepository.GetByClientIdAsync(oauth2ClientSubmit.ClientId);

            bool newClient = false;

            if (client == null)
            {
                client    = new IdentityServer4.EntityFramework.Entities.Client();
                newClient = true;
            }

            client.AllowOfflineAccess = oauth2ClientSubmit.AllowedOfflineAccess;
            client.ClientId           = oauth2ClientSubmit.ClientId;
            client.ClientName         = oauth2ClientSubmit.Name;

            // The following properties of clients are not externally configurable, but we do need to add them th clients to get the desired behaviour.
            client.UpdateAccessTokenClaimsOnRefresh = true;
            client.AlwaysSendClientClaims           = true;
            client.AlwaysIncludeUserClaimsInIdToken = true;
            client.RequireConsent = false;

            if (oauth2ClientSubmit.AccessTokenLifetime > 0)
            {
                client.AccessTokenLifetime = oauth2ClientSubmit.AccessTokenLifetime;
            }

            if (oauth2ClientSubmit.IdentityTokenLifetime > 0)
            {
                client.IdentityTokenLifetime = oauth2ClientSubmit.IdentityTokenLifetime;
            }

            client.RefreshTokenExpiration = (int)TokenExpiration.Absolute;
            client.RefreshTokenUsage      = (int)TokenUsage.OneTimeOnly;

            ApplyClientAllowedScopes(client, oauth2ClientSubmit);
            ApplyClientAllowedGrantTypes(client, oauth2ClientSubmit);
            ApplyClientSecrets(client, oauth2ClientSubmit);
            ApplyClientRedirectUris(client, oauth2ClientSubmit);
            ApplyClientPostLogoutRedirectUris(client, oauth2ClientSubmit);
            ApplyClientAllowedCorsOrigins(client, oauth2ClientSubmit, dryRun, securityContractDryRunResult);

            if (newClient)
            {
                logger.Debug($"[client.clientId: '{oauth2ClientSubmit.ClientId}']: Client '{oauth2ClientSubmit.ClientId}' does not exist. Creating it.");
                return(mapper.Map <Oauth2Client>(await identityClientRepository.CreateAsync(client)));
            }

            logger.Debug($"[client.clientId: '{oauth2ClientSubmit.ClientId}']: Client '{oauth2ClientSubmit.ClientId}' already exists. Updating it.");
            return(mapper.Map <Oauth2Client>(await identityClientRepository.UpdateAsync(client)));
        }
Example #23
0
        private void ApplyClientAllowedGrantTypes(IdentityServer4.EntityFramework.Entities.Client client, Oauth2ClientSubmit oauth2ClientSubmit)
        {
            client.AllowedGrantTypes = new List <ClientGrantType>();

            foreach (var grantType in oauth2ClientSubmit.AllowedGrantTypes)
            {
                client.AllowedGrantTypes.Add(new ClientGrantType
                {
                    Client    = client,
                    GrantType = grantType
                });
            }
        }
Example #24
0
        private void ApplyClientRedirectUris(IdentityServer4.EntityFramework.Entities.Client client, Oauth2ClientSubmit oauth2ClientSubmit)
        {
            client.RedirectUris = new List <ClientRedirectUri>();

            foreach (var redirectUri in oauth2ClientSubmit.RedirectUris)
            {
                client.RedirectUris.Add(new ClientRedirectUri
                {
                    Client      = client,
                    RedirectUri = redirectUri
                });
            }
        }
Example #25
0
        private async Task RemoveClientRelationsAsync(Client client, bool updateClientClaims,
                                                      bool updateClientProperties)
        {
            //Remove old allowed scopes
            var clientScopes = await DbContext.ClientScopes.Where(x => x.Client.Id == client.Id).ToListAsync();

            DbContext.ClientScopes.RemoveRange(clientScopes);

            //Remove old grant types
            var clientGrantTypes = await DbContext.ClientGrantTypes.Where(x => x.Client.Id == client.Id).ToListAsync();

            DbContext.ClientGrantTypes.RemoveRange(clientGrantTypes);

            //Remove old redirect uri
            var clientRedirectUris = await DbContext.ClientRedirectUris.Where(x => x.Client.Id == client.Id).ToListAsync();

            DbContext.ClientRedirectUris.RemoveRange(clientRedirectUris);

            //Remove old client cors
            var clientCorsOrigins = await DbContext.ClientCorsOrigins.Where(x => x.Client.Id == client.Id).ToListAsync();

            DbContext.ClientCorsOrigins.RemoveRange(clientCorsOrigins);

            //Remove old client id restrictions
            var clientIdPRestrictions = await DbContext.ClientIdPRestrictions.Where(x => x.Client.Id == client.Id).ToListAsync();

            DbContext.ClientIdPRestrictions.RemoveRange(clientIdPRestrictions);

            //Remove old client post logout redirect
            var clientPostLogoutRedirectUris = await DbContext.ClientPostLogoutRedirectUris.Where(x => x.Client.Id == client.Id).ToListAsync();

            DbContext.ClientPostLogoutRedirectUris.RemoveRange(clientPostLogoutRedirectUris);

            //Remove old client claims
            if (updateClientClaims)
            {
                var clientClaims = await DbContext.ClientClaims.Where(x => x.Client.Id == client.Id).ToListAsync();

                DbContext.ClientClaims.RemoveRange(clientClaims);
            }

            //Remove old client properties
            if (updateClientProperties)
            {
                var clientProperties = await DbContext.ClientProperties.Where(x => x.Client.Id == client.Id).ToListAsync();

                DbContext.ClientProperties.RemoveRange(clientProperties);
            }
        }
Example #26
0
        public async Task <bool> CanInsertClientAsync(Client client, bool isCloned = false)
        {
            if (client.Id == 0 || isCloned)
            {
                var existsWithClientName = await _dbContext.Clients.Where(x => x.ClientId == client.ClientId).SingleOrDefaultAsync();

                return(existsWithClientName == null);
            }
            else
            {
                var existsWithClientName = await _dbContext.Clients.Where(x => x.ClientId == client.ClientId && x.Id != client.Id).SingleOrDefaultAsync();

                return(existsWithClientName == null);
            }
        }
Example #27
0
        public void UpdateSecrets(
            IdentityServer4.EntityFramework.Entities.Client client,
            List <string> clientSecrets
            )
        {
            List <IdentityServer4.Models.Secret> SecretModels = new List <IdentityServer4.Models.Secret>();

            clientSecrets.ForEach(e => {
                SecretModels.Add(new IdentityServer4.Models.Secret(e.Sha256()));
            });

            IdentityServer4.Models.Client clientModel = new IdentityServer4.Models.Client();
            clientModel.ClientSecrets = SecretModels;

            client.ClientSecrets = clientModel.ToEntity().ClientSecrets;
        }
Example #28
0
        public void ApplyClientPostLogoutRedirectUris(IdentityServer4.EntityFramework.Entities.Client client, Oauth2ClientSubmit oauth2ClientSubmit)
        {
            client.PostLogoutRedirectUris = new List <ClientPostLogoutRedirectUri>();

            if (oauth2ClientSubmit.PostLogoutRedirectUris != null && oauth2ClientSubmit.PostLogoutRedirectUris.Any())
            {
                foreach (var postLogoutRedirectUri in oauth2ClientSubmit.PostLogoutRedirectUris)
                {
                    client.PostLogoutRedirectUris.Add(new ClientPostLogoutRedirectUri
                    {
                        Client = client,
                        PostLogoutRedirectUri = postLogoutRedirectUri
                    });
                }
            }
        }
        public async Task <MachineClientCreateCommandResult> Handle(MachineClientCreateCommand request, CancellationToken cancellationToken)
        {
            var client = new IdentityServer4.EntityFramework.Entities.Client()
            {
                ClientId          = Guid.NewGuid().ToString(),
                ClientName        = request.Name,
                AllowedGrantTypes = new List <ClientGrantType>
                {
                    new ClientGrantType
                    {
                        GrantType = IdentityServer4.Models.GrantType.ClientCredentials
                    }
                },
                AllowedScopes = request.AllowedScopes.Select(x => new ClientScope
                {
                    Scope = x
                }).ToList(),
                ClientSecrets = new List <ClientSecret>
                {
                    new ClientSecret
                    {
                        Expiration  = DateTime.UtcNow.AddYears(2),
                        Description = "Example Secret",
                        Value       = "thesecret".Sha256(),
                        Created     = DateTime.UtcNow,
                        Type        = IdentityServerConstants.SecretTypes.SharedSecret
                    }
                },
                RequirePkce         = false,
                RequireClientSecret = true
            };



            await _context.Clients.AddAsync(client, cancellationToken);

            await _context.SaveChangesAsync(cancellationToken);

            return(new MachineClientCreateCommandResult
            {
                ClientId = client.ClientId,
                Name = client.ClientName,
                GrantTypes = client.AllowedGrantTypes.Select(x => x.GrantType).ToList(),
                RedirectUris = client.RedirectUris.Select(x => x.RedirectUri).ToList(),
                Scopes = client.AllowedScopes.Select(x => x.Scope).ToList()
            });
        }
Example #30
0
        public async Task <IActionResult> AddClients(ClientsViewModel args)
        {
            if (ModelState.IsValid)
            {
                var scoper = new List <ClientScope>();
                args.allowed_scopes?.ForEach(x => { scoper.Add(new ClientScope {
                        Scope = x
                    }); });
                var corss = new List <ClientCorsOrigin>();
                args.allowed_cors_origins?.ForEach(x => { corss.Add(new ClientCorsOrigin {
                        Origin = x
                    }); });
                var grants = new  List <ClientGrantType>();
                args.allowed_grant_types?.ForEach(x => { grants.Add(new ClientGrantType {
                        GrantType = x
                    }); });
                var client = new IdentityServer4.EntityFramework.Entities.Client
                {
                    ClientId      = args.client_id,
                    ClientName    = args.client_name,
                    ClientSecrets = new List <ClientSecret> {
                        new ClientSecret {
                            Value = args.client_secrets.Sha256()
                        }
                    },
                    AllowedScopes      = scoper,
                    AllowedCorsOrigins = corss,
                    // RedirectUris = new List<ClientRedirectUri> { new ClientRedirectUri { RedirectUri = args.redirect_uris } },
                    //PostLogoutRedirectUris = new List<ClientPostLogoutRedirectUri> { new ClientPostLogoutRedirectUri { PostLogoutRedirectUri=args.post_logout_redirect_uris} },
                    AllowedGrantTypes = grants
                };
                _context.Clients.Add(client);
                var resutlt = await _context.SaveChangesAsync();

                if (resutlt > 0)
                {
                    return(RedirectToAction("Clients"));
                }
                ModelState.AddModelError(string.Empty, "Client添加失败");
                return(View(args));
            }

            ModelState.AddModelError(string.Empty, "参数验证错误");
            return(RedirectToAction("AddClients"));
        }