Exemplo n.º 1
0
        public void Properties_Map()
        {
            var model = new ApiResource()
            {
                Description = "description",
                DisplayName = "displayname",
                Name        = "foo",
                Scopes      = { new Scope("foo1"), new Scope("foo2") },
                Enabled     = false
            };


            var mappedEntity = model.ToEntity();

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

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

            foo2.Should().NotBeNull();


            var mappedModel = mappedEntity.ToModel();

            mappedModel.Description.Should().Be("description");
            mappedModel.DisplayName.Should().Be("displayname");
            mappedModel.Enabled.Should().BeFalse();
            mappedModel.Name.Should().Be("foo");
        }
Exemplo n.º 2
0
        public async Task StoreAsync(Model.ApiResource model)
        {
            var entity = model.ToEntity();

            try
            {
                // Remove old scope indexes
                var existingEntity = await StorageContext.GetEntityBlobAsync <Entities.ApiResource>(entity.Name, StorageContext.ApiResourceBlobContainer);

                if (existingEntity != null &&
                    existingEntity.Scopes != null &&
                    existingEntity.Scopes.Count > 0)
                {
                    //Remove old scope indexes
                    var deleteIndexes = existingEntity?.Scopes?.Select(s => s.Name).Distinct().Select(i => GenerateResourceIndexEntity(entity.Name, i)).ToList();
                    await DeleteScopeIndexesAsync(deleteIndexes, StorageContext.ApiResourceTable);
                }
                // Add new scope indexes
                var newIndexes = entity?.Scopes?.Select(s => s.Name).Distinct().Select(i => GenerateResourceIndexEntity(entity.Name, i)).ToList();
                await CreateScopeIndexesAsync(newIndexes, StorageContext.ApiResourceTable);

                await StorageContext.SaveBlobAsync(entity.Name, JsonConvert.SerializeObject(entity), StorageContext.ApiResourceBlobContainer);
            }
            catch (AggregateException agg)
            {
                ExceptionHelper.LogStorageExceptions(agg, (tblEx) =>
                {
                    _logger.LogWarning("exception updating {apiName} api resource in table storage: {error}", model.Name, tblEx.Message);
                }, (blobEx) =>
                {
                    _logger.LogWarning("exception updating {apiName} api resource in blob storage: {error}", model.Name, blobEx.Message);
                });
                throw;
            }
        }
Exemplo n.º 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();
                }
            }
        }
Exemplo n.º 4
0
        public void Update(ApiResource obj)
        {
            var apiResource = DbSet.FirstOrDefault(w => w.Name == obj.Name);
            var newOne      = obj.ToEntity();

            newOne.Id = apiResource.Id;
            DbSet.Update(newOne);
        }
        public async Task StoreAsync(Model.ApiResource model)
        {
            var entity = model.ToEntity();

            try
            {
                // Remove old scope indexes
                var existingEntity = await StorageContext.GetEntityBlobAsync <Entities.ApiResource>(entity.Name, StorageContext.ApiResourceBlobContainer).ConfigureAwait(false);

                if (existingEntity != null &&
                    existingEntity.Scopes != null &&
                    existingEntity.Scopes.Count > 0)
                {
                    //Remove old scope indexes
                    var deleteIndexes = existingEntity?.Scopes?.Select(s => s.Name).Distinct().Select(i => GenerateResourceIndexEntity(entity.Name, i));
                    await DeleteScopeIndexesAsync(deleteIndexes, StorageContext.ApiResourceTable).ConfigureAwait(false);
                }
                // Add new scope indexes
                var newIndexes = entity?.Scopes?.Select(s => s.Name).Distinct().Select(i => GenerateResourceIndexEntity(entity.Name, i));
                await CreateScopeIndexesAsync(newIndexes, StorageContext.ApiResourceTable).ConfigureAwait(false);

                await StorageContext.SaveBlobWithHashedKeyAsync(entity.Name,
                                                                JsonConvert.SerializeObject(entity), StorageContext.ApiResourceBlobContainer)
                .ConfigureAwait(false);

                //Create ApiScopes that don't exist
                List <string> entityScopes = entity.Scopes?.Select(s => s.Name).ToList();
                if (entityScopes.Count > 0)
                {
                    List <Model.ApiScope> existingApiScopes = (await FindApiScopesByNameAsync(entityScopes).ConfigureAwait(false)).ToList();
                    foreach (string entityScope in entityScopes.Where(w => !String.IsNullOrEmpty(w)).Distinct())
                    {
                        if (!existingApiScopes.Any(a => entityScope.Equals(a.Name, StringComparison.Ordinal)))
                        {
                            await StoreAsync(new Model.ApiScope()
                            {
                                Name = entityScope
                            }).ConfigureAwait(false);
                        }
                    }
                }
                var entities = await GetAllApiResourceEntitiesAsync().ConfigureAwait(false);

                entities = entities.Where(e => entity.Name != e.Name).Concat(new Entities.ApiResource[] { entity });
                await UpdateApiResourceCacheFileAsync(entities).ConfigureAwait(false);
            }
            catch (AggregateException agg)
            {
                ExceptionHelper.LogStorageExceptions(agg, (tblEx) =>
                {
                    _logger.LogWarning("exception updating {apiName} api resource in table storage: {error}", model.Name, tblEx.Message);
                }, (blobEx) =>
                {
                    _logger.LogWarning("exception updating {apiName} api resource in blob storage: {error}", model.Name, blobEx.Message);
                });
                throw;
            }
        }
