Exemplo n.º 1
0
        private static IEnumerable <IdentityResource> CreateIdentityResources(
            ModIdentityServerBaseConfigEnumIdentityResources[] configSettings
            )
        {
            var result = new List <IdentityResource>();

            foreach (var configSetting in configSettings)
            {
                IdentityResource item = null;

                switch (configSetting)
                {
                case ModIdentityServerBaseConfigEnumIdentityResources.OpenId:
                    item = new IdentityResources.OpenId();
                    break;
                }

                if (item != null)
                {
                    result.Add(item);
                }
            }

            return(result);
        }
        // scopes define the resources in your system
        private static IEnumerable <IdentityResource> GetIdentityResources()
        {
            var openId = new IdentityResources.OpenId();

            openId.DisplayName = "用户标识";
            var profile = new IdentityResources.Profile
            {
                DisplayName = "基本信息: 如姓名、角色等", Description = ""
            };

            profile.UserClaims.Add(JwtClaimTypes.Role);

            var fullProfile = new IdentityResources.Profile
            {
                Name = "full_profile", DisplayName = "完整信息: 如姓名、角色、电话、邮件、公司信息等", Description = ""
            };

            fullProfile.UserClaims.Add(JwtClaimTypes.Role);
            fullProfile.UserClaims.Add(JwtClaimTypes.PhoneNumber);
            fullProfile.UserClaims.Add(JwtClaimTypes.Email);
            fullProfile.UserClaims.Add("title");
            fullProfile.UserClaims.Add("group");
            fullProfile.UserClaims.Add("level");
            fullProfile.UserClaims.Add("office_phone");
            fullProfile.UserClaims.Add("full_name");
            return(new List <IdentityResource>
            {
                openId,
                profile,
                fullProfile
            });
        }
Exemplo n.º 3
0
        public static IEnumerable <IdentityResource> GetIdentityResources()
        {
            var identityResources = new List <IdentityResource>();
            var identityResource  = new IdentityResources.OpenId();

            identityResources.Add(identityResource);
            return(identityResources);
        }
Exemplo n.º 4
0
        public IActionResult AddGeneralScope()
        {
            var ir  = new IdentityResources.OpenId();
            var ir2 = new IdentityResources.Profile();

            _confContext.IdentityResources.Add(ir.ToEntity());
            _confContext.IdentityResources.Add(ir2.ToEntity());
            _confContext.SaveChanges();

            return(Ok());
        }
        public static List <IdentityResource> GetIdentityResources()
        {
            var openIdScope = new IdentityResources.OpenId();

            return(new List <IdentityResource>
            {
                openIdScope,
                new IdentityResources.Profile(),
                new IdentityResources.Email()
            });
        }
Exemplo n.º 6
0
        public static IEnumerable <IdentityResource> GetIdentityResources()
        {
            var openid = new IdentityResources.OpenId();

            openid.UserClaims.Add("role");

            return(new List <IdentityResource>
            {
                openid,
                new IdentityResources.Profile()
            });
        }
Exemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <ICorsPolicyService, CustomCorsPolicyService>();
            services.AddSingleton <IRedirectUriValidator, CustomRedirectUriValidator>();
            services.AddSingleton <IClientStore, CustomClientStore>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            var openIdResource = new IdentityResources.OpenId();

            openIdResource.UserClaims.Add(JwtClaimTypes.Address);
            openIdResource.UserClaims.Add(JwtClaimTypes.Name);

            services.AddIdentityServer()
            .AddInMemoryIdentityResources(new List <IdentityResource>
            {
                openIdResource,
                new IdentityResources.Email()
            })
            .AddInMemoryApiResources(new List <ApiResource>
            {
                new ApiResource("api1", "My API")
            })
            .AddTestUsers(new List <TestUser>
            {
                new TestUser
                {
                    SubjectId = "818727",
                    Username  = "******",
                    Password  = "******",
                    Claims    = new List <Claim>()
                    {
                        new Claim(JwtClaimTypes.Name, "liza"),
                        new Claim(JwtClaimTypes.Subject, "818727")
                    }
                },
                new TestUser
                {
                    SubjectId = "818729",
                    Username  = "******",
                    Password  = "******",
                    Claims    = new List <Claim>()
                    {
                        new Claim(JwtClaimTypes.Name, "hummingbird"),
                        new Claim(JwtClaimTypes.Subject, "818729")
                    }
                },
            })
            .AddDeveloperSigningCredential()
            .AddProfileService <CustomProfileService>();
        }
        /// <summary>
        /// 转换为Identity资源数组
        /// </summary>
        /// <param name="identityResources">Identity资源信息数组</param>
        /// <returns>Identity资源数组</returns>
        public static IdentityResource[] ToIdentityResources(this IdentityResourceInfo[] identityResources)
        {
            if (identityResources.IsNullOrLength0())
            {
                return(null);
            }

            var result = new IdentityResource[identityResources.Length];

            for (var i = 0; i < result.Length; i++)
            {
                var source = identityResources[i];
                var type   = source.Type != null?source.Type.ToLower() : null;

                if ("openid".Equals(type))
                {
                    result[i] = new IdentityResources.OpenId();
                }
                else if ("profile".Equals(type))
                {
                    result[i] = new IdentityResources.Profile();
                }
                else if ("address".Equals(type))
                {
                    result[i] = new IdentityResources.Address();
                }
                else if ("email".Equals(type))
                {
                    result[i] = new IdentityResources.Email();
                }
                else if ("phone".Equals(type))
                {
                    result[i] = new IdentityResources.Phone();
                }
                else
                {
                    result[i] = new IdentityResource(source.Name, source.DisplayName, source.UserClaims);
                }

                result[i].Description             = source.Description;
                result[i].Enabled                 = source.Enabled;
                result[i].Emphasize               = source.Emphasize;
                result[i].Required                = source.Required;
                result[i].ShowInDiscoveryDocument = source.ShowInDiscoveryDocument;
            }

            return(result);
        }
        public List <IdentityResource> GetIdentityResources()
        {
            var openIdResource = new IdentityResources.OpenId();

            openIdResource.UserClaims.Add("role");

            var profileResource = new IdentityResources.Profile();

            profileResource.UserClaims.Add("role");

            return(new List <IdentityResource>
            {
                openIdResource,
                profileResource
            });
        }
Exemplo n.º 10
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();
                }
            }
        }
Exemplo n.º 11
0
        public Task IsActiveAsync(IsActiveContext context)
        {
            //client verification

            var openId   = new IdentityResources.OpenId();
            var subClaim = openId.UserClaims.First();

            var sub = context.Subject.Claims.FirstOrDefault(x => x.Type == subClaim); //identityuser ID

            if (sub == null)
            {
                context.IsActive = false;
                return(Task.FromResult(context));
            }

            context.IsActive = _userIdentityService.IsUserIdentityActive(int.Parse(sub.Value));

            return(Task.CompletedTask);
        }
Exemplo n.º 12
0
        public Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var openId   = new IdentityResources.OpenId();
            var subClaim = openId.UserClaims.First();

            var sub = context.Subject.Claims.FirstOrDefault(x => x.Type == subClaim); //identityuser ID

            if (sub == null)
            {
                throw new Exception(); //todo exception
            }
            var userIdentity = _userIdentityService.GetUserIdentity(int.Parse(sub.Value));

            var claims = ClaimTypeHelper.GetRequiredClaimsFromObject(userIdentity, context.RequestedClaimTypes.ToList());

            context.IssuedClaims.AddRange(claims.ToList());

            return(Task.CompletedTask);
        }
        public void TestAdd(string sqltype)
        {
            var provider = GetDefaultIdentityResourceProvider(sqltype);
            var openid   = new IdentityResources.OpenId()
            {
                Name        = "OpenID",
                DisplayName = "OpenID",
                Description = "OpenID"
            };

            var dbidentity = provider.FindIdentityResourcesByName(openid.Name);

            if (dbidentity == null)
            {
                provider.Add(openid);
            }
            dbidentity = provider.FindIdentityResourcesByName(openid.Name);
            Assert.False(dbidentity == null);
        }
