Пример #1
0
 private static void SeedClientRestrictions(IAdminStore <Entity.ClientIdpRestriction> clientIdpRestrictionStore, IdentityServer4.Models.Client client)
 {
     foreach (var restriction in client.IdentityProviderRestrictions)
     {
         clientIdpRestrictionStore.CreateAsync(new Entity.ClientIdpRestriction
         {
             ClientId = client.ClientId,
             Id       = Guid.NewGuid().ToString(),
             Provider = restriction
         }).GetAwaiter().GetResult();
     }
 }
Пример #2
0
        private static void SeedClientUris(IAdminStore <Entity.ClientUri> clientUriStore, IdentityServer4.Models.Client client)
        {
            var uris = client.RedirectUris.Select(o => new Entity.ClientUri
            {
                Id       = Guid.NewGuid().ToString(),
                ClientId = client.ClientId,
                Uri      = o
            }).ToList();

            foreach (var origin in client.AllowedCorsOrigins)
            {
                var cors      = new Uri(origin);
                var uri       = uris.FirstOrDefault(u => cors.CorsMatch(u.Uri));
                var corsUri   = new Uri(origin);
                var sanetized = $"{corsUri.Scheme.ToUpperInvariant()}://{corsUri.Host.ToUpperInvariant()}:{corsUri.Port}";

                if (uri == null)
                {
                    uris.Add(new Entity.ClientUri
                    {
                        Id               = Guid.NewGuid().ToString(),
                        ClientId         = client.ClientId,
                        Uri              = origin,
                        Kind             = Entity.UriKinds.Cors,
                        SanetizedCorsUri = sanetized
                    });
                    continue;
                }

                uri.SanetizedCorsUri = sanetized;
                uri.Kind             = Entity.UriKinds.Redirect | Entity.UriKinds.Cors;
            }

            foreach (var postLogout in client.PostLogoutRedirectUris)
            {
                var uri = uris.FirstOrDefault(u => u.Uri == postLogout);
                if (uri == null)
                {
                    uris.Add(new Entity.ClientUri
                    {
                        Id       = Guid.NewGuid().ToString(),
                        ClientId = client.ClientId,
                        Uri      = postLogout,
                        Kind     = Entity.UriKinds.PostLogout
                    });
                    continue;
                }

                uri.Kind |= Entity.UriKinds.Redirect;
            }

            foreach (var uri in uris)
            {
                clientUriStore.CreateAsync(uri).GetAwaiter().GetResult();
            }
        }
Пример #3
0
 private static void SeedClientProperties(IAdminStore <Entity.ClientProperty> clientPropertyStore, IdentityServer4.Models.Client client)
 {
     foreach (var property in client.Properties)
     {
         clientPropertyStore.CreateAsync(new Entity.ClientProperty
         {
             ClientId = client.ClientId,
             Id       = Guid.NewGuid().ToString(),
             Key      = property.Key,
             Value    = property.Value
         }).GetAwaiter().GetResult();
     }
 }
 public UpdateClientCommand(IdentityServer4.Models.Client client, string originalClinetId)
 {
     Client           = client;
     OriginalClinetId = originalClinetId;
 }
Пример #5
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;
        }
Пример #6
0
 public async Task AddClient(IdentityServer4.Models.Client entity)
 {
     await _configurationDbContext.Clients.AddAsync(entity.ToEntity());
 }
