コード例 #1
0
        /// <summary>
        /// 添加IdentityServer认证
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <param name="environmentName">环境名称</param>
        public static IServiceCollection AddIdentityServer <T>(this IServiceCollection services, IConfigurationSection section) where T : class, IResourceOwnerPasswordValidator
        {
            var apiResources = new List <ApiResource>();
            var clients      = new List <Client>();

            if (section.Exists())
            {
                var idsOptions = section.Get <IdsOptions>();

                if (idsOptions != null)
                {
                    foreach (var item in idsOptions.IdsApiResources)
                    {
                        apiResources.Add(new ApiResource(item.Name, item.DisplayName));
                    }

                    foreach (var item in idsOptions.IdsClients)
                    {
                        var allowedScopes = new List <string>()
                        {
                            IdentityServerConstants.StandardScopes.OfflineAccess
                        };

                        foreach (var i in item.AllowedScopes)
                        {
                            allowedScopes.Add(i);
                        }

                        clients.Add(
                            new Client
                        {
                            ClientId = item.ClientId,
                            AllowAccessTokensViaBrowser = true,
                            ClientSecrets                    = new[] { new Secret("secret".Sha256()) },
                            AllowedGrantTypes                = GetAllowedGrantTypes(item.GrantTypes),
                            AllowedScopes                    = allowedScopes,
                            AllowOfflineAccess               = true,
                            AccessTokenLifetime              = item.AccessTokenLifetime,
                            RefreshTokenExpiration           = TokenExpiration.Sliding,
                            RefreshTokenUsage                = TokenUsage.ReUse,
                            UpdateAccessTokenClaimsOnRefresh = false
                        });
                    }
                }
            }

            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResourceResources())
            .AddInMemoryApiResources(apiResources)
            .AddInMemoryClients(clients)
            .AddResourceOwnerValidator <T>()
            .AddProfileService <ProfileService>();
            services.TryAddSingleton <ILoginInfo, LoginInfo>();
            return(services);
        }