Ejemplo n.º 1
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                LoadLookups();
                return(Page());
            }

            ApiResource apiResource;
            var         isNew = ApiResource.Id == 0;

            if (isNew)
            {
                apiResource = ApiResource.ToEntity();
                await _dbContext.ApiResources.AddAsync(apiResource);
            }
            else
            {
                apiResource = await LoadApiResource(ApiResource.Id);

                ApiResource.ToEntity(apiResource);
            }

            await _dbContext.SaveChangesAsync();

            return(isNew
                ? RedirectToPage("/ApiResources/Edit", new { id = apiResource.Id })
                : RedirectToPage("/ApiResources/Index"));
        }
        public async Task GetAllResources_WhenAllResourcesRequested_ExpectAllResourcesIncludingHidden()
        {
            var storeHolder = GetConfigurationDocumentStoreHolder();

            var visibleIdentityResource = CreateIdentityTestResource();
            var visibleApiResource      = CreateApiResourceTestResource();
            var visibleApiScope         = CreateApiScopeTestResource();
            var hiddenIdentityResource  = new IdentityResource
            {
                Name = Guid.NewGuid().ToString(), ShowInDiscoveryDocument = false
            };
            var hiddenApiResource = new ApiResource
            {
                Name   = Guid.NewGuid().ToString(),
                Scopes = { Guid.NewGuid().ToString() },
                ShowInDiscoveryDocument = false
            };
            var hiddenApiScope = new ApiScope
            {
                Name = Guid.NewGuid().ToString(),
                ShowInDiscoveryDocument = false
            };

            using (var session = storeHolder.OpenAsyncSession())
            {
                await session.StoreAsync(visibleIdentityResource.ToEntity());

                await session.StoreAsync(visibleApiResource.ToEntity());

                await session.StoreAsync(visibleApiScope.ToEntity());

                await session.StoreAsync(hiddenIdentityResource.ToEntity());

                await session.StoreAsync(hiddenApiResource.ToEntity());

                await session.StoreAsync(hiddenApiScope.ToEntity());

                await session.SaveChangesAsync();
            }

            WaitForIndexing(storeHolder.IntegrationTest_GetDocumentStore());
            WaitForUserToContinueTheTest(storeHolder.IntegrationTest_GetDocumentStore());

            var store     = new ResourceStore(storeHolder, FakeLogger <ResourceStore> .Create());
            var resources = await store.GetAllResourcesAsync();

            Assert.NotNull(resources);
            Assert.NotEmpty(resources.IdentityResources);
            Assert.NotEmpty(resources.ApiResources);
            Assert.NotEmpty(resources.ApiScopes);

            Assert.Contains(resources.IdentityResources, x => x.Name == visibleIdentityResource.Name);
            Assert.Contains(resources.IdentityResources, x => x.Name == hiddenIdentityResource.Name);

            Assert.Contains(resources.ApiResources, x => x.Name == visibleApiResource.Name);
            Assert.Contains(resources.ApiResources, x => x.Name == hiddenApiResource.Name);

            Assert.Contains(resources.ApiScopes, x => x.Name == visibleApiScope.Name);
            Assert.Contains(resources.ApiScopes, x => x.Name == hiddenApiScope.Name);
        }
        public void Properties_Map()
        {
            ApiResource model = new ApiResource
            {
                Description = "description",
                DisplayName = "displayname",
                Name        = "foo",
                Scopes      = { "foo1", "foo2" },
                Enabled     = false
            };

            Entities.ApiResource mappedEntity = model.ToEntity();

            mappedEntity.Scopes.Count.Should().Be(2);
            string foo1 = mappedEntity.Scopes.FirstOrDefault(x => x == "foo1");

            foo1.Should().NotBeNull();
            string foo2 = mappedEntity.Scopes.FirstOrDefault(x => x == "foo2");

            foo2.Should().NotBeNull();


            ApiResource mappedModel = mappedEntity.ToModel();

            mappedModel.Description.Should().Be("description");
            mappedModel.DisplayName.Should().Be("displayname");
            mappedModel.Enabled.Should().BeFalse();
            mappedModel.Name.Should().Be("foo");
        }
        public static void SeedResource(this IApplicationBuilder app)
        {
            using var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope();

            var context = serviceScope.ServiceProvider.GetRequiredService <ConfigurationDBContext>();

            if (!context.ApiResources.Any())
            {
                var catalogRes = new ApiResource("catalog", "Catalog API");
                context.ApiResources.Add(catalogRes.ToEntity());

                var accountsRes = new ApiResource("accounts", "Account API");
                context.ApiResources.Add(accountsRes.ToEntity());

                var localRes = new ApiResource(IdentityServerConstants.LocalApi.ScopeName, "IS4 Local API");
                context.ApiResources.Add(localRes.ToEntity());

                context.SaveChanges();
            }

            if (!context.ApiScopes.Any())
            {
                var apiResource = new ApiScope("trainers", "Trainers Services");
                context.ApiScopes.Add(apiResource.ToEntity());
                context.SaveChanges();
            }
        }
