コード例 #1
0
        public IActionResult AddTestClient(TestClientViewModel clientViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var apiScopes = clientViewModel.ApiScopes.Split(" ").Select(apiScope => apiScope.Trim()).ToArray();

            var client = new ClientModel
            {
                ClientId          = clientViewModel.ClientId,
                ClientName        = clientViewModel.ClientName,
                AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,

                ClientSecrets =
                {
                    new SecretModel(clientViewModel.ClientSecret.Sha256())
                },

                AllowedScopes = apiScopes
            };

            _configurationDbContext.Clients.Add(client.ToEntity());
            _configurationDbContext.SaveChanges();

            _trackTelemetry.TrackEvent(EventName.AddTestClient, EventType.Action, EventStatus.Success);
            return(RedirectToAction(nameof(Index)));
        }
コード例 #2
0
        public IActionResult CreateClientApps([FromBody] JObject jObject)
        {
            try
            {
                var applicationName   = (string)jObject["applicationName"];
                var applicationSecret = (string)jObject["applicationSecret"];
                var client            = new IdentityServer4.Models.Client
                {
                    ClientId            = Guid.NewGuid().ToString(),
                    ClientSecrets       = { new IdentityServer4.Models.Secret(applicationSecret.Sha256()) },
                    ClientName          = applicationName,
                    AllowedGrantTypes   = GrantTypes.ClientCredentials,
                    AllowedScopes       = { "scim.read.write" },
                    AccessTokenLifetime = 600
                };
                _configurationDbContext.Clients.Add(client.ToEntity());
                _configurationDbContext.SaveChanges();

                return(Ok(client));
            }
            catch (Exception exception)
            {
                var errorJobject = CommonFunctions.CreateErrorJobject(exception);
                Response.Headers.Add("Content-Type", "application/scim+json");

                return(StatusCode(StatusCodes.Status500InternalServerError, errorJobject));
            }
        }
コード例 #3
0
        private void InitializeIdentityServerDatabase(IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope()) {
                serviceScope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();
                var context = serviceScope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();
                context.Database.Migrate();
                if (!context.Clients.Any())
                {
                    var client1 = new IdentityServer4.Models.Client {
                        ClientId          = "demo.client1",
                        AllowedGrantTypes = GrantTypes.ClientCredentials,
                        ClientSecrets     =
                        {
                            new IdentityServer4.Models.Secret("secret".Sha256())
                        },
                        AllowedScopes = { "demo.api1" },
                        ClientName    = "Demo Client1"
                    };
                    context.Clients.Add(client1.ToEntity());
                    context.SaveChanges();
                }

                if (!context.ApiResources.Any())
                {
                    var api1 = new IdentityServer4.Models.ApiResource {
                        Name        = "demo.api1",
                        DisplayName = "demo api",
                        Description = "this is just for demo"
                    };
                    context.ApiResources.Add(api1.ToEntity());
                    context.SaveChanges();
                }
            }
        }
コード例 #4
0
ファイル: ClientController.cs プロジェクト: yiyungent/UHub
        public async Task <ActionResult <ResponseModel> > Create(ClientInputModel inputModel)
        {
            ResponseModel responseModel = new ResponseModel();

            try
            {
                // TODO: 效验
                #region 效验
                // 1.授权类型只能来自选项
                // eg: 若选项是两项: CodeAndClientCredentials => authorization_code,client_credentials
                string selectedGrantTypes = inputModel.AllowedGrantTypes;
                if (!AllGrantTypes.Contains(selectedGrantTypes))
                {
                    responseModel.code    = -1;
                    responseModel.message = "创建失败: 不存在此授权类型";
                    return(await Task.FromResult(responseModel));
                }

                #endregion

                // InputModel => IdentityServer4.Models
                IdentityServer4.Models.Client clientModel = new IdentityServer4.Models.Client()
                {
                    ClientId           = inputModel.ClientId,
                    ClientName         = inputModel.DisplayName,
                    AllowedGrantTypes  = inputModel.AllowedGrantTypes?.Split(","),
                    AllowedScopes      = inputModel.AllowedScopes?.Split(","),
                    Description        = inputModel.Description,
                    AllowedCorsOrigins = inputModel.AllowedCorsOrigins?.Split(","),
                    ClientSecrets      = new List <Secret>()
                    {
                        new Secret(inputModel.ClientSecret.Sha256())
                    },
                    PostLogoutRedirectUris           = inputModel.PostLogoutRedirectUris?.Split(","),
                    RedirectUris                     = inputModel.RedirectUris?.Split(","),
                    RequireConsent                   = inputModel.RequireConsent,
                    AllowAccessTokensViaBrowser      = inputModel.AllowAccessTokensViaBrowser,
                    AlwaysIncludeUserClaimsInIdToken = inputModel.AlwaysIncludeUserClaimsInIdToken,
                    AllowOfflineAccess               = inputModel.AllowOfflineAccess
                };

                // 保存到数据库
                var dbModel = clientModel.ToEntity();
                // TODO: 注意: 1.发现使用 DateTime.UtcNow 时间不正确,不知道为什么,明明推荐用这个统一时间 2.就算不手动赋值, 最后也会有创建时间, 更新时间, 而内部用的就是UtcNow
                dbModel.Created = DateTime.Now;
                await _configurationDbContext.Clients.AddAsync(dbModel);

                await _configurationDbContext.SaveChangesAsync();

                responseModel.code    = 1;
                responseModel.message = "创建成功 ";
            }
            catch (Exception ex)
            {
                responseModel.code    = -1;
                responseModel.message = "创建失败: " + ex.Message;
            }

            return(await Task.FromResult(responseModel));
        }
