Exemple #1
0
        public async Task CreateClient(IdentityServer4.Models.Client client)
        {
            var newData = client.ToEntity();
            await repoWrapper.Clients.Add(newData).ConfigureAwait(false);

            repoWrapper.Save();
        }
        public void Properties_Map()
        {
            var model = new Client()
            {
                Properties =
                {
                    { "foo1", "bar1" },
                    { "foo2", "bar2" },
                }
            };

            var mappedEntity = model.ToEntity();

            mappedEntity.Properties.Count.Should().Be(2);

            var foo1 = mappedEntity.Properties
                       .FirstOrDefault(x => x.Key == "foo1");

            foo1.Should().NotBeNull();
            foo1.Value.Should().Be("bar1");

            var foo2 = mappedEntity.Properties
                       .FirstOrDefault(x => x.Key == "foo2");

            foo2.Should().NotBeNull();
            foo2.Value.Should().Be("bar2");

            var mappedModel = mappedEntity.ToModel();

            mappedModel.Properties.Count.Should().Be(2);
            mappedModel.Properties.ContainsKey("foo1").Should().BeTrue();
            mappedModel.Properties.ContainsKey("foo2").Should().BeTrue();
            mappedModel.Properties["foo1"].Should().Be("bar1");
            mappedModel.Properties["foo2"].Should().Be("bar2");
        }
Exemple #3
0
        public void UpdateClient(IdentityServer4.Models.Client client)
        {
            var dbEntity = client.ToEntity();

            repoWrapper.Clients.Update(dbEntity);
            repoWrapper.Save();
        }
        public IActionResult UpdateClient(IdentityServer4.Models.Client model)
        {
            try
            {
                var client = _clientRepository.Get(x => x.ClientId == model.ClientId).FirstOrDefault();

                if (client == null)
                {
                    return(new OkObjectResult(BaseModel.Error("No client exist with the Id " + model.ClientId)));
                }


                var entity = model.ToEntity();

                client.AllowedGrantTypes = entity.AllowedGrantTypes;
                client.AllowedScopes     = entity.AllowedScopes;
                client.AlwaysIncludeUserClaimsInIdToken = entity.AlwaysIncludeUserClaimsInIdToken;
                client.Enabled = entity.Enabled;
                client.AlwaysSendClientClaims = entity.AlwaysSendClientClaims;
                client.AccessTokenLifetime    = entity.AccessTokenLifetime;
                client.IdentityTokenLifetime  = entity.IdentityTokenLifetime;
                client.AllowOfflineAccess     = entity.AllowOfflineAccess;

                _clientRepository.Update(client);

                return(new OkObjectResult(BaseModel.Success("Client Added Successfully.")));
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult(BaseModel.Error("Operation failed, please try again.")));
            }
        }
Exemple #5
0
        public void Update(Client obj)
        {
            var client = DbSet.FirstOrDefault(w => w.ClientId == obj.ClientId);
            var newOne = obj.ToEntity();

            newOne.Id = client.Id;
            DbSet.Update(newOne);
        }
Exemple #6
0
        public async Task UpdateWithChildrens(string oldClientId, Client client)
        {
            var newClient = client.ToEntity();
            var clientDb  = await GetFullClient(oldClientId);

            newClient.Id = clientDb.Id;
            newClient.ShallowCopyTo(clientDb);
        }
Exemple #7
0
        public void Can_Map()
        {
            var model        = new Client();
            var mappedEntity = model.ToEntity();
            var mappedModel  = mappedEntity.ToModel();

            Assert.NotNull(mappedModel);
            Assert.NotNull(mappedEntity);
        }
        public async Task <Client> AddClientAsync(Client client)
        {
            var clientEntity = client.ToEntity();
            var entityEntry  = await context.Clients.AddAsync(clientEntity);

            await context.SaveChangesAsync();

            return(entityEntry.Entity?.ToModel());
        }
        public void ClientAutomapperConfigurationIsValid()
        {
            var model        = new Client();
            var mappedEntity = model.ToEntity();
            var mappedModel  = mappedEntity.ToModel();

            Assert.NotNull(mappedModel);
            Assert.NotNull(mappedEntity);
            ClientMapper.Mapper.ConfigurationProvider.AssertConfigurationIsValid();
        }
Exemple #10
0
        public void ClientModelToEntityConfigurationIsValid()
        {
            var model = new IdentityServer4.Models.Client();

            // TODO: set references

            var mappedEntity = model.ToEntity();
            var mappedModel  = mappedEntity.ToModel();

            Assert.NotNull(mappedModel);
            Assert.NotNull(mappedEntity);
            ClientMappers.Mapper.ConfigurationProvider.AssertConfigurationIsValid();
        }
Exemple #11
0
 public void DeleteClient(IdentityServer4.Models.Client client)
 {
     repoWrapper.Clients.Remove(client.ToEntity());
     repoWrapper.Save();
 }