Ejemplo n.º 5
0
        public void UpdateClaimsByApiResourceId(ApiResource apiResource)
        {
            var dbitem = GetByName(apiResource.Name);

            if (dbitem == null)
            {
                throw new InvalidOperationException($"could not update ApiResource {apiResource.Name} not existed");
            }
            var entity = apiResource.ToEntity();

            entity.Id = dbitem.Id;
            using (var con = _options.DbProviderFactory.CreateConnection())
            {
                con.ConnectionString = _options.ConnectionString;
                con.Open();
                var t = con.BeginTransaction();

                try
                {
                    UpdateClaimsByApiResourceId(entity.UserClaims, dbitem.Id, con, t);
                    t.Commit();
                }
                catch (Exception ex)
                {
                    t.Rollback();
                    throw ex;
                }
            }
        }
Ejemplo n.º 6
0
        public void Add(ApiResource apiResource)
        {
            var dbapiResource = FindApiResource(apiResource.Name);

            if (dbapiResource != null)
            {
                throw new InvalidOperationException($"you can not add an existed ApiResource,Name={apiResource.Name}.");
            }

            var entity = apiResource.ToEntity();

            using (var con = _options.DbProviderFactory.CreateConnection())
            {
                con.ConnectionString = _options.ConnectionString;
                con.Open();
                using (var t = con.BeginTransaction())
                {
                    try
                    {
                        string left  = _options.ColumnProtect["left"];
                        string right = _options.ColumnProtect["right"];

                        var apiid = con.ExecuteScalar <int>($"insert into ApiResources ({left}Description{right},DisplayName,Enabled,{left}Name{right}) values (@Description,@DisplayName,@Enabled,@Name);{_options.GetLastInsertID}", new
                        {
                            entity.Description,
                            entity.DisplayName,
                            entity.Enabled,
                            entity.Name
                        }, commandTimeout: _options.CommandTimeOut, commandType: CommandType.Text, transaction: t);
                        entity.Id = apiid;

                        if (entity.UserClaims != null && entity.UserClaims.Count() > 0)
                        {
                            foreach (var item in entity.UserClaims)
                            {
                                InsertApiResourceClaim(item, entity.Id, con, t);
                            }
                        }
                        if (entity.Secrets != null && entity.Secrets.Count() > 0)
                        {
                            foreach (var item in entity.Secrets)
                            {
                                InsertApiSecretsByApiResourceId(item, apiid, con, t);
                            }
                        }
                        if (entity.Scopes != null && entity.Scopes.Count() > 0)
                        {
                            InsertApiScopeByApiResourceId(entity.Scopes, entity.Id, con, t);
                        }
                        t.Commit();
                    }
                    catch (Exception ex)
                    {
                        t.Rollback();
                        throw ex;
                    }
                }
            }
        }