コード例 #5
0
        public IActionResult AddClient(ClientViewModel clientViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var apiScopes = clientViewModel.ApiScopes.Split(" ").Select(apiScope => apiScope.Trim()).ToArray();

            var client = new ClientModel
            {
                ClientId                    = clientViewModel.ClientId,
                ClientName                  = clientViewModel.ClientName,
                AllowedGrantTypes           = GrantTypes.Implicit,
                AllowAccessTokensViaBrowser = clientViewModel.AllowAccessTokensViaBrowser,
                RequireConsent              = false,

                RedirectUris           = { clientViewModel.RedirectUri },
                PostLogoutRedirectUris = { clientViewModel.PostLogoutRedirectUri },
                AllowedCorsOrigins     = { clientViewModel.CorsOrigin },

                AllowedScopes = apiScopes
            };

            _configurationDbContext.Clients.Add(client.ToEntity());
            _configurationDbContext.SaveChanges();

            _trackTelemetry.TrackEvent(EventName.AddClient, EventType.Action, EventStatus.Success);
            return(RedirectToAction(nameof(Index)));
        }
コード例 #6
0
        public async Task <IActionResult> Create([FromBody] CreateClientRequest request)
        {
            var clientId = (request.UserId + "client_id_" + request.ApplicationName).Sha256();
            int i        = 0;

            Console.WriteLine("clientId = " + clientId);
            while (true)
            {
                Console.WriteLine("IndexOf + = " + (clientId.IndexOf('+') >= 0).ToString());
                if (clientId.IndexOf('+') >= 0)
                {
                    clientId = (request.UserId + "client_id_" + request.ApplicationName + "_" + i).Sha256();
                    Console.WriteLine("clientId = " + clientId);
                    i++;
                }
                else
                {
                    break;
                }
            }
            var clientSecret = ("client_secret_" + request.ApplicationName).Sha256();

            request.RedirectUris.Add("http://localhost:7030/Auth/AuthorizationGrantCode");
            IdentityServer4.Models.Client client = new IdentityServer4.Models.Client
            {
                ClientName    = request.ApplicationName,
                ClientId      = clientId,
                ClientSecrets =
                {
                    new IdentityServer4.Models.Secret(clientSecret.Sha256())
                },
                AllowedGrantTypes      = { GrantType.AuthorizationCode, GrantType.ClientCredentials },
                RedirectUris           = request.RedirectUris,
                AllowedScopes          = request.Scopes,
                RequireConsent         = true,
                AlwaysSendClientClaims = true
            };
            var entry = await _configurationDbContext.Clients.AddAsync(client.ToEntity());

            if (await _configurationDbContext.SaveChangesAsync() > 0)
            {
                List <string> scopes = new List <string>();
                foreach (var item in entry.Entity.AllowedScopes)
                {
                    scopes.Add(item.Scope);
                }
                var response = new CreateClientResponse
                {
                    ClientId        = entry.Entity.ClientId,
                    ClientSecret    = clientSecret,
                    RedirectUris    = entry.Entity.RedirectUris.Select(x => x.RedirectUri).ToList(),
                    ApplicationName = request.ApplicationName,
                    Scopes          = entry.Entity.AllowedScopes.Select(x => x.Scope).Join(",")
                };
                return(await Task.FromResult(Ok(response)));
            }
            return(BadRequest());
        }
コード例 #7
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;
        }
コード例 #8
0
 public Task Create(IdentityServer4.Models.Client client)
 {
     if (client == null)
     {
         throw new ArgumentNullException(nameof(client));
     }
     State.Client = client.ToEntity();
     return(WriteStateAsync());
 }
コード例 #9
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;
        }
コード例 #10
0
 private static void AddTestEntitiesToSql(IS4.Client client, IS4.ApiResource apiResource)
 {
     using (var identityContext = IdentityDbContext)
     {
         identityContext.Database.ExecuteSqlCommand(DeleteDataSql);
         identityContext.ApiResources.Add(apiResource.ToEntity());
         identityContext.Clients.Add(client.ToEntity());
         identityContext.SaveChanges();
     }
 }
コード例 #11
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;
        }
