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)));
        }
Exemple #2
0
        private static IdentityServer4.Models.Client CreateWpfClient()
        {
            var client = new IdentityServer4.Models.Client
            {
                ClientId   = "Boardgames.WpfClient",
                ClientName = "Wpf Client for boardgames",

                RedirectUris = { "http://127.0.0.1:8080/boardgames/" },
                //PostLogoutRedirectUris = { "https://notused" },

                RequireClientSecret = false,

                AllowedGrantTypes           = GrantTypes.Code,
                AllowAccessTokensViaBrowser = true,
                RequirePkce   = true,
                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.OfflineAccess,
                    "Boardgames.WebServerAPI"
                },

                AllowOfflineAccess = true,

                //Access token life time is 7200 seconds (2 hour)
                AccessTokenLifetime = 7200,

                //Identity token life time is 7200 seconds (2 hour)
                IdentityTokenLifetime = 7200,
                RefreshTokenUsage     = TokenUsage.ReUse,
            };

            return(client);
        }
Exemple #3
0
        private IdentityServer4.Models.Client CreateNewClient(SystemViewModel systemViewModel)
        {
            var client = new IdentityServer4.Models.Client {
                ClientId          = Guid.NewGuid().ToString(),
                ClientName        = systemViewModel.SystemName,
                AllowedGrantTypes = GrantTypes.Hybrid,
                ClientUri         = systemViewModel.ClientUri,
                Description       = systemViewModel.Description,
                ClientSecrets     =
                {
                    new IdentityServer4.Models.Secret("secret".Sha256())
                },

                RedirectUris           = { systemViewModel.ClientUri + "/signin-oidc" },
                PostLogoutRedirectUris = { systemViewModel.ClientUri + "/signout-callback-oidc" },

                AllowedScopes =
                {
                    IdentityServer4.IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServer4.IdentityServerConstants.StandardScopes.Profile,

                    "api1",
                    "access.profile",
                    "role",
                    "token"
                },

                AllowOfflineAccess          = true,
                AllowAccessTokensViaBrowser = true
            };

            return(client);
        }
Exemple #4
0
        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));
        }
Exemple #5
0
 public static IdentityServer4.Models.Client ViewModelToClient(ClientViewModel clientViewModel)
 {
     IdentityServer4.Models.Client Client = new IdentityServer4.Models.Client
     {
         ClientId      = clientViewModel.Name,
         ClientName    = clientViewModel.Name,
         AllowedScopes = clientViewModel.Scopes,
         AlwaysIncludeUserClaimsInIdToken = clientViewModel.IsIncludeIDToken,
         AllowOfflineAccess = clientViewModel.IsIncludeRefreshToken
     };
     if (clientViewModel.IsPublicClient)
     {
         Client.RequireClientSecret = false;
     }
     else
     {
         Client.ClientSecrets = new[]
         { new Secret(clientViewModel.Secret.Sha256()) };
     }
     if (!string.IsNullOrEmpty(clientViewModel.PostLogoutRedirectUri)
         & !string.IsNullOrEmpty(clientViewModel.RedirectUri))
     {
         Client.RedirectUris           = new[] { clientViewModel.RedirectUri };
         Client.PostLogoutRedirectUris = new[] { clientViewModel.PostLogoutRedirectUri };
     }
     Client.AllowedGrantTypes = Helper.GetGrantType(clientViewModel.GrantType);
     return(Client);
 }
        private ConsentViewModel CreateConsentViewModel(
            ConsentInputModel model, string returnUrl,
            AuthorizationRequest request,
            IdentityServer4.Models.Client client, Resources resources)
        {
            var vm = new ConsentViewModel
            {
                RememberConsent = model?.RememberConsent ?? true,
                ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty <string>(),

                ReturnUrl = returnUrl,

                ClientName           = client.ClientName ?? client.ClientId,
                ClientUrl            = client.ClientUri,
                ClientLogoUrl        = client.LogoUri,
                AllowRememberConsent = client.AllowRememberConsent
            };

            vm.IdentityScopes = resources.IdentityResources
                                .Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
            vm.ResourceScopes = resources.ApiResources.SelectMany(x => x.Scopes).Select(x =>
                                                                                        CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
            if (ConsentOptions.EnableOfflineAccess && resources.OfflineAccess)
            {
                vm.ResourceScopes = vm.ResourceScopes.Union(new[]
                {
                    GetOfflineAccessScope(
                        vm.ScopesConsented.Contains(
                            IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null)
                });
            }

            return(vm);
        }
Exemple #7
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));
            }
        }
Exemple #8
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();
                }
            }
        }