Ejemplo n.º 7
0
        public async Task AddAsync(ApiResource apiResource)
        {
            var apiResourceEntity = apiResource.ToEntity();

            await this._configurationDbContext.ApiResources.AddAsync(apiResourceEntity);

            await this._configurationDbContext.SaveChangesAsync();
        }
Ejemplo n.º 8
0
        public async Task CreateApiResource(string siteId, ApiResource apiResource, CancellationToken cancellationToken = default(CancellationToken))
        {
            var ent = apiResource.ToEntity();

            ent.SiteId = siteId;
            context.ApiResources.Add(ent);
            await context.SaveChangesAsync();
        }
Ejemplo n.º 9
0
 public Task Create(ApiResource resouce)
 {
     if (resouce == null)
     {
         throw new ArgumentNullException(nameof(resouce));
     }
     State.ApiResource = resouce.ToEntity();
     return(WriteStateAsync());
 }
Ejemplo n.º 10
0
        public void CanMapApiResources()
        {
            var model        = new ApiResource();
            var mappedEntity = model.ToEntity();
            var mappedModel  = mappedEntity.ToModel();

            Assert.NotNull(mappedModel);
            Assert.NotNull(mappedEntity);
        }
Ejemplo n.º 11
0
        public async Task <int> AddApiResourceAsync(ApiResource resource)
        {
            var result = await this._configContext.ApiResources.AddAsync(resource.ToEntity());

            await this._configContext.SaveChangesAsync();

            resource = result.Entity.ToModel();

            return(result.Entity.Id);
        }
        public void Can_Map()
        {
            ApiResource model = new ApiResource();

            Entities.ApiResource mappedEntity = model.ToEntity();
            ApiResource          mappedModel  = mappedEntity.ToModel();

            Assert.NotNull(mappedModel);
            Assert.NotNull(mappedEntity);
        }
        public void ApiResourceAutomapperConfigurationIsValid()
        {
            var model        = new ApiResource();
            var mappedEntity = model.ToEntity();
            var mappedModel  = mappedEntity.ToModel();

            Assert.NotNull(mappedModel);
            Assert.NotNull(mappedEntity);
            ApiResourceMappers.Mapper.ConfigurationProvider.AssertConfigurationIsValid();
        }
Ejemplo n.º 14
0
        public async Task GetAllResources_WhenAllResourcesRequested_ExpectAllResourcesIncludingHidden(DbContextOptions <ConfigurationDbContext> options)
        {
            var visibleIdentityResource = CreateIdentityTestResource();
            var visibleApiResource      = CreateApiResourceTestResource();
            var visibleApiScope         = CreateApiScopeTestResource();
            var hiddenIdentityResource  = new IdentityResource {
                Name = Guid.NewGuid().ToString(), ShowInDiscoveryDocument = false
            };
            var hiddenApiResource = new ApiResource
            {
                Name   = Guid.NewGuid().ToString(),
                Scopes = { Guid.NewGuid().ToString() },
                ShowInDiscoveryDocument = false
            };
            var hiddenApiScope = new ApiScope
            {
                Name = Guid.NewGuid().ToString(),
                ShowInDiscoveryDocument = false
            };

            using (var context = new ConfigurationDbContext(options, StoreOptions))
            {
                context.IdentityResources.Add(visibleIdentityResource.ToEntity());
                context.ApiResources.Add(visibleApiResource.ToEntity());
                context.ApiScopes.Add(visibleApiScope.ToEntity());

                context.IdentityResources.Add(hiddenIdentityResource.ToEntity());
                context.ApiResources.Add(hiddenApiResource.ToEntity());
                context.ApiScopes.Add(hiddenApiScope.ToEntity());

                context.SaveChanges();
            }

            Resources resources;

            using (var context = new ConfigurationDbContext(options, StoreOptions))
            {
                var store = new ResourceStore(context, FakeLogger <ResourceStore> .Create());
                resources = await store.GetAllResourcesAsync();
            }

            Assert.NotNull(resources);
            Assert.NotEmpty(resources.IdentityResources);
            Assert.NotEmpty(resources.ApiResources);
            Assert.NotEmpty(resources.ApiScopes);

            Assert.Contains(resources.IdentityResources, x => x.Name == visibleIdentityResource.Name);
            Assert.Contains(resources.IdentityResources, x => x.Name == hiddenIdentityResource.Name);

            Assert.Contains(resources.ApiResources, x => x.Name == visibleApiResource.Name);
            Assert.Contains(resources.ApiResources, x => x.Name == hiddenApiResource.Name);

            Assert.Contains(resources.ApiScopes, x => x.Name == visibleApiScope.Name);
            Assert.Contains(resources.ApiScopes, x => x.Name == hiddenApiScope.Name);
        }