コード例 #12
0
ファイル: ManageController.cs プロジェクト: detmach/Teknik
        public IActionResult CreateClient(CreateClientModel model, [FromServices] ConfigurationDbContext configContext)
        {
            // Generate a unique client ID
            var clientId = StringHelper.RandomString(20, "abcdefghjkmnpqrstuvwxyz1234567890");

            while (configContext.Clients.Where(c => c.ClientId == clientId).FirstOrDefault() != null)
            {
                clientId = StringHelper.RandomString(20, "abcdefghjkmnpqrstuvwxyz1234567890");
            }

            var clientSecret = StringHelper.RandomString(40, "abcdefghjkmnpqrstuvwxyz1234567890");

            // Generate the origin for the callback
            Uri    redirect = new Uri(model.CallbackUrl);
            string origin   = redirect.Scheme + "://" + redirect.Host;

            var client = new IdentityServer4.Models.Client
            {
                Properties = new Dictionary <string, string>()
                {
                    { "username", model.Username }
                },
                ClientId   = clientId,
                ClientName = model.Name,
                ClientUri  = model.HomepageUrl,
                LogoUri    = model.LogoUrl,

                AllowedGrantTypes = model.AllowedGrants,
                AllowedScopes     = model.AllowedScopes,

                ClientSecrets =
                {
                    new IdentityServer4.Models.Secret(clientSecret.Sha256())
                },

                RedirectUris =
                {
                    model.CallbackUrl
                },

                AllowedCorsOrigins =
                {
                    origin
                },

                RequireConsent     = true,
                AllowOfflineAccess = true
            };

            configContext.Clients.Add(client.ToEntity());
            configContext.SaveChanges();

            return(new JsonResult(new { success = true, data = new { id = clientId, secret = clientSecret } }));
        }
コード例 #13
0
        public void UpdateAllowedGrantType(
            IdentityServer4.EntityFramework.Entities.Client client,
            string allowedGrantType
            )
        {
            ICollection <string> clientGrantTypeList = new List <string>();

            if (!string.IsNullOrEmpty(allowedGrantType))
            {
                clientGrantTypeList = _clientGrantTypeManager.GetClientGrantTypesForName(allowedGrantType);
            }

            IdentityServer4.Models.Client clientModel = new IdentityServer4.Models.Client()
            {
                ClientId = "ClientId"
            };
            clientModel.AllowedGrantTypes = clientGrantTypeList;
            var newclient = clientModel.ToEntity();

            client.AllowedGrantTypes = clientModel.ToEntity().AllowedGrantTypes;
        }
コード例 #14
0
        public async Task <IActionResult> Post([FromBody] IroncladClient model)
        {
            if (string.IsNullOrEmpty(model.Id))
            {
                return(this.BadRequest(new { Message = $"Cannot create a client without a client ID" }));
            }

            var accessTokenType = default(AccessTokenType);

            if (model.AccessTokenType != null && !Enum.TryParse(model.AccessTokenType, out accessTokenType))
            {
                return(this.BadRequest(new { Message = $"Access token type '{model.AccessTokenType}' does not exist" }));
            }

            var client = new IdentityServerClient {
                ClientId = model.Id
            };

            // optional properties
            client.ClientName    = model.Name ?? client.ClientName;
            client.ClientSecrets = model.Secret == null ? client.ClientSecrets : new HashSet <Secret> {
                new Secret(model.Secret.Sha256())
            };
            client.AllowedCorsOrigins          = model.AllowedCorsOrigins ?? client.AllowedCorsOrigins;
            client.RedirectUris                = model.RedirectUris ?? client.RedirectUris;
            client.PostLogoutRedirectUris      = model.PostLogoutRedirectUris ?? client.PostLogoutRedirectUris;
            client.AllowedScopes               = model.AllowedScopes ?? client.AllowedScopes;
            client.AccessTokenType             = model.AccessTokenType == null ? client.AccessTokenType : accessTokenType;
            client.AllowedGrantTypes           = model.AllowedGrantTypes ?? client.AllowedGrantTypes;
            client.AllowAccessTokensViaBrowser = model.AllowAccessTokensViaBrowser ?? client.AllowAccessTokensViaBrowser;
            client.AllowOfflineAccess          = model.AllowOfflineAccess ?? client.AllowOfflineAccess;
            client.RequireClientSecret         = model.RequireClientSecret ?? client.RequireClientSecret;
            client.RequirePkce    = model.RequirePkce ?? client.RequirePkce;
            client.RequireConsent = model.RequireConsent ?? client.RequireConsent;
            client.Enabled        = model.Enabled ?? client.Enabled;

            using (var session = this.store.LightweightSession())
            {
                if (session.Query <PostgresClient>().Any(document => document.ClientId == client.ClientId))
                {
                    return(this.StatusCode((int)HttpStatusCode.Conflict, new { Message = "Client already exists" }));
                }

                session.Insert(client.ToEntity());

                await session.SaveChangesAsync();
            }

            return(this.Created(new Uri(this.HttpContext.GetIdentityServerRelativeUrl("~/api/clients/" + model.Id)), null));
        }
コード例 #15
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;
        }
コード例 #16
0
        public async Task <bool> AddClient(IdentityServer4.Models.Client client)
        {
            bool Result = false;

            try
            {
                await Context.Clients.AddAsync(client.ToEntity());

                Result = await Context.SaveChangesAsync() > 0;
            }
            catch (Exception E)
            {
                var Message = E.Message;
            }
            return(Result);
        }