Exemple #9
0
        public void Configure(IdentityServer4.Models.Client client)
        {
            IClientConfigurationStrategy strategy = null;

            if (_clientType.Id == ClientType.WebImplicit.Id)
            {
                strategy = new WebImplicitClientConfigurationStrategy();
            }
            else if (_clientType.Id == ClientType.WebHybrid.Id)
            {
                strategy = new WebHybridClientConfigurationStrategy();
            }
            else if (_clientType.Id == ClientType.Device.Id)
            {
                strategy = new DeviceClientConfigurationStrategy();
            }
            else if (_clientType.Id == ClientType.Spa.Id)
            {
                strategy = new SpaClientConfigurationStrategy();
            }
            else if (_clientType.Id == ClientType.Native.Id)
            {
                strategy = new NativeClientConfigurationStrategy();
            }
            else if (_clientType.Id == ClientType.Machine.Id)
            {
                strategy = new MachineClientConfigurationStrategy();
            }
            else
            {
                // empty
            }
            strategy?.Configure(client);
        }
        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)));
        }
Exemple #11
0
        public async Task <Scope> RollupAsync(
            Neo4jIdentityServer4ApiResource apiResource,
            Neo4jIdentityServer4ApiScope apiScope,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            apiResource.ThrowIfNull(nameof(apiResource));
            apiScope.ThrowIfNull(nameof(apiScope));

            await RaiseApiScopeChangeEventAsync(apiResource, apiScope);

            var finalResult   = new Client();
            var apiScopeFound = await GetApiScopeAsync(apiResource, apiScope, cancellationToken);

            var model          = apiScopeFound.ToModel();
            var apiScopeClaims = await GetApiScopeClaimsAsync(apiResource, apiScopeFound, cancellationToken);

            if (apiScopeClaims != null)
            {
                foreach (var item in apiScopeClaims)
                {
                    model.UserClaims.Add(item.Type);
                }
            }
            var rollup = new ApiScopeRollup()
            {
                ApiScopeJson = JsonConvert.SerializeObject(model),
            };
            var result = await AddRollupAsync(apiResource, apiScopeFound, rollup, cancellationToken);

            return(model);
        }
        public void TestClientConversion()
        {
            var is4Client = new IS4.Client();
            var client    = is4Client.ToClientViewModel();

            // Secret should never be automatically copied to view model.
            Assert.Null(client.ClientSecret);
        }
        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());
        }
Exemple #14
0
 public Task Create(IdentityServer4.Models.Client client)
 {
     if (client == null)
     {
         throw new ArgumentNullException(nameof(client));
     }
     State.Client = client.ToEntity();
     return(WriteStateAsync());
 }
Exemple #15
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;
        }
Exemple #16
0
        public static Client ToClientViewModel(this IS4.Client client)
        {
            if (client == null)
            {
                return(null);
            }

            var newClient = new Client
            {
                // Basic
                Enabled                     = client.Enabled,
                ClientId                    = client.ClientId,
                RequireClientSecret         = client.RequireClientSecret,
                AllowedGrantTypes           = client.AllowedGrantTypes,
                RequirePkce                 = client.RequirePkce,
                AllowPlainTextPkce          = client.AllowPlainTextPkce,
                RedirectUris                = client.RedirectUris,
                AllowedScopes               = client.AllowedScopes,
                AllowOfflineAccess          = client.AllowOfflineAccess,
                AllowAccessTokensViaBrowser = client.AllowAccessTokensViaBrowser,
                ProtocolType                = client.ProtocolType,

                // Authentication / Logout
                PostLogoutRedirectUris       = client.PostLogoutRedirectUris,
                EnableLocalLogin             = client.EnableLocalLogin,
                IdentityProviderRestrictions = client.IdentityProviderRestrictions,
                LogoutUri             = client.LogoutUri,
                LogoutSessionRequired = client.LogoutSessionRequired,

                // Token
                IdentityTokenLifetime            = client.IdentityTokenLifetime,
                AccessTokenLifetime              = client.AccessTokenLifetime,
                AuthorizationCodeLifetime        = client.AuthorizationCodeLifetime,
                AbsoluteRefreshTokenLifetime     = client.AbsoluteRefreshTokenLifetime,
                SlidingRefreshTokenLifetime      = client.SlidingRefreshTokenLifetime,
                RefreshTokenUsage                = client.RefreshTokenUsage,
                RefreshTokenExpiration           = client.RefreshTokenExpiration,
                UpdateAccessTokenClaimsOnRefresh = client.UpdateAccessTokenClaimsOnRefresh,
                AccessTokenType                  = client.AccessTokenType,
                IncludeJwtId                     = client.IncludeJwtId,
                AllowedCorsOrigins               = client.AllowedCorsOrigins,
                Claims                           = client.Claims,
                AlwaysSendClientClaims           = client.AlwaysSendClientClaims,
                AlwaysIncludeUserClaimsInIdToken = client.AlwaysIncludeUserClaimsInIdToken,
                PrefixClientClaims               = client.PrefixClientClaims,

                // Consent
                RequireConsent       = client.RequireConsent,
                AllowRememberConsent = client.AllowRememberConsent,
                ClientName           = client.ClientName,
                ClientUri            = client.ClientUri,
                LogoUri = client.LogoUri
            };

            return(newClient);
        }