Ejemplo n.º 15
0
        public async Task <OperationResult <ApiResource> > AddAsync(ApiResource apiResource)
        {
            var entity = apiResource.ToEntity();
            await _apiResourceRepository.AddAsync(entity);

            await _unitOfWork.SaveChangesAsync();

            return(new OperationResult <ApiResource>
            {
                Data = entity.ToModel(), IsSuccessful = true
            });
        }
Ejemplo n.º 16
0
        public async Task StoreAsync(ApiResource model)
        {
            Guard.ForNull(model, nameof(model));
            Guard.ForNull(model.Name, nameof(model.Name));
            var entity   = model.ToEntity();
            var response = await _apiResourceGrantCosmosStore.UpsertAsync(entity);

            if (!response.IsSuccess)
            {
                _logger.LogCritical("Could not store ApiResource");
            }
        }
Ejemplo n.º 17
0
        public static void SeedApiResource(this IApplicationBuilder app)
        {
            using var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope();

            var context = serviceScope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();

            if (!context.ApiResources.Any())
            {
                var apiResource = new ApiResource("payment", "Payment API");
                context.ApiResources.Add(apiResource.ToEntity());
                context.SaveChanges();
            }
        }
Ejemplo n.º 18
0
        public async Task GetAllResources_WhenAllResourcesRequested_ExpectAllResourcesIncludingHidden()
        {
            var visibleIdentityResource = CreateIdentityTestResource();
            var visibleApiResource      = CreateApiResourceTestResource();
            var visibleApiScope         = CreateApiScopeTestResource();
            var hiddenIdentityResource  = new IdentityResource {
                Name = Guid.NewGuid().ToString(), ShowInDiscoveryDocument = false
            };
            var hiddenApiResource = new ApiResource
            {
                Name   = Guid.NewGuid().ToString(),
                Scopes = { Guid.NewGuid().ToString() },
                ShowInDiscoveryDocument = false
            };
            var hiddenApiScope = new ApiScope
            {
                Name = Guid.NewGuid().ToString(),
                ShowInDiscoveryDocument = false
            };

            await _context.IdentityResources.AddAsync(visibleIdentityResource.ToEntity());

            await _context.ApiResources.AddAsync(visibleApiResource.ToEntity());

            await _context.ApiScopes.AddAsync(visibleApiScope.ToEntity());

            await _context.IdentityResources.AddAsync(hiddenIdentityResource.ToEntity());

            await _context.ApiResources.AddAsync(hiddenApiResource.ToEntity());

            await _context.ApiScopes.AddAsync(hiddenApiScope.ToEntity());

            Resources resources;
            var       store = new ResourceStore(_context, FakeLogger <ResourceStore> .Create());

            resources = await store.GetAllResourcesAsync();

            Assert.NotNull(resources);
            Assert.NotEmpty(resources.IdentityResources);
            Assert.NotEmpty(resources.ApiResources);
            Assert.NotEmpty(resources.ApiScopes);

            Assert.Contains(resources.IdentityResources, x => x.Name == visibleIdentityResource.Name);
            Assert.Contains(resources.IdentityResources, x => x.Name == hiddenIdentityResource.Name);

            Assert.Contains(resources.ApiResources, x => x.Name == visibleApiResource.Name);
            Assert.Contains(resources.ApiResources, x => x.Name == hiddenApiResource.Name);

            Assert.Contains(resources.ApiScopes, x => x.Name == visibleApiScope.Name);
            Assert.Contains(resources.ApiScopes, x => x.Name == hiddenApiScope.Name);
        }
        public void ToEntity_MapsAllowedAccessTokenSigningAlgorithms()
        {
            var apiResource = new ApiResource
            {
                AllowedAccessTokenSigningAlgorithms = new List <string>
                {
                    "HS256", "ES256"
                }
            };

            var entity = apiResource.ToEntity();

            var expectedSigningAlgorithms = "HS256,ES256";

            Assert.Equal(expectedSigningAlgorithms, entity.AllowedAccessTokenSigningAlgorithms);
        }