Exemplo n.º 14
0
        public ResourceStore()
        {
            apiResources["https://example.com/api"] =
                new ApiResource("https://example.com/api")
            {
                UserClaims = { JwtClaimTypes.Email },
                Scopes     =
                {
                    new Scope {
                        Name = "read:product", DisplayName = "Read access to product data"
                    }
                }
            };

            identityResources["openid"]  = new IdentityResources.OpenId();
            identityResources["email"]   = new IdentityResources.Email();
            identityResources["address"] = new IdentityResources.Address();
            identityResources["phone"]   = new IdentityResources.Phone();
            identityResources["profile"] = new IdentityResources.Profile();
        }
Exemplo n.º 15
0
        public static IEnumerable <IdentityResource> GetIdentityResources()
        {
            var openIdScope = new IdentityResources.OpenId();

            openIdScope.UserClaims.Add(JwtClaimTypes.Locale);

            return(new List <IdentityResource>
            {
                openIdScope,
                //new IdentityResources.OpenId(),
                new IdentityResources.Email(),
                new IdentityResources.Profile(),
                //new IdentityResource(Constants.RolesScopeType, Constants.RolesScopeType,
                //new List<string> {JwtClaimTypes.Role, Constants.TenantIdClaimType})
                //{
                //    //when false (default), the user can deselect the scope on consent screen
                //    Required = true
                //}
            });
        }
Exemplo n.º 16
0
        public static void IdentityResources(ConfigurationDbContext context)
        {
            IdentityResources.OpenId openId = new IdentityResources.OpenId();

            if (!context.IdentityResources.Any(resource => resource.Name == openId.Name))
            {
                context.IdentityResources.Add(openId.ToEntity());

                context.SaveChanges();
            }

            IdentityResources.Profile profile = new IdentityResources.Profile();

            if (!context.IdentityResources.Any(resource => resource.Name == profile.Name))
            {
                context.IdentityResources.Add(profile.ToEntity());

                context.SaveChanges();
            }
        }
Exemplo n.º 17
0
        public static List <IdentityResource> GetIdentityResources()
        {
            // Claims automatically included in OpenId scope
            var openIdScope = new IdentityResources.OpenId();

            openIdScope.UserClaims.Add(JwtClaimTypes.Locale);
            openIdScope.UserClaims.Add(Constants.TenantIdClaimType);
            openIdScope.UserClaims.Add(JwtClaimTypes.Subject);

            // Available scopes
            return(new List <IdentityResource>
            {
                openIdScope,
                new IdentityResources.Profile(),
                new IdentityResources.Email(),
                new IdentityResource(Constants.RolesScopeType, Constants.RolesScopeType,
                                     new List <string> {
                    JwtClaimTypes.Role, Constants.TenantIdClaimType
                })
                {
                    Required = true
                }
            });
        }
Exemplo n.º 18
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);
        }