コード例 #17
0
        private IdentityServer4.EntityFramework.Entities.Client MapBllToDal(SharedModels.Client client)
        {
            IdentityServer4.Models.Client clientModelIds4 = new IdentityServer4.Models.Client();

            clientModelIds4.ClientName            = client.ClientName;
            clientModelIds4.ClientUri             = client.ClientUri;
            clientModelIds4.ClientId              = client.ClientId;
            clientModelIds4.FrontChannelLogoutUri = client.FrontChannelLogoutUrl;

            if (client.ClientSecret != null)
            {
                IdentityServer4.Models.Secret secret = new IdentityServer4.Models.Secret(client.ClientSecret.Sha256());
                secret.Type = "SharedSecret";
                clientModelIds4.ClientSecrets = new List <IdentityServer4.Models.Secret>();
                clientModelIds4.ClientSecrets.Add(secret);
            }


            clientModelIds4.AllowedGrantTypes = new List <string>();
            client.GrantType = client.GrantType.Replace(" ", "_");
            clientModelIds4.AllowedGrantTypes.Add(client.GrantType);

            if (client.ClientProperty != null)
            {
                string key = "ApplicationType";
                clientModelIds4.Properties = new Dictionary <string, string>();
                clientModelIds4.Properties.Add(key, client.ClientProperty);
            }

            clientModelIds4.AllowedScopes = new List <string>();
            foreach (string scope in client.AllowedScopes)
            {
                var replacedScope = scope.Replace(" ", "_");
                clientModelIds4.AllowedScopes.Add(replacedScope);
            }

            clientModelIds4.RedirectUris = new List <string>();
            foreach (string redirctUri in client.RedirectUrls)
            {
                clientModelIds4.RedirectUris.Add(redirctUri);
            }

            clientModelIds4.PostLogoutRedirectUris = new List <string>();
            clientModelIds4.PostLogoutRedirectUris.Add(client.PostLogoutUrl);

            return(clientModelIds4.ToEntity());
        }
コード例 #18
0
        public IActionResult AddClient()
        {
            IdentityServer4.Models.Client client = new IdentityServer4.Models.Client();

            client.ClientId      = "mobileapp";
            client.ClientSecrets = new List <IdentityServer4.Models.Secret> {
                new IdentityServer4.Models.Secret("cleduclient".Sha256())
            };

            client.AllowedScopes = new List <string> {
                "api_meteo_scope"
            };

            _confContext.Clients.Add(client.ToEntity());
            _confContext.SaveChanges();
            return(Ok());
        }
コード例 #19
0
            public IActionResult EditClient(IdentityServer4.Models.Client model)
            {
                var vModel = model.ToEntity();

                var rClient = _configContext.Clients.Where(s => s.ClientId == model.ClientId).SingleOrDefault();

                rClient.ClientId                         = model.ClientId;
                rClient.ClientName                       = model.ClientName;
                rClient.RedirectUris                     = vModel.RedirectUris;
                rClient.PostLogoutRedirectUris           = vModel.PostLogoutRedirectUris;
                rClient.Description                      = model.Description;
                rClient.AllowOfflineAccess               = model.AllowOfflineAccess;
                rClient.AlwaysSendClientClaims           = model.AlwaysSendClientClaims;
                rClient.AlwaysIncludeUserClaimsInIdToken = model.AlwaysIncludeUserClaimsInIdToken;
                rClient.RequireConsent                   = model.RequireConsent;

                _configContext.Update(rClient);
                _configContext.SaveChanges();
                return(RedirectToAction("ClientList"));
            }
コード例 #20
0
        public IActionResult AddClientProfile()
        {
            IdentityServer4.Models.Client client = new IdentityServer4.Models.Client();

            client.ClientId      = "mvcapp";
            client.ClientSecrets = new List <IdentityServer4.Models.Secret> {
                new IdentityServer4.Models.Secret("cleduclient".Sha256())
            };

            client.AllowedScopes = new List <string> {
                "api_meteo_scope", IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile
            };

            client.AllowedGrantTypes = GrantTypes.Code;

            // URLS de redirection =>>> https://oauth.pstmn.io/v1/callback

            _confContext.Clients.Add(client.ToEntity());
            _confContext.SaveChanges();
            return(Ok());
        }
コード例 #21
0
        public IdentityServer4.EntityFramework.Entities.Client CreateClient(
            string clientId,
            string allowedGrantType,
            List <string> clientSecrets,
            List <string> redirectUris,
            List <string> postLogoutRedirectUris,
            List <string> allowedScopes
            )
        {
            ICollection <string> clientGrantTypeList = new List <string>();

            // 认证客户端认证类型是否存在
            if (!string.IsNullOrEmpty(allowedGrantType) && !_clientGrantTypeManager.IsExistClientGrantTypeGroup(allowedGrantType))
            {
                throw new Exception("不存在的客户端认证类型[" + allowedGrantType + "]");
            }

            if (!string.IsNullOrEmpty(allowedGrantType))
            {
                clientGrantTypeList = _clientGrantTypeManager.GetClientGrantTypesForName(allowedGrantType);
            }

            List <IdentityServer4.Models.Secret> clientSecretList = new List <IdentityServer4.Models.Secret>();

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

            IdentityServer4.Models.Client client = new IdentityServer4.Models.Client()
            {
                ClientId               = clientId,
                AllowedGrantTypes      = clientGrantTypeList,
                ClientSecrets          = clientSecretList,
                RedirectUris           = redirectUris,
                PostLogoutRedirectUris = postLogoutRedirectUris,
                AllowedScopes          = allowedScopes,
            };

            return(client.ToEntity());
        }