Ejemplo n.º 20
0
        public async Task CreateApiResource(string siteId, ApiResource apiResource, CancellationToken cancellationToken = default(CancellationToken))
        {
            var ent = apiResource.ToEntity();

            ent.SiteId = siteId;
            foreach (var s in ent.Scopes)
            {
                s.SiteId = siteId;
            }

            using (var context = _contextFactory.CreateContext())
            {
                context.ApiResources.Add(ent);
                await context.SaveChangesAsync();
            }
        }
Ejemplo n.º 21
0
        public void UpdateApiSecretsByApiResourceId(ApiResource apiResource)
        {
            var entity = apiResource.ToEntity();
            var dbitem = GetByName(apiResource.Name);

            if (dbitem == null)
            {
                throw new InvalidOperationException($"could not update ApiSecrets for {apiResource.Name} which not exists.");
            }
            entity.Id = dbitem.Id;
            using (var con = _options.DbProviderFactory.CreateConnection())
            {
                con.ConnectionString = _options.ConnectionString;
                UpdateApiSecretsByApiResourceId(entity.Secrets, entity.Id, null, null);
            }
        }
Ejemplo n.º 22
0
 public ActionResult Create(IFormCollection collection)
 {
     try
     {
         //IdentityServer4.EntityFramework.Entities.ApiResource
         string name        = collection["Name"];
         string displayName = collection["DisplayName"];
         var    api         = new ApiResource(name, displayName);
         _context.ApiResources.Add(api.ToEntity());
         _context.SaveChanges();
         return(RedirectToAction(nameof(Index)));
     }
     catch
     {
         return(View());
     }
 }
        private void InitializeClientsAndScopes()
        {
            if (cfgDbContext.Clients.FirstOrDefault() == null)
            {
                var mainOrg = dbContext.Organizations.FirstOrDefault(p => !p.ParentId.HasValue);
                if (mainOrg == null)
                {
                    throw new System.Exception("Main organization not set");
                }
                foreach (var client in config.GetClients())
                {
                    // HOTFIX
                    // TODO: move to configuration
                    client.AllowedGrantTypes = GrantTypes.HybridAndClientCredentials;
                    var clientEntity = client.ToEntity();
                    cfgDbContext.Clients.Add(clientEntity);
                    mainOrg.OrganizationClients = new System.Collections.Generic.List <Models.OrganizationClient>();
                    mainOrg.OrganizationClients.Add(new Models.OrganizationClient()
                    {
                        ClientId = clientEntity.Id
                    });
                }
                cfgDbContext.SaveChanges();
                dbContext.SaveChanges();
            }

            if (cfgDbContext.ApiResources.FirstOrDefault() == null)
            {
                foreach (var apiResource in config.GetApiResources())
                {
                    var resource = new ApiResource(apiResource.Name, apiResource.DisplayName);
                    cfgDbContext.ApiResources.Add(resource.ToEntity());
                }
                cfgDbContext.SaveChanges();
            }

            if (cfgDbContext.IdentityResources.FirstOrDefault() == null)
            {
                foreach (var identityResource in config.GetIdentityResources())
                {
                    cfgDbContext.IdentityResources.Add(identityResource.ToEntity());
                }
                cfgDbContext.SaveChanges();
            }
        }
