是否可以在IdentityServer4的.net Core中的ConfigureServices中动态设置AddOpenIdConnect选项

时间:2018-08-30 17:33:44

标签: asp.net-core-2.0 identityserver4

我是.NETCore的新手,并且正在使用.NETCore Web应用程序中的IdentityServer4进行身份验证,因此我需要能够根据以下网址的网址动态设置ClientId或redirectUrls(从登录/注销页面)网络应用。但是无法在ConfigureServices方法中访问HttpContext或在ConfigureServices之外访问AddAuthentication选项-我真的很困惑!

    public void ConfigureServices(IServiceCollection services)
        {
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped<ISessionHelper, SessionHelper.SessionHelper>();
            services.AddSingleton<PortalSetup>();
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                })
                .AddCookie("Cookies", options =>
                {
                    options.LoginPath = "/account/login";
                    options.LogoutPath = "/account/logoff";
                })
                .AddOpenIdConnect(options =>
                {
                    options.SignInScheme = Configuration["Oidc:SignInScheme"];
                    options.Authority = Configuration["Oidc:Authority"];
                    options.MetadataAddress = $"{Configuration["Oidc:Authority"]}/.well-known/openid-configuration";
                    options.RequireHttpsMetadata = Convert.ToBoolean(Configuration["Oidc:RequireHttpsMetadata"]);
                    options.ClientId = Configuration["Oidc:ClientId"];
                    options.ResponseType = Configuration["Oidc:ResponseType"];
                    options.SaveTokens = Convert.ToBoolean(Configuration["Oidc:SaveTokens"]);
                    options.GetClaimsFromUserInfoEndpoint = Convert.ToBoolean(Configuration["Oidc:GetClaimsFromUserEndpoint"]);
                    options.ClientSecret = Configuration["Oidc:ClientSecret"];
                    foreach (var s in Configuration["Oidc:Scopes"].Split(','))
                    {
                        options.Scope.Add(s);
                    }
                });



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

            services.Configure<IISOptions>(iis =>
            {
                iis.AuthenticationDisplayName = "Windows";
                iis.AutomaticAuthentication = false;
                iis.ForwardClientCertificate = false;

            });

            services.AddScoped<ActionExceptionFilter>();

            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(5); // set the time for session timeout here
            });

            services.AddDataProtection()
                .PersistKeysToFileSystem(new DirectoryInfo(Configuration["keysDirectory"]));
        }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ISessionHelper session)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseFileServer(new FileServerOptions
            {
                FileProvider = new PhysicalFileProvider(Configuration["ImageDirectory"]),
                EnableDirectoryBrowsing = false,
                RequestPath = new PathString("/desimages")
            });
            //enable session before mvc
            app.UseSession();
            app.UseMiddleware<PortalSetup>();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Store}/{id?}");
            });
        }

1 个答案:

答案 0 :(得分:0)

我最终定制了标准的OIDC中间件,以在运行时通过ChallengeAsync调用获取这些参数。实际上很简单。