Пример #7
0
 public static Entities.Client ToEntity(this IdentityServer4.Models.Client client)
 {
     return(Mapper.Map <Entities.Client>(client));
 }
        private async Task <Client> ConvertToModelAsync(ClientEntity entity)
        {
            var client = new Client
            {
                ClientId                          = entity.ClientId,
                Enabled                           = entity.Enabled,
                ProtocolType                      = entity.ProtocolType,
                RequireClientSecret               = entity.RequireClientSecret,
                ClientName                        = entity.ClientName,
                Description                       = entity.Description,
                ClientUri                         = entity.ClientUri,
                LogoUri                           = entity.LogoUri,
                RequireConsent                    = entity.RequireConsent,
                AllowRememberConsent              = entity.AllowRememberConsent,
                RequirePkce                       = entity.RequirePkce,
                AllowPlainTextPkce                = entity.AllowPlainTextPkce,
                AllowAccessTokensViaBrowser       = entity.AllowAccessTokensViaBrowser,
                FrontChannelLogoutUri             = entity.FrontChannelLogoutUri,
                FrontChannelLogoutSessionRequired = entity.FrontChannelLogoutSessionRequired,
                BackChannelLogoutUri              = entity.BackChannelLogoutUri,
                BackChannelLogoutSessionRequired  = entity.BackChannelLogoutSessionRequired,
                AllowOfflineAccess                = entity.AllowOfflineAccess,
                AlwaysIncludeUserClaimsInIdToken  = entity.AlwaysIncludeUserClaimsInIdToken,
                IdentityTokenLifetime             = entity.IdentityTokenLifetime,
                AccessTokenLifetime               = entity.AccessTokenLifetime,
                AuthorizationCodeLifetime         = entity.AuthorizationCodeLifetime,
                AbsoluteRefreshTokenLifetime      = entity.AbsoluteRefreshTokenLifetime,
                SlidingRefreshTokenLifetime       = entity.SlidingRefreshTokenLifetime,
                ConsentLifetime                   = entity.ConsentLifetime,
                RefreshTokenUsage                 = entity.RefreshTokenUsage,
                UpdateAccessTokenClaimsOnRefresh  = entity.UpdateAccessTokenClaimsOnRefresh,
                RefreshTokenExpiration            = entity.RefreshTokenExpiration,
                AccessTokenType                   = entity.AccessTokenType,
                EnableLocalLogin                  = entity.EnableLocalLogin,
                IncludeJwtId                      = entity.IncludeJwtId,
                AlwaysSendClientClaims            = entity.AlwaysSendClientClaims,
                ClientClaimsPrefix                = entity.ClientClaimsPrefix,
                PairWiseSubjectSalt               = entity.PairWiseSubjectSalt,
                UserSsoLifetime                   = entity.UserSsoLifetime,
                UserCodeType                      = entity.UserCodeType,
                DeviceCodeLifetime                = entity.DeviceCodeLifetime,
            };

            await foreach (var claim in _claims.EnumAsync(entity.ClientId))
            {
                client.Claims.Add(new Claim(claim.Type, claim.Value));
            }

            await foreach (var corsOrigin in _corsOrigins.EnumAsync(client.ClientId))
            {
                client.AllowedCorsOrigins.Add(WebUtility.UrlDecode(corsOrigin.Origin));
            }

            await foreach (var grantType in _grantTypes.EnumAsync(entity.ClientId))
            {
                client.AllowedGrantTypes.Add(grantType.GrantType);
            }

            await foreach (var restriction in _idPRestrictions.EnumAsync(entity.ClientId))
            {
                client.IdentityProviderRestrictions.Add(restriction.Provider);
            }

            await foreach (var redirectUri in _postLogoutRedirectUris.EnumAsync(entity.ClientId))
            {
                client.PostLogoutRedirectUris.Add(WebUtility.UrlDecode(redirectUri.PostLogoutRedirectUri));
            }

            await foreach (var redirectUri in _redirectUris.EnumAsync(entity.ClientId))
            {
                client.RedirectUris.Add(WebUtility.UrlDecode(redirectUri.RedirectUri));
            }

            await foreach (var secret in _secrets.EnumAsync(entity.ClientId))
            {
                client.ClientSecrets.Add(new Secret
                {
                    Description = secret.Description,
                    Expiration  = secret.Expiration,
                    Type        = secret.Type,
                    Value       = secret.Value,
                });
            }

            await foreach (var scope in _scopes.EnumAsync(entity.ClientId))
            {
                client.AllowedScopes.Add(scope.Scope);
            }

            return(client);
        }
        public async Task StoreAsync(Client client)
        {
            await _clients.InsertAsync(new ClientEntity
            {
                ClientId                          = client.ClientId,
                Enabled                           = client.Enabled,
                ProtocolType                      = client.ProtocolType,
                RequireClientSecret               = client.RequireClientSecret,
                ClientName                        = client.ClientName,
                Description                       = client.Description,
                ClientUri                         = client.ClientUri,
                LogoUri                           = client.LogoUri,
                RequireConsent                    = client.RequireConsent,
                AllowRememberConsent              = client.AllowRememberConsent,
                RequirePkce                       = client.RequirePkce,
                AllowPlainTextPkce                = client.AllowPlainTextPkce,
                AllowAccessTokensViaBrowser       = client.AllowAccessTokensViaBrowser,
                FrontChannelLogoutUri             = client.FrontChannelLogoutUri,
                FrontChannelLogoutSessionRequired = client.FrontChannelLogoutSessionRequired,
                BackChannelLogoutUri              = client.BackChannelLogoutUri,
                BackChannelLogoutSessionRequired  = client.BackChannelLogoutSessionRequired,
                AllowOfflineAccess                = client.AllowOfflineAccess,
                AlwaysIncludeUserClaimsInIdToken  = client.AlwaysIncludeUserClaimsInIdToken,
                IdentityTokenLifetime             = client.IdentityTokenLifetime,
                AccessTokenLifetime               = client.AccessTokenLifetime,
                AuthorizationCodeLifetime         = client.AuthorizationCodeLifetime,
                AbsoluteRefreshTokenLifetime      = client.AbsoluteRefreshTokenLifetime,
                SlidingRefreshTokenLifetime       = client.SlidingRefreshTokenLifetime,
                ConsentLifetime                   = client.ConsentLifetime,
                RefreshTokenUsage                 = client.RefreshTokenUsage,
                UpdateAccessTokenClaimsOnRefresh  = client.UpdateAccessTokenClaimsOnRefresh,
                RefreshTokenExpiration            = client.RefreshTokenExpiration,
                AccessTokenType                   = client.AccessTokenType,
                EnableLocalLogin                  = client.EnableLocalLogin,
                IncludeJwtId                      = client.IncludeJwtId,
                AlwaysSendClientClaims            = client.AlwaysSendClientClaims,
                ClientClaimsPrefix                = client.ClientClaimsPrefix,
                PairWiseSubjectSalt               = client.PairWiseSubjectSalt,
                UserSsoLifetime                   = client.UserSsoLifetime,
                UserCodeType                      = client.UserCodeType,
                DeviceCodeLifetime                = client.DeviceCodeLifetime,
            });

            foreach (var claim in client.Claims)
            {
                await _claims.InsertAsync(new ClientClaimEntity
                {
                    ClientId = client.ClientId,
                    Type     = claim.Type,
                    Value    = claim.Value,
                });
            }

            foreach (var corsOrigin in client.AllowedCorsOrigins)
            {
                await _corsOrigins.InsertAsync(new ClientCorsOriginEntity
                {
                    ClientId = client.ClientId,
                    Origin   = WebUtility.UrlEncode(corsOrigin),
                });
            }

            foreach (var grantType in client.AllowedGrantTypes)
            {
                await _grantTypes.InsertAsync(new ClientGrantTypeEntity
                {
                    ClientId  = client.ClientId,
                    GrantType = grantType,
                });
            }

            foreach (var restriction in client.IdentityProviderRestrictions)
            {
                await _idPRestrictions.InsertAsync(new ClientIdPRestrictionEntity
                {
                    ClientId = client.ClientId,
                    Provider = restriction,
                });
            }

            foreach (var redirectUri in client.PostLogoutRedirectUris)
            {
                await _postLogoutRedirectUris.InsertAsync(new ClientPostLogoutRedirectUriEntity
                {
                    ClientId = client.ClientId,
                    PostLogoutRedirectUri = WebUtility.UrlEncode(redirectUri),
                });
            }

            foreach (var redirectUri in client.RedirectUris)
            {
                await _redirectUris.InsertAsync(new ClientRedirectUriEntity
                {
                    ClientId    = client.ClientId,
                    RedirectUri = WebUtility.UrlEncode(redirectUri),
                });
            }

            var secrets = client.ClientSecrets.ToArray();

            for (var index = 0; index < client.ClientSecrets.Count; index++)
            {
                var secret = secrets[index];
                await _secrets.InsertAsync(new ClientSecretEntity
                {
                    ClientId    = client.ClientId,
                    Sequence    = index,
                    Description = secret.Description,
                    Expiration  = secret.Expiration,
                    Type        = secret.Type,
                    Value       = secret.Value,
                });
            }

            foreach (var scope in client.AllowedScopes)
            {
                await _scopes.InsertAsync(new ClientScopeEntity
                {
                    ClientId = client.ClientId,
                    Scope    = scope,
                });
            }
        }
 /// <summary>
 /// Maps a model to an entity.
 /// </summary>
 /// <param name="model">The model.</param>
 /// <returns></returns>
 public static Client ToEntity(this IdentityServer4.Models.Client model)
 {
     return(Mapper.Map <Client>(model));
 }