Exemple #12
0
        public async Task <IActionResult> CreateAsync([FromBody] CreateClientDto dto)
        {
            if (await _dbContext.Clients.AnyAsync(u => u.ClientId == dto.ClientId))
            {
                return(new ApiResult(ApiResultType.Error, "资源名已经存在"));
            }

            var redirectUris = dto.RedirectUris.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries)
                               .Where(cors => !string.IsNullOrWhiteSpace(cors) && cors.IsUrl()).ToList();

            if (redirectUris.Count == 0)
            {
                return(new ApiResult(ApiResultType.Error, "回调地址不能为空"));
            }

            var allowedCorsOrigins = dto.AllowedCorsOrigins.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries)
                                     .Where(cors => !string.IsNullOrWhiteSpace(cors) && cors.IsUrl()).ToList();

            if (allowedCorsOrigins.Count == 0)
            {
                return(new ApiResult(ApiResultType.Error, "授权范围不能为空"));
            }

            var client = new IdentityServer4.Models.Client();

            switch (dto.AllowedGrantTypes)
            {
            case GrantTypes.Code:
            {
                client.AllowedGrantTypes = Models.GrantTypes.Code;
                break;
            }

            case GrantTypes.Hybrid:
            {
                client.AllowedGrantTypes = Models.GrantTypes.Hybrid;
                break;
            }

            case GrantTypes.Implicit:
            {
                client.AllowedGrantTypes = Models.GrantTypes.Implicit;
                break;
            }

            case GrantTypes.ClientCredentials:
            {
                client.AllowedGrantTypes = Models.GrantTypes.ClientCredentials;
                break;
            }

            case GrantTypes.DeviceFlow:
            {
                client.AllowedGrantTypes = Models.GrantTypes.DeviceFlow;
                break;
            }

            case GrantTypes.ResourceOwnerPassword:
            {
                client.AllowedGrantTypes = Models.GrantTypes.ResourceOwnerPassword;
                break;
            }

            case GrantTypes.CodeAndClientCredentials:
            {
                client.AllowedGrantTypes = Models.GrantTypes.CodeAndClientCredentials;
                break;
            }

            case GrantTypes.HybridAndClientCredentials:
            {
                client.AllowedGrantTypes = Models.GrantTypes.HybridAndClientCredentials;
                break;
            }

            case GrantTypes.ImplicitAndClientCredentials:
            {
                client.AllowedGrantTypes = Models.GrantTypes.ImplicitAndClientCredentials;
                break;
            }

            case GrantTypes.ResourceOwnerPasswordAndClientCredentials:
            {
                client.AllowedGrantTypes = Models.GrantTypes.ResourceOwnerPasswordAndClientCredentials;
                break;
            }
            }

            client.Description   = dto.Description;
            client.Properties    = dto.Properties;
            client.AllowedScopes = dto.AllowedScopes.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                                   .Where(cors => !string.IsNullOrWhiteSpace(cors)).ToList();
            client.ClientId                     = dto.ClientId;
            client.ClientName                   = dto.ClientName;
            client.ClientUri                    = dto.ClientUri;
            client.ConsentLifetime              = dto.ConsentLifetime;
            client.LogoUri                      = dto.LogoUri;
            client.ProtocolType                 = dto.ProtocolType;
            client.RedirectUris                 = redirectUris;
            client.RequireConsent               = dto.RequireConsent;
            client.RequirePkce                  = dto.RequirePkce;
            client.AccessTokenLifetime          = dto.AccessTokenLifetime;
            client.AccessTokenType              = dto.AccessTokenType;
            client.AllowedCorsOrigins           = allowedCorsOrigins;
            client.AllowOfflineAccess           = dto.AllowOfflineAccess;
            client.AllowRememberConsent         = dto.AllowRememberConsent;
            client.AuthorizationCodeLifetime    = dto.AuthorizationCodeLifetime;
            client.ClientClaimsPrefix           = dto.ClientClaimsPrefix;
            client.DeviceCodeLifetime           = dto.DeviceCodeLifetime;
            client.EnableLocalLogin             = dto.EnableLocalLogin;
            client.IdentityProviderRestrictions = dto.IdentityProviderRestrictions;
            client.IdentityTokenLifetime        = dto.IdentityTokenLifetime;
            client.IncludeJwtId                 = dto.IncludeJwtId;
            client.RefreshTokenExpiration       = dto.RefreshTokenExpiration;
            client.RefreshTokenUsage            = dto.RefreshTokenUsage;
            client.RequireClientSecret          = dto.RequireClientSecret;
            client.UserCodeType                 = dto.UserCodeType;
            client.UserSsoLifetime              = dto.UserSsoLifetime;
            client.AbsoluteRefreshTokenLifetime = dto.AbsoluteRefreshTokenLifetime;
            client.AllowPlainTextPkce           = dto.AllowPlainTextPkce;
            client.AlwaysSendClientClaims       = dto.AlwaysSendClientClaims;
            client.BackChannelLogoutUri         = dto.BackChannelLogoutUri;
            client.FrontChannelLogoutUri        = dto.FrontChannelLogoutUri;
            client.PairWiseSubjectSalt          = dto.PairWiseSubjectSalt;
            client.PostLogoutRedirectUris       = dto.PostLogoutRedirectUris
                                                  .Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries)
                                                  .Where(cors => !string.IsNullOrWhiteSpace(cors) && cors.IsUrl()).ToList();
            client.SlidingRefreshTokenLifetime       = dto.SlidingRefreshTokenLifetime;
            client.AllowAccessTokensViaBrowser       = dto.AllowAccessTokensViaBrowser;
            client.BackChannelLogoutSessionRequired  = dto.BackChannelLogoutSessionRequired;
            client.FrontChannelLogoutSessionRequired = dto.FrontChannelLogoutSessionRequired;
            client.UpdateAccessTokenClaimsOnRefresh  = dto.UpdateAccessTokenClaimsOnRefresh;
            client.AlwaysIncludeUserClaimsInIdToken  = dto.AlwaysIncludeUserClaimsInIdToken;


            await _dbContext.Clients.AddAsync(client.ToEntity());

            await _dbContext.SaveChangesAsync();

            return(ApiResult.Ok);
        }