Exemplo n.º 19
0
        public static void PopulateDatabase(IApplicationBuilder app)
        {
            using var serviceScope         = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope();
            using var configurationContext = serviceScope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();

            //Seed clients
            bool frontEndClientExists =
                configurationContext.Clients.Any(x => x.ClientId == "7ceea8f0-9ef6-4a41-b0d7-d4ebe99430bb");

            if (!frontEndClientExists)
            {
                Client frontEndClient = new Client
                {
                    ClientName                       = "Microservices.WebUI",
                    ClientId                         = "7ceea8f0-9ef6-4a41-b0d7-d4ebe99430bb",
                    AllowedGrantTypes                = GrantTypes.Implicit,
                    RequireConsent                   = false,
                    AllowAccessTokensViaBrowser      = true,
                    AlwaysIncludeUserClaimsInIdToken = true,
                    PostLogoutRedirectUris           = new List <string>()
                    {
                        "http://localhost:4200"
                    },
                    RedirectUris = new List <string>()
                    {
                        "http://localhost:4200/authentication/signin-oidc",
                        "http://localhost:4200/authentication/redirect-silent"
                    },
                    AllowedScopes = new List <string>()
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "roles", "portal-gateway", "product-service-api"
                    },
                    ClientSecrets = new List <Secret>()
                    {
                        new Secret("2af62f010fab4e558324b841d8006be1".Sha256())
                    },
                    Claims = new List <ClientClaim>()
                    {
                        new ClientClaim(string.Empty, "openid"),
                        new ClientClaim(string.Empty, "profile"),
                        new ClientClaim(string.Empty, "roles")
                    }
                };

                configurationContext.Clients.Add(frontEndClient.ToEntity());
            }

            //Seed identity resources
            IdentityResources.OpenId openId = new IdentityResources.OpenId();
            if (!configurationContext.IdentityResources.Any(x => x.Name == openId.Name))
            {
                configurationContext.IdentityResources.Add(openId.ToEntity());
            }

            IdentityResources.Profile profile = new IdentityResources.Profile();
            if (!configurationContext.IdentityResources.Any(x => x.Name == profile.Name))
            {
                configurationContext.IdentityResources.Add(profile.ToEntity());
            }

            IdentityResource role = new IdentityResource("roles", "Your role(s)", new[] { "role" });

            if (!configurationContext.IdentityResources.Any(x => x.Name == role.Name))
            {
                configurationContext.IdentityResources.Add(role.ToEntity());
            }

            //Seed api resources
            ApiResource portalGateway = new ApiResource("portal-gateway", "Portal.Gateway", new[] { "role" });

            if (!configurationContext.ApiResources.Any(x => x.Name == portalGateway.Name))
            {
                configurationContext.ApiResources.Add(portalGateway.ToEntity());
            }

            ApiResource productService = new ApiResource("product-service-api", "ProductService.API", new[] { "role" });

            if (!configurationContext.ApiResources.Any(x => x.Name == productService.Name))
            {
                configurationContext.ApiResources.Add(productService.ToEntity());
            }


            ApiResource pricingService = new ApiResource("pricing-service-api", "PricingService.API", new[] { "role" });

            if (!configurationContext.ApiResources.Any(x => x.Name == pricingService.Name))
            {
                configurationContext.ApiResources.Add(pricingService.ToEntity());
            }


            ApiResource policyService = new ApiResource("policy-service-api", "PolicyService.API", new[] { "role" });

            if (!configurationContext.ApiResources.Any(x => x.Name == policyService.Name))
            {
                configurationContext.ApiResources.Add(policyService.ToEntity());
            }


            ApiResource policySearchService = new ApiResource("policy-search-service-api", "PolicySearchService.API", new[] { "role" });

            if (!configurationContext.ApiResources.Any(x => x.Name == policySearchService.Name))
            {
                configurationContext.ApiResources.Add(policySearchService.ToEntity());
            }


            ApiResource paymentService = new ApiResource("payment-service-api", "PaymentService.API", new[] { "role" });

            if (!configurationContext.ApiResources.Any(x => x.Name == paymentService.Name))
            {
                configurationContext.ApiResources.Add(paymentService.ToEntity());
            }

            //.AddInMemoryApiScopes(new IdentityServer4.Models.ApiScope[] { new IdentityServer4.Models.ApiScope("portal-gateway", "Portal.Gateway", new[] { "role" })})
            ApiScope portalGatewayScope = new ApiScope("portal-gateway", "Portal.Gateway", new[] { "role" });

            if (!configurationContext.ApiScopes.Any(x => x.Name == portalGatewayScope.Name))
            {
                configurationContext.ApiScopes.Add(portalGatewayScope.ToEntity());
            }

            configurationContext.SaveChanges();
        }