Пример #11
0
 private static void SeedClientGrantType(IAdminStore <Entity.ClientGrantType> clientGrantTypeStore, IdentityServer4.Models.Client client)
 {
     foreach (var grantType in client.AllowedGrantTypes)
     {
         clientGrantTypeStore.CreateAsync(new Entity.ClientGrantType
         {
             ClientId  = client.ClientId,
             GrantType = grantType,
             Id        = Guid.NewGuid().ToString()
         }).GetAwaiter().GetResult();
     }
 }
Пример #12
0
 private static void SeedClientClaims(IAdminStore <Entity.ClientClaim> clientClaimStore, IdentityServer4.Models.Client client)
 {
     foreach (var claim in client.Claims)
     {
         clientClaimStore.CreateAsync(new Entity.ClientClaim
         {
             ClientId = client.ClientId,
             Id       = Guid.NewGuid().ToString(),
             Type     = claim.Type,
             Value    = claim.Value
         }).GetAwaiter().GetResult();
     }
 }
Пример #13
0
 private static void SeedClientSecrets(IAdminStore <Entity.ClientSecret> clientSecretStore, IdentityServer4.Models.Client client)
 {
     foreach (var secret in client.ClientSecrets)
     {
         clientSecretStore.CreateAsync(new Entity.ClientSecret
         {
             ClientId    = client.ClientId,
             Description = secret.Description,
             Expiration  = secret.Expiration,
             Id          = Guid.NewGuid().ToString(),
             Type        = secret.Type,
             Value       = secret.Value
         }).GetAwaiter().GetResult();
     }
 }
Пример #14
0
 public Task <bool> IsRedirectUriValidAsync(string requestedUri, IdentityServer4.Models.Client client)
 {
     _logger.LogInformation("Client {ClientName} used post logout uri {RequestedUri}.", client.ClientName, requestedUri);
     return(Task.FromResult(true));
 }