コード例 #22
0
        public async Task <JsonResult> Create(IdentityServer4.Models.Client request)
        {
            JsonResponse response = new JsonResponse();

            request.ClientSecrets.ToList().ForEach(m =>
            {
                m.Value = m.Value.Sha256();
            });
            var model = (await _context.Clients.AddAsync(request.ToEntity())).Entity;
            await _context.SaveChangesAsync();

            if (model != null)
            {
                response.status = 0;
                response.code   = "200";
            }
            else
            {
                response.status = -1;
                response.code   = "500";
            }
            return(Json(response));
        }
コード例 #23
0
        public async Task <MessageModel <string> > SaveData(ClientDto request)
        {
            if (request != null && request.id == 0)
            {
                IdentityServer4.Models.Client client = new IdentityServer4.Models.Client()
                {
                    ClientId    = request?.ClientId,
                    ClientName  = request?.ClientName,
                    Description = request?.Description,
                    AllowAccessTokensViaBrowser = (request?.AllowAccessTokensViaBrowser).ObjToBool(),
                    AllowedCorsOrigins          = request?.AllowedCorsOrigins?.Split(","),
                    AllowedGrantTypes           = request?.AllowedGrantTypes?.Split(","),
                    AllowedScopes          = request?.AllowedScopes?.Split(","),
                    PostLogoutRedirectUris = request?.PostLogoutRedirectUris?.Split(","),
                    RedirectUris           = request?.RedirectUris?.Split(","),
                };

                if (!string.IsNullOrEmpty(request.ClientSecrets))
                {
                    client.ClientSecrets = new List <Secret>()
                    {
                        new Secret(request.ClientSecrets.Sha256())
                    };
                }

                var result = (await _configurationDbContext.Clients.AddAsync(client.ToEntity()));
                await _configurationDbContext.SaveChangesAsync();
            }

            if (request != null && request.id > 0)
            {
                var modelEF = (await _configurationDbContext.Clients
                               .Include(d => d.AllowedGrantTypes)
                               .Include(d => d.AllowedScopes)
                               .Include(d => d.AllowedCorsOrigins)
                               .Include(d => d.RedirectUris)
                               .Include(d => d.PostLogoutRedirectUris)
                               .ToListAsync()).FirstOrDefault(d => d.Id == request.id);

                modelEF.ClientId    = request?.ClientId;
                modelEF.ClientName  = request?.ClientName;
                modelEF.Description = request?.Description;
                modelEF.AllowAccessTokensViaBrowser = (request?.AllowAccessTokensViaBrowser).ObjToBool();

                var AllowedCorsOrigins = new List <IdentityServer4.EntityFramework.Entities.ClientCorsOrigin>();
                if (!string.IsNullOrEmpty(request?.AllowedCorsOrigins))
                {
                    request?.AllowedCorsOrigins.Split(",").Where(s => s != "" && s != null).ToList().ForEach(s =>
                    {
                        AllowedCorsOrigins.Add(new IdentityServer4.EntityFramework.Entities.ClientCorsOrigin()
                        {
                            Client   = modelEF,
                            ClientId = modelEF.Id,
                            Origin   = s
                        });
                    });
                    modelEF.AllowedCorsOrigins = AllowedCorsOrigins;
                }



                var AllowedGrantTypes = new List <IdentityServer4.EntityFramework.Entities.ClientGrantType>();
                if (!string.IsNullOrEmpty(request?.AllowedGrantTypes))
                {
                    request?.AllowedGrantTypes.Split(",").Where(s => s != "" && s != null).ToList().ForEach(s =>
                    {
                        AllowedGrantTypes.Add(new IdentityServer4.EntityFramework.Entities.ClientGrantType()
                        {
                            Client    = modelEF,
                            ClientId  = modelEF.Id,
                            GrantType = s
                        });
                    });
                    modelEF.AllowedGrantTypes = AllowedGrantTypes;
                }



                var AllowedScopes = new List <IdentityServer4.EntityFramework.Entities.ClientScope>();
                if (!string.IsNullOrEmpty(request?.AllowedScopes))
                {
                    request?.AllowedScopes.Split(",").Where(s => s != "" && s != null).ToList().ForEach(s =>
                    {
                        AllowedScopes.Add(new IdentityServer4.EntityFramework.Entities.ClientScope()
                        {
                            Client   = modelEF,
                            ClientId = modelEF.Id,
                            Scope    = s
                        });
                    });
                    modelEF.AllowedScopes = AllowedScopes;
                }


                var PostLogoutRedirectUris = new List <IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri>();
                if (!string.IsNullOrEmpty(request?.PostLogoutRedirectUris))
                {
                    request?.PostLogoutRedirectUris.Split(",").Where(s => s != "" && s != null).ToList().ForEach(s =>
                    {
                        PostLogoutRedirectUris.Add(new IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri()
                        {
                            Client   = modelEF,
                            ClientId = modelEF.Id,
                            PostLogoutRedirectUri = s
                        });
                    });
                    modelEF.PostLogoutRedirectUris = PostLogoutRedirectUris;
                }


                var RedirectUris = new List <IdentityServer4.EntityFramework.Entities.ClientRedirectUri>();
                if (!string.IsNullOrEmpty(request?.RedirectUris))
                {
                    request?.RedirectUris.Split(",").Where(s => s != "" && s != null).ToList().ForEach(s =>
                    {
                        RedirectUris.Add(new IdentityServer4.EntityFramework.Entities.ClientRedirectUri()
                        {
                            Client      = modelEF,
                            ClientId    = modelEF.Id,
                            RedirectUri = s
                        });
                    });
                    modelEF.RedirectUris = RedirectUris;
                }

                var result = (_configurationDbContext.Clients.Update(modelEF));
                await _configurationDbContext.SaveChangesAsync();
            }


            return(new MessageModel <string>()
            {
                success = true,
                msg = "添加成功",
            });
        }