Ejemplo n.º 24
0
        public async Task <IActionResult> CreateAsync([FromBody] CreateApiResourceDto dto)
        {
            if (await _dbContext.ApiResources.AnyAsync(u => u.Name == dto.Name))
            {
                return(new ApiResult(ApiResultType.Error, "资源名已经存在"));
            }

            var apiResource = new ApiResource(dto.Name, dto.DisplayName, dto.UserClaims)
            {
                Enabled = dto.Enabled, Description = dto.Description
            };
            var entity = apiResource.ToEntity();
            await _dbContext.ApiResources.AddAsync(entity);

            await _dbContext.SaveChangesAsync();

            return(ApiResult.Ok);
        }
Ejemplo n.º 25
0
        private static void SeedAdminClient(string adminApiName, string clientId, string clientSecret, ConfigurationDbContext configContext)
        {
            if (!configContext.IdentityResources.Any())
            {
                foreach (var resource in DefaultData.IdentityResources)
                {
                    configContext.IdentityResources.Add(resource.ToEntity());
                }
            }

            if (!configContext.ApiResources.Any())
            {
                var apiResource = new ApiResource(adminApiName, "Identity Server Admin");
                configContext.ApiResources.Add(apiResource.ToEntity());
            }

            if (!configContext.Clients.Any())
            {
                var adminClient = new Client
                {
                    ClientName    = "Identity Server Admin",
                    ClientId      = clientId,
                    ClientSecrets =
                    {
                        new Secret(clientSecret.Sha256())
                    },
                    AllowedScopes =
                    {
                        adminApiName
                    },
                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    Claims            =
                    {
                        new Claim(AdminClientClaims.ManageUsersType,   AdminClientClaims.ManageUsersValue),
                        new Claim(AdminClientClaims.ManageClientsType, AdminClientClaims.ManageClientsValue)
                    },
                    ClientClaimsPrefix = null
                };

                configContext.Clients.Add(adminClient.ToEntity());
            }

            configContext.SaveChanges();
        }
Ejemplo n.º 26
0
        public void map_ApiResource_to_Entity()
        {
            var model = new ApiResource
            {
                DisplayName = NewGuidS,
                Description = NewGuidS,
                Enabled     = true,
                Name        = NewGuidS,
                UserClaims  = new List <string> {
                    NewGuidS
                },
                Scopes = new List <Scope> {
                    new Scope(NewGuidS, NewGuidS, new List <string> {
                        NewGuidS
                    })
                    {
                        Description             = NewGuidS,
                        Emphasize               = true,
                        Required                = true,
                        ShowInDiscoveryDocument = true
                    }
                },
                ApiSecrets = new List <Secret> {
                    new Secret
                    {
                        Value       = NewGuidS,
                        Description = NewGuidS,
                        Type        = NewGuidS,
                        Expiration  = DateTime.UtcNow
                    }
                },
                Properties = new Dictionary <string, string>()
                {
                    { NewGuidS, NewGuidS }
                }
            };
            var entity = model.ToEntity();


            var actual = entity.ToModel();

            model.DeepCompare(actual).Should().BeTrue();
        }
Ejemplo n.º 27
0
        private void InitializeDatabase(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 client = new Client
                    {
                        ClientId          = "TestClientForPhotoLake",
                        AllowedGrantTypes = GrantTypes.ClientCredentials,
                        ClientSecrets     =
                        {
                            // This needs to comes from azure vault.

                            new Secret("testclientphotolake".Sha256())
                        },
                        AllowedScopes = { "PhotoLakeAPI" }
                    };

                    context.Clients.Add(client.ToEntity());
                    context.SaveChanges();
                }

                if (!context.IdentityResources.Any())
                {
                    var resource = new IdentityResources.OpenId();
                    context.IdentityResources.Add(resource.ToEntity());
                    context.SaveChanges();
                }

                if (!context.ApiResources.Any())
                {
                    var apiResource = new ApiResource("PhotoLakeAPI", "The API for upload photo to Photo Lake APP");
                    context.ApiResources.Add(apiResource.ToEntity());
                    context.SaveChanges();
                }
            }
        }