Exemplo n.º 6
0
        public void Can_Map()
        {
            var model        = new ApiResource();
            var mappedEntity = model.ToEntity();
            var mappedModel  = mappedEntity.ToModel();

            Assert.NotNull(mappedModel);
            Assert.NotNull(mappedEntity);
        }
Exemplo n.º 7
0
        public async Task <bool> AddApiResource(IdentityServer4.Models.ApiResource resource)
        {
            bool Result = false;
            await Context.ApiResources.AddAsync(resource.ToEntity());

            Result = await Context.SaveChangesAsync() > 0;

            return(Result);
        }
 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();
     }
 }
Exemplo n.º 9
0
        public async Task UpdateWithChildrens(string oldName, ApiResource irs)
        {
            var apiDb = await DbSet
                        .Include(s => s.UserClaims)
                        .Where(x => x.Name == oldName).FirstAsync();

            var newIr = irs.ToEntity();

            newIr.Id = apiDb.Id;
            newIr.ShallowCopyTo(apiDb);
        }
        public async Task <MessageModel <string> > SaveData(ApiResourceDto request)
        {
            if (request != null && request.Id == 0)
            {
                IdentityServer4.Models.ApiResource apiResource = new IdentityServer4.Models.ApiResource()
                {
                    Name        = request?.Name,
                    DisplayName = request?.DisplayName,
                    Description = request?.Description,
                    Enabled     = true,
                    UserClaims  = request?.UserClaims?.Split(","),
                };

                var result = (await _configurationDbContext.ApiResources.AddAsync(apiResource.ToEntity()));
                await _configurationDbContext.SaveChangesAsync();
            }

            if (request != null && request.Id > 0)
            {
                var modelEF = (await _configurationDbContext.ApiResources
                               .Include(d => d.UserClaims)
                               .ToListAsync()).FirstOrDefault(d => d.Id == request.Id);

                modelEF.Name        = request?.Name;
                modelEF.DisplayName = request?.DisplayName;
                modelEF.Description = request?.Description;

                var apiResourceClaim = new List <IdentityServer4.EntityFramework.Entities.ApiResourceClaim>();
                if (!string.IsNullOrEmpty(request?.UserClaims))
                {
                    request?.UserClaims.Split(",").Where(s => s != "" && s != null).ToList().ForEach(s =>
                    {
                        apiResourceClaim.Add(new IdentityServer4.EntityFramework.Entities.ApiResourceClaim()
                        {
                            ApiResource   = modelEF,
                            ApiResourceId = modelEF.Id,
                            Type          = s
                        });
                    });
                    modelEF.UserClaims = apiResourceClaim;
                }


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


            return(new MessageModel <string>()
            {
                success = true,
                msg = "添加成功",
            });
        }
        public async Task <IActionResult> Put(string resourceName, [FromBody] IroncladResource model)
        {
            if (string.Equals(resourceName, "auth_api", StringComparison.OrdinalIgnoreCase))
            {
                return(this.BadRequest(new { Message = $"Cannot modify the authorization console web API" }));
            }

            using (var session = this.store.LightweightSession())
            {
                var document = await session.Query <PostgresResource>().SingleOrDefaultAsync(item => item.Name == resourceName);

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

                // 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 resource = new IdentityServerResource
                {
                    UserClaims = model.UserClaims,
                    Scopes     = model.ApiScopes.Select(scope => new Scope(scope.Name, scope.UserClaims)).ToList(),
                };

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

                var entity = resource.ToEntity();

                // update properties (everything supported is an optional update eg. if null is passed we will not update)
                document.DisplayName = model.DisplayName ?? document.DisplayName;
                document.UserClaims  = entity.UserClaims ?? document.UserClaims;
                document.Scopes      = entity.Scopes ?? document.Scopes;
                document.Enabled     = model.Enabled ?? document.Enabled;

                if (!string.IsNullOrEmpty(model.ApiSecret))
                {
                    document.Secrets.Add(entity.Secrets.First());
                }

                session.Update(document);

                await session.SaveChangesAsync();
            }

            return(this.Ok());
        }
Exemplo n.º 12
0
        public IActionResult AddApiResource(ApiResourceViewModel apiResourceViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var apiResource = new ApiResourceModel(apiResourceViewModel.Name, apiResourceViewModel.DisplayName);

            _configurationDbContext.ApiResources.Add(apiResource.ToEntity());
            _configurationDbContext.SaveChanges();

            _trackTelemetry.TrackEvent(EventName.AddApiResource, EventType.Action, EventStatus.Success);
            return(RedirectToAction(nameof(Index)));
        }
        public static void SeedConfiguration(IConfigurationDbContext context)
        {
            Log.Information("Seeding Identity Server configuration");
            if (!context.Clients.Any())
            {
                context.Clients.Add(new Client
                {
                    ClientId   = "spa",
                    ClientName = "SPA Client",
                    ClientUri  = "http://localhost:4200",

                    AllowedGrantTypes           = GrantTypes.Implicit,
                    AllowAccessTokensViaBrowser = true,
                    RequireConsent = false,
                    RedirectUris   =
                    {
                        "http://localhost:4200",
                        "http://localhost:4200/auth-callback",
                        "http://localhost:4200/silent.html",
                    },
                    PostLogoutRedirectUris = { "http://localhost:4200" },
                    AllowedCorsOrigins     = { "http://localhost:4200" },
                    AllowedScopes          = { "openid", "profile", "api" }
                }.ToEntity());
                context.SaveChanges();
            }

            if (!context.IdentityResources.Any())
            {
                context.IdentityResources.AddRange(new IdentityResource[]
                {
                    new IdentityResources.OpenId(),
                    new IdentityResources.Profile()
                }.Select(r => r.ToEntity()));
                context.SaveChanges();
            }

            if (!context.ApiResources.Any())
            {
                var apiResource = new ApiResource("api", "Application api");
                context.ApiResources.Add(apiResource.ToEntity());
                context.SaveChanges();
            }
        }
        public async Task <IActionResult> Post([FromBody] IroncladResource model)
        {
            if (string.IsNullOrEmpty(model.Name))
            {
                return(this.BadRequest(new { Message = $"Cannot create an API resource without a name" }));
            }

            if (string.IsNullOrEmpty(model.ApiSecret))
            {
                return(this.BadRequest(new { Message = $"Cannot create an API resource without a secret" }));
            }

            var resource = new IdentityServerResource(model.Name, model.DisplayName)
            {
                ApiSecrets = new List <Secret> {
                    new Secret(model.ApiSecret.Sha256())
                },
            };

            // optional properties
            resource.UserClaims = model.UserClaims ?? resource.UserClaims;
            resource.Scopes     = model.ApiScopes?.Select(item => new Scope(item.Name, item.UserClaims)).ToList() ?? resource.Scopes;
            resource.Enabled    = model.Enabled ?? resource.Enabled;

            using (var session = this.store.LightweightSession())
            {
                if (session.Query <PostgresResource>().Any(document => document.Name == model.Name))
                {
                    return(this.StatusCode((int)HttpStatusCode.Conflict, new { Message = "API resource already exists" }));
                }

                session.Insert(resource.ToEntity());

                await session.SaveChangesAsync();
            }

            return(this.Created(new Uri(this.HttpContext.GetIdentityServerRelativeUrl("~/api/apiresources/" + model.Name)), null));
        }
Exemplo n.º 15
0
 public void Add(ApiResource obj)
 {
     DbSet.Add(obj.ToEntity());
 }
Exemplo n.º 16
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);
        }