コード例 #24
0
        public static void ConfigurationDbContextSeed(this ModelBuilder modelBuilder)
        {
            var clientGrantTypeEntity = new ClientGrantType
            {
                Id        = -1,
                GrantType = GrantType.ResourceOwnerPassword,
                ClientId  = -1,
            };

            var clientScopes = new[]
            {
                new ClientScope
                {
                    ClientId = -1,
                    Id       = -1,
                    Scope    = "record-keep-api"
                },
                new ClientScope
                {
                    ClientId = -1,
                    Id       = -2,
                    Scope    = IdentityServerConstants.StandardScopes.OpenId
                },
                new ClientScope
                {
                    ClientId = -1,
                    Id       = -3,
                    Scope    = IdentityServerConstants.StandardScopes.Profile
                }
            };

            var client = new Client
            {
                ClientId                    = "record-keep",
                AccessTokenType             = AccessTokenType.Jwt,
                RequireClientSecret         = false,
                AllowOfflineAccess          = false,
                AllowAccessTokensViaBrowser = true
            };

            var clientEntity = client.ToEntity();

            clientEntity.Id = -1;

            var apiResourceClaimEntity = new ApiResourceClaim
            {
                Id            = -1,
                ApiResourceId = -1,
                Type          = JwtClaimTypes.Name
            };

            var apiResourceScopesEntity = new ApiScope
            {
                Name          = "record-keep-api",
                Id            = -1,
                DisplayName   = "Record Keep API",
                ApiResourceId = -1,
            };

            var apiResource = new ApiResource
            {
                Name        = "record-keep-api",
                DisplayName = "Record Keep API"
            };

            var apiResourceEntity = apiResource.ToEntity();

            apiResourceEntity.Id = -1;

            var openIdIdentity  = new IdentityResources.OpenId().ToEntity();
            var profileIdentity = new IdentityResources.Profile().ToEntity();

            openIdIdentity.Id  = -1;
            profileIdentity.Id = -2;

            var identityClaimOpenId = new IdentityClaim
            {
                Id   = -1,
                Type = JwtClaimTypes.Subject,
                IdentityResourceId = -1
            };

            var identityClaims = new List <IdentityClaim>
            {
                identityClaimOpenId
            };

            var index = -2;

            foreach (var claims in profileIdentity.UserClaims)
            {
                identityClaims.Add(new IdentityClaim
                {
                    Id   = index,
                    Type = claims.Type,
                    IdentityResourceId = -2,
                });

                index--;
            }

            openIdIdentity.UserClaims  = new List <IdentityClaim>();
            profileIdentity.UserClaims = new List <IdentityClaim>();

            modelBuilder.Entity <ClientGrantType>().HasData(clientGrantTypeEntity);
            modelBuilder.Entity <ClientScope>().HasData(clientScopes);
            modelBuilder.Entity <IdentityServer4.EntityFramework.Entities.Client>().HasData(clientEntity);

            modelBuilder.Entity <ApiResourceClaim>().HasData(apiResourceClaimEntity);
            modelBuilder.Entity <ApiScope>().HasData(apiResourceScopesEntity);
            modelBuilder.Entity <IdentityServer4.EntityFramework.Entities.ApiResource>().HasData(apiResourceEntity);

            modelBuilder.Entity <IdentityResource>().HasData(openIdIdentity, profileIdentity);
            modelBuilder.Entity <IdentityClaim>().HasData(identityClaims);
        }