Exemple #17
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;
        }
Exemple #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;
        }
        public async Task <Client> FindClientByIdAsync(string clientId)
        {
            Model.Client    model  = null;
            Entities.Client entity = await StorageContext.GetEntityBlobAsync <Entities.Client>(clientId, StorageContext.ClientBlobContainer);

            model = entity?.ToModel();
            _logger.LogDebug("{clientName} found in blob storage: {clientFound}", clientId, model != null);

            return(model);
        }
        static IntegrationTestsFixture()
        {
            var api = GetTestApiResource();

            Client = GetTestClient();
            InMemoryDocumentDbService.AddDocument(api.Name, api);
            InMemoryDocumentDbService.AddDocument(Client.ClientId, Client);
            CreateSqlServerDatabase();
            AddTestEntitiesToSql(Client, api);
        }
 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();
     }
 }
Exemple #22
0
        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 } }));
        }
Exemple #23
0
 public CreateClientCommand(string clientId, string clientName, string clientUri, string description, string logoUri, ClientType clientType)
 {
     Client = new IdentityServer4.Models.Client
     {
         ClientId    = clientId,
         ClientName  = clientName,
         ClientUri   = clientUri,
         LogoUri     = logoUri,
         Description = description
     };
     ClientType = clientType;
 }
        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));
        }
Exemple #25
0
        public async void ShouldAddAndSaveTheClientInTheContext()
        {
            var client           = new Models.Client();
            var context          = A.Fake <IConfigurationDbContext>();
            var clientRepository = new ClientRepository(context);

            await clientRepository.AddAsync(client);

            A.CallTo(() => context.SaveChangesAsync())
            .MustHaveHappened();

            A.CallTo(() => context.Clients.AddAsync(
                         A <Entities.Client> .Ignored,
                         A <CancellationToken> .Ignored))
            .MustHaveHappened();
        }
Exemple #26
0
        public async Task <JsonResult> GetList(IdentityServer4.Models.Client dto)
        {
            JsonResponse json  = new JsonResponse();
            var          query = _context.Clients.AsQueryable();

            if (!string.IsNullOrEmpty(dto.ClientId))
            {
                query = query.Where(m => m.ClientId == dto.ClientId);
            }
            var list = await query.ToListAsync();

            json.status = 0;
            json.total  = list.Count();
            json.data   = list;
            return(Json(json));
        }
Exemple #27
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);
        }
Exemple #28
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;
        }
Exemple #29
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());
        }
        public Task <Client> FindClientByIdAsync(string clientId)
        {
            var c = uow.Clients.Find(cl => cl.ClientId == clientId).FirstOrDefault();

            // preparing the secrets
            List <Secret> secrets = new List <Secret>();
            List <DomainModel.ClientSecret> cs = uow.Clients.GetSecrets(clientId).ToList();

            foreach (var s in cs)
            {
                secrets.Add(new Secret()
                {
                    Description = s.Description,
                    Expiration  = s.Expiration,
                    Type        = s.Type,
                    Value       = s.Value
                });
            }



            // prepapring the allowed grant types
            List <string> grantTypes = uow.Clients.GetGrantTypes(clientId).Select(x => x.GrantType).ToList();

            // preparing scopes
            List <string> scopes = uow.Clients.GetScopes(clientId).Select(x => x.Scope).ToList();

            //prepare cors origins
            List <string> cors = uow.Clients.GetCorsOrigins(clientId).Select(x => x.Origin).ToList();

            IdentityServer4.Models.Client C = new IdentityServer4.Models.Client()
            {
                ClientId                    = c.ClientId,
                AllowOfflineAccess          = c.AllowOfflineAccess,
                AccessTokenLifetime         = c.AccessTokenLifeTime,
                AllowedGrantTypes           = grantTypes,
                AccessTokenType             = c.AccessTokenIsReference? AccessTokenType.Reference : AccessTokenType.Jwt,
                ClientSecrets               = secrets,
                AllowedScopes               = scopes,
                AllowedCorsOrigins          = cors,
                RefreshTokenExpiration      = 0,
                SlidingRefreshTokenLifetime = c.SlidingRefreshTokenLifetime,
                Enabled = c.Enabled
            };
            return(Task.FromResult(C));
        }