Exemple #13
0
 public async Task AddClient(IdentityServer4.Models.Client entity)
 {
     await _configurationDbContext.Clients.AddAsync(entity.ToEntity());
 }
Exemple #14
0
 public void Add(Client obj)
 {
     DbSet.Add(obj.ToEntity());
 }
Exemple #15
0
        /// <summary>
        /// 添加或者更新客户端
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task <Result> CreateOrUpdateClientAsync(ClientDto dto)
        {
            //if(!GetExampleGrantTypes().Any(e=>e.GrantType == dto.AllowedGrantTypes))
            //{
            //    return Failed($"无效的grantType【{dto.AllowedGrantTypes}】");
            //}


            IdentityServer4.Models.Client model = mapper.Map <IdentityServer4.Models.Client>(dto);
            var entity = model.ToEntity();

            if (!dto.Id.HasValue || dto.Id == 0)
            {
                //创建
                await configurationDbContext.Clients.AddAsync(entity).ConfigureAwait(false);
            }
            else
            {
                entity.Id = dto.Id.Value;

                Client client = await Clients.FirstOrDefaultAsync(e => e.Id == dto.Id).ConfigureAwait(false);

                if (client == null)
                {
                    return(FailedResult($"客户端[{dto.ClientId}]不存在"));
                }


                client = mapper.Map(entity, client);
            }

            try
            {
                int row = await configurationDbContext.SaveChangesAsync().ConfigureAwait(false);

                if (row > 0)
                {
                    return(OkResult());
                }

                return(FailedResult("已执行,但未更新数据"));
            }
            catch (DbUpdateException ex)
            {
                return(FailedResult(ex));
            }

            //如果Id有值,先删除
            //if (dto.Id.HasValue && dto.Id > 0)
            //{
            //    //先删除
            //    var existClient = await configurationDbContext.Clients.FirstOrDefaultAsync(e => e.ClientId == dto.ClientId).ConfigureAwait(false);
            //    if (existClient != null)
            //    {
            //        configurationDbContext.Clients.Remove(existClient);
            //    }
            //}


            //IdentityServer4.Models.Client client = new IdentityServer4.Models.Client
            //{
            //    ClientName = dto.ClientName,
            //    Description = dto.Description,
            //    ClientId = dto.ClientId,
            //    Enabled = true,
            //    RequireClientSecret = false,//不需要密码
            //    AllowOfflineAccess = true, //允许离线访问
            //    AllowAccessTokensViaBrowser = true,  //允许令牌通过浏览器

            //    AlwaysSendClientClaims = true,//允许发送客户端声明
            //    AlwaysIncludeUserClaimsInIdToken = false, //允许userClaims 包含在 token 中

            //    //授权确认同意页面,false则跳过
            //    RequireConsent = dto.RequireConsent,

            //    RequirePkce = false,

            //    RedirectUris = dto.RedirectUris.Split(';')?.ToList(), //登录后重定位路径
            //    PostLogoutRedirectUris = dto.PostLogoutRedirectUris.Split(';')?.ToList(), //后端注销url
            //    FrontChannelLogoutUri = dto.FrontChannelLogoutUri,  //前端频道注销uri

            //    AllowedGrantTypes = IdentityServer4.Models.GrantTypes.Implicit, //添加简化模式授权

            //    AllowedScopes = dto.Scopes.Split(';')?.ToList()   //添加允许的作用域
            //};
            //var entity = client.ToEntity();
            //await configurationDbContext.Clients.AddAsync(entity).ConfigureAwait(false);

            //DataResult<int?> result = new DataResult<int?>();

            //try
            //{
            //    var row = await configurationDbContext.SaveChangesAsync().ConfigureAwait(false);
            //    if (row > 0)
            //    {
            //        var id = (await configurationDbContext.Clients.FirstOrDefaultAsync(e => e.ClientId == dto.ClientId).ConfigureAwait(false))?.Id;
            //        result.Succeeded = true;
            //        result.Data = id;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    result.ErrorMessage = ex.InnerException?.Message ?? ex.Message;
            //}

            //return result;
        }