コード例 #25
0
        public async Task <IActionResult> Put(string clientId, [FromBody] IroncladClient model)
        {
            if (string.Equals(clientId, "auth_console", StringComparison.OrdinalIgnoreCase))
            {
                return(this.BadRequest(new { Message = $"Cannot modify the authorization console client" }));
            }

            using (var session = this.store.LightweightSession())
            {
                var document = await session.Query <PostgresClient>().SingleOrDefaultAsync(item => item.ClientId == clientId);

                if (document == null)
                {
                    return(this.NotFound(new { Message = $"Client '{clientId}' not found" }));
                }

                var accessTokenType = default(AccessTokenType);
                if (model.AccessTokenType != null && !Enum.TryParse(model.AccessTokenType, out accessTokenType))
                {
                    return(this.BadRequest(new { Message = $"Access token type '{model.AccessTokenType}' does not exist" }));
                }

                // NOTE (Cameron): Because of the mapping/conversion unknowns we rely upon the Postgres integration to perform that operation which is why we do this...
                var client = new IdentityServerClient
                {
                    AllowedCorsOrigins     = model.AllowedCorsOrigins,
                    RedirectUris           = model.RedirectUris,
                    PostLogoutRedirectUris = model.PostLogoutRedirectUris,
                    AllowedScopes          = model.AllowedScopes,
                    AllowedGrantTypes      = model.AllowedGrantTypes,
                };

                client.AccessTokenType = model.AccessTokenType == null ? client.AccessTokenType : accessTokenType;

                // NOTE (Cameron): If the secret is updated we want to add the new secret...
                if (!string.IsNullOrEmpty(model.Secret))
                {
                    client.ClientSecrets = new List <Secret> {
                        new Secret(model.Secret.Sha256())
                    };
                }

                var entity = client.ToEntity();

                // update properties (everything supported is an optional update eg. if null is passed we will not update)
                document.ClientName                  = model.Name ?? document.ClientName;
                document.AllowedCorsOrigins          = entity.AllowedCorsOrigins ?? document.AllowedCorsOrigins;
                document.RedirectUris                = entity.RedirectUris ?? document.RedirectUris;
                document.PostLogoutRedirectUris      = entity.PostLogoutRedirectUris ?? document.PostLogoutRedirectUris;
                document.AllowedScopes               = entity.AllowedScopes ?? document.AllowedScopes;
                document.AccessTokenType             = model.AccessTokenType == null ? document.AccessTokenType : entity.AccessTokenType;
                document.AllowedGrantTypes           = entity.AllowedGrantTypes ?? document.AllowedGrantTypes;
                document.AllowAccessTokensViaBrowser = model.AllowAccessTokensViaBrowser ?? document.AllowAccessTokensViaBrowser;
                document.AllowOfflineAccess          = model.AllowOfflineAccess ?? document.AllowOfflineAccess;
                document.RequireClientSecret         = model.RequireClientSecret ?? document.RequireClientSecret;
                document.RequirePkce                 = model.RequirePkce ?? document.RequirePkce;
                document.RequireConsent              = model.RequireConsent ?? document.RequireConsent;
                document.Enabled = model.Enabled ?? document.Enabled;

                if (!string.IsNullOrEmpty(model.Secret))
                {
                    document.ClientSecrets.Add(entity.ClientSecrets.First());
                }

                session.Update(document);

                await session.SaveChangesAsync();
            }

            return(this.Ok());
        }