Ejemplo n.º 28
0
        public void Update(ApiResource apiResource)
        {
            var dbitem = GetByName(apiResource.Name);

            if (dbitem == null)
            {
                throw new InvalidOperationException($"you can not update an unexisted ApiResource,Name={apiResource.Name}.");
            }
            var entity = apiResource.ToEntity();

            entity.Id = dbitem.Id;
            using (var con = _options.DbProviderFactory.CreateConnection())
            {
                con.ConnectionString = _options.ConnectionString;
                con.Open();
                using (var t = con.BeginTransaction())
                {
                    try
                    {
                        var ret = con.Execute($"update ApiResources set {left}Description{right} = @Description," +
                                              $"DisplayName=@DisplayName," +
                                              $"Enabled=@Enabled," +
                                              $"{left}Name{right}=@Name where Id=@Id;", entity, commandTimeout: _options.CommandTimeOut, commandType: CommandType.Text, transaction: t);

                        UpdateScopesByApiResourceId(entity.Scopes, entity.Id, con, t);
                        UpdateApiSecretsByApiResourceId(entity.Secrets, entity.Id, con, t);
                        UpdateClaimsByApiResourceId(entity.UserClaims, entity.Id, con, t);
                        t.Commit();
                    }
                    catch (Exception ex)
                    {
                        t.Rollback();
                        throw ex;
                    }
                }
            }

            var key = "apiresource." + apiResource.Name;

            _cache.Remove(key);
        }
Ejemplo n.º 29
0
        public void GetAllResources_WhenAllResourcesRequested_ExpectAllResourcesIncludingHidden(DbContextOptions <ConfigurationDbContext> options)
        {
            var visibleIdentityResource = CreateIdentityTestResource();
            var visibleApiResource      = CreateApiTestResource();
            var hiddenIdentityResource  = new IdentityResource {
                Name = Guid.NewGuid().ToString(), ShowInDiscoveryDocument = false
            };
            var hiddenApiResource = new ApiResource
            {
                Name   = Guid.NewGuid().ToString(),
                Scopes = new List <Scope> {
                    new Scope {
                        Name = Guid.NewGuid().ToString(), ShowInDiscoveryDocument = false
                    }
                }
            };

            using (var context = new ConfigurationDbContext(options, StoreOptions))
            {
                context.IdentityResources.Add(visibleIdentityResource.ToEntity());
                context.ApiResources.Add(visibleApiResource.ToEntity());
                context.IdentityResources.Add(hiddenIdentityResource.ToEntity());
                context.ApiResources.Add(hiddenApiResource.ToEntity());
                context.SaveChanges();
            }

            Resources resources;

            using (var context = new ConfigurationDbContext(options, StoreOptions))
            {
                var store = new ResourceStore(context, FakeLogger <ResourceStore> .Create());
                resources = store.GetAllResourcesAsync().Result;
            }

            Assert.NotNull(resources);
            Assert.NotEmpty(resources.IdentityResources);
            Assert.NotEmpty(resources.ApiResources);

            Assert.True(resources.IdentityResources.Any(x => !x.ShowInDiscoveryDocument));
            Assert.True(resources.ApiResources.Any(x => !x.Scopes.Any(y => y.ShowInDiscoveryDocument)));
        }
Ejemplo n.º 30
0
        /// <summary>
        /// 创建新的Api Resource
        /// </summary>
        /// <param name="apiResourceCreateViewModel"></param>
        /// <returns></returns>
        private async Task <ApiResource> CreateApiResource(string name, string displayName)
        {
            var query = _configurationContext.ApiResources.Where(a => a.Name == name).FirstOrDefaultAsync();

            if (query == null)
            {
                return(null);
            }
            var apiResource = new ApiResource(name, displayName);

            _configurationContext.ApiResources.Add(apiResource.ToEntity());
            try
            {
                await _configurationContext.SaveChangesAsync();

                return(apiResource);
            }
            catch (Exception)
            {
                return(null);
            }
        }