Ejemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddHttpContextAccessor();
            services.TryAddSingleton <IActionContextAccessor, ActionContextAccessor>();

            // Pass configuration (IConfigurationRoot) to the configuration service if needed
            _externalStartupConfiguration.ConfigureService(services, null);

            services.RemoveAll <IConfiguration>();
            services.AddSingleton <IConfiguration>(Configuration);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <PathPolicyConfig>(Configuration.GetSection(PathPolicyConfig.WellKnown_SectionName));
            services.AddObjectCache();

            services.AddSingleton <IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));
            services.Configure <RouteOptions>(options => options.LowercaseUrls = true);
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);



            services.AddHttpContextAccessor();
            services.TryAddSingleton <IActionContextAccessor, ActionContextAccessor>();

            services.AddStarWarsTypes();

            // Pass configuration (IConfigurationRoot) to the configuration service if needed
            _externalStartupConfiguration.ConfigureService(services, null);

            var authority = Configuration["Authority"];

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = authority;
                options.RequireHttpsMetadata = false;
                options.ApiName   = "nitro";
                options.ApiSecret = "secret";
            });
            services.AddAuthorization(options =>
            {
                options.AddPolicy("IsAuthenticatedPolicy", policy =>
                                  policy.Requirements.Add(new IsAuthenticatedAuthorizationRequirement()));
            });
            services.AddSingleton <IAuthorizationHandler, SimpleAuthorizationHandler>();
            services.RemoveAll <IConfiguration>();
            services.AddSingleton <IConfiguration>(Configuration);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddObjectCache();  // use this vs a static to cache class data.
            services.AddOptions();
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  corsBuilder => corsBuilder
                                  .AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });
            var  clients            = Configuration.LoadClientsFromSettings();
            var  apiResources       = Configuration.LoadApiResourcesFromSettings();
            var  identityResources  = Configuration.LoadIdentityResourcesFromSettings();
            bool useRedis           = Convert.ToBoolean(Configuration["appOptions:redis:useRedis"]);
            bool useKeyVault        = Convert.ToBoolean(Configuration["appOptions:keyVault:useKeyVault"]);
            bool useKeyVaultSigning = Convert.ToBoolean(Configuration["appOptions:keyVault:useKeyVaultSigning"]);

            var builder = services
                          .AddIdentityServer(options =>
            {
                options.InputLengthRestrictions.RefreshToken = 256;
            })
                          .AddInMemoryIdentityResources(identityResources)
                          .AddInMemoryApiResources(apiResources)
                          .AddInMemoryClientsExtra(clients)
                          .AddIdentityServer4Extras()
                          .AddProfileServiceManager()
                          .AddArbitraryOwnerResourceExtensionGrant()
                          .AddArbitraryIdentityExtensionGrant()
                          .AddArbitraryNoSubjectExtensionGrant();

            // My Replacement Services.
            if (useRedis)
            {
                var redisConnectionString = Configuration["appOptions:redis:redisConnectionString"];
                builder.AddOperationalStore(options =>
                {
                    options.RedisConnectionString = redisConnectionString;
                    options.Db = 1;
                })
                .AddRedisCaching(options =>
                {
                    options.RedisConnectionString = redisConnectionString;
                    options.KeyPrefix             = "prefix";
                });
                services.AddDistributedRedisCache(options =>
                {
                    options.Configuration = redisConnectionString;
                });
            }
            else
            {
                builder.AddInMemoryPersistedGrants();
                services.AddDistributedMemoryCache();
            }
            if (useKeyVault)
            {
                builder.AddKeyVaultCredentialStore();
                services.AddKeyVaultTokenCreateServiceTypes();
                services.AddKeyVaultTokenCreateServiceConfiguration(Configuration);
                if (useKeyVaultSigning)
                {
                    // this signs the token using azure keyvault to do the actual signing
                    builder.AddKeyVaultTokenCreateService();
                }
            }
            else
            {
                builder.AddDeveloperSigningCredential();
            } // my replacement services.
            builder.AddRefreshTokenRevokationGeneratorWorkAround();
            builder.AddPluginHostClientSecretValidator();
            builder.AddNoSecretRefreshClientSecretValidator();

            builder.AddInMemoryClientStoreExtra(); // redis extra needs IClientStoreExtra
            builder.SwapOutTokenResponseGenerator();
            builder.SwapOutDefaultTokenService();
            builder.SwapOutScopeValidator();
            builder.SwapOutTokenRevocationRequestValidator();
            builder.SwapOutEventSink();

            // My Types
            services.AddArbitraryNoSubjectExtentionGrantTypes();
            services.AddArbitraryResourceOwnerExtentionGrantTypes();
            services.AddArbitraryIdentityExtentionGrantTypes();
            services.AddIdentityModelExtrasTypes();
            services.AddIdentityServer4ExtraTypes();
            services.AddRefreshTokenRevokationGeneratorWorkAroundTypes();

            builder.AddProtectedRefreshTokenKeyObfuscator();

            // Request Tracker
            services.AddIdentityServerRequestTrackerMiddleware();

            // Ratelimiter
            services.AddClientRateLimiterOptions(Configuration);
            services.AddClientRateLimiter();

            // Usage Tracking
            services.AddClientUsageTrackerOptions(Configuration);
            services.AddClientUsageTracker()
            .AddInMemoryClientUsageStore();

            // my configurations
            services.AddSingleton <IHostedService, SchedulerHostedService>();
            services.Configure <Options.RedisAppOptions>(Configuration.GetSection("appOptions:redis"));
            services.Configure <Options.KeyVaultAppOptions>(Configuration.GetSection("appOptions:keyVault"));
            services.RegisterP7CoreConfigurationServices(Configuration);

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

            services.AddHttpContextAccessor();
            services.TryAddSingleton <IActionContextAccessor, ActionContextAccessor>();

            services.AddLogging();
            // Pass configuration (IConfigurationRoot) to the configuration service if needed
            _externalStartupConfiguration.ConfigureService(services, null);

            var identityServer4BasePath = Configuration["IdentityServerPublicFacingUri"];

            if (!string.IsNullOrEmpty(identityServer4BasePath))
            {
                identityServer4BasePath = identityServer4BasePath.Trim('/');
                var endpoints = builder.Services
                                .Where(service => service.ServiceType == typeof(Endpoint))
                                .Select(item => (Endpoint)item.ImplementationInstance)
                                .ToList();

                // endpoints.ForEach(item =>item.Path.Value.r = $"api/Authority/{item.Path.Value}");
                endpoints.ForEach(item => item.Path = item.Path.Value.Replace("connect", $"{identityServer4BasePath}/connect"));
                endpoints.ForEach(item => item.Path = item.Path.Value.Replace(".well-known/openid-configuration",
                                                                              $"{identityServer4BasePath}/.well-known/openid-configuration"));
            }
        }