コード例 #26
0
ファイル: SeedData.cs プロジェクト: BionStt/edamos
        public static void Clients(ConfigurationDbContext context)
        {
            if (!context.ApiResources.Any(r => r.Name == UiLoginApiResource))
            {
                ApiResource resource = new ApiResource(UiLoginApiResource, "Main UI");

                context.ApiResources.Add(resource.ToEntity());

                context.SaveChanges();
            }

            if (!context.ApiResources.Any(r => r.Name == Consts.Api.ResourceId))
            {
                ApiResource resource = new ApiResource(Consts.Api.ResourceId, "Main API");

                context.ApiResources.Add(resource.ToEntity());

                context.SaveChanges();
            }

            // TODO: configure clients
            if (!context.Clients.Any(client => client.ClientId == DebugConstants.Ui.ClientId))
            {
                IdentityServer4.Models.Client client = new IdentityServer4.Models.Client();
                client.ClientId          = DebugConstants.Ui.ClientId;
                client.ClientName        = "EDAMOS UI";
                client.AllowedGrantTypes = GrantTypes.HybridAndClientCredentials;
                client.ClientSecrets     = new[] { new Secret(DebugConstants.Ui.ClientSecret.Sha256()) }; // TODO: configure secret
                client.AllowedScopes     = new[]
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    Consts.Api.ResourceId
                };

                client.RedirectUris           = new[] { DebugConstants.Ui.RootAddress + Consts.OpenId.CallbackPath };
                client.PostLogoutRedirectUris = new[] { DebugConstants.Ui.RootAddress + Consts.OpenId.SignOutCallbackPath };
                client.RequireConsent         = false;
                context.Clients.Add(client.ToEntity());

                context.SaveChanges();
            }

            if (!context.Clients.Any(client => client.ClientId == DebugConstants.AdminUi.ClientId))
            {
                IdentityServer4.Models.Client client = new IdentityServer4.Models.Client();
                client.ClientId          = DebugConstants.AdminUi.ClientId;
                client.ClientName        = "EDAMOS ADMIN";
                client.AllowedGrantTypes = GrantTypes.HybridAndClientCredentials;
                client.ClientSecrets     = new[] { new Secret(DebugConstants.AdminUi.ClientSecret.Sha256()) }; // TODO: configure secret
                client.AllowedScopes     = new[]
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    Consts.Api.ResourceId
                };

                client.RedirectUris           = new[] { DebugConstants.AdminUi.RootAddress + Consts.OpenId.CallbackPath };
                client.PostLogoutRedirectUris = new[] { DebugConstants.AdminUi.RootAddress + Consts.OpenId.SignOutCallbackPath };
                client.RequireConsent         = false;
                context.Clients.Add(client.ToEntity());

                context.SaveChanges();
            }

            if (!context.Clients.Any(client => client.ClientId == DebugConstants.ProxyUi.ClientId))
            {
                Client client = new Client();
                client.ClientId          = DebugConstants.ProxyUi.ClientId;
                client.ClientName        = "EDAMOS PROXY UI";
                client.AllowedGrantTypes = GrantTypes.HybridAndClientCredentials;
                client.ClientSecrets     = new[] { new Secret(DebugConstants.ProxyUi.ClientSecret.Sha256()) }; // TODO: configure secret
                client.AllowedScopes     = new[]
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile
                };

                client.RedirectUris = new[]
                {
                    DebugConstants.ProxyUi.KibanaRootAddress + Consts.OpenId.CallbackPath,
                    DebugConstants.ProxyUi.GrafanaRootAddress + Consts.OpenId.CallbackPath,
                    DebugConstants.ProxyUi.RabbitMqRootAddress + Consts.OpenId.CallbackPath,
                };
                client.PostLogoutRedirectUris = new[]
                {
                    DebugConstants.ProxyUi.KibanaRootAddress + Consts.OpenId.SignOutCallbackPath,
                    DebugConstants.ProxyUi.GrafanaRootAddress + Consts.OpenId.SignOutCallbackPath,
                    DebugConstants.ProxyUi.RabbitMqRootAddress + Consts.OpenId.SignOutCallbackPath,
                };
                client.RequireConsent = false;
                context.Clients.Add(client.ToEntity());

                context.SaveChanges();
            }
        }
コード例 #27
0
            public IActionResult CreateClient(ClientModel model)
            {
                if (model.SelectedScopes == null)
                {
                    ModelState.AddModelError("Client", "Please select or insert at least a scope.");
                }

                if (model.AllowedGrantType == null)
                {
                    ModelState.AddModelError("Client", "Please select a grnt type.");
                }

                if (model.RedirectUris == null)
                {
                    ModelState.AddModelError("Client", "Please insert at least a RedirectUris.");
                }

                if (model.PostLogoutRedirectUris == null)
                {
                    ModelState.AddModelError("Client", "Please insert at least a PostLogoutRedirectUris.");
                }
                var grantType = HelperExtension.GetPropValue <GrantTypes>(model.AllowedGrantType) as ICollection <string>;

                if (grantType == null)
                {
                    ModelState.AddModelError("Client", "grant Type not valid.");
                }

                if (!ModelState.IsValid)
                {
                    PropertyInfo[] grantInfo;
                    grantInfo = typeof(GrantTypes).GetProperties(BindingFlags.Public |
                                                                 BindingFlags.Static);
                    model.AllowedGrantTypes = grantInfo.Select(s => s.Name).ToList();

                    FieldInfo[] scopesInfo;
                    scopesInfo = typeof(StandardScopes).GetFields(BindingFlags.Public | BindingFlags.Static |
                                                                  BindingFlags.FlattenHierarchy)
                                 .Where(fi => fi.IsLiteral && !fi.IsInitOnly).ToArray();

                    model.AllowedScopes = scopesInfo.Select(s => s.GetValue(s).ToString()).ToList();

                    return(View(model));
                }

                var client = new IdentityServer4.Models.Client
                {
                    ClientId          = Guid.NewGuid().ToString(),
                    ClientName        = model.ClientName,
                    AllowedGrantTypes = grantType,
                    Description       = model.Description,
                    RequireConsent    = model.RequireConsent,

                    ClientSecrets =
                    {
                        new Secret(model.SecretCode.Sha256())
                    },

                    RedirectUris           = model.RedirectUris,
                    PostLogoutRedirectUris = model.PostLogoutRedirectUris,

                    AllowedScopes = model.SelectedScopes,

                    AllowOfflineAccess               = model.AllowOfflineAccess,
                    AlwaysSendClientClaims           = model.AlwaysSendClientClaims,
                    AlwaysIncludeUserClaimsInIdToken = model.AlwaysIncludeUserClaimsInIdToken,
                };

                _configContext.Clients.Add(client.ToEntity());
                _configContext.SaveChanges();

                return(RedirectToAction("ClientList"));
            }