ASP.NET Core & OpenID Connect 重定向到外部身份提供商

ASP.NET Core & OpenID Connect Redirect to External Identity Provider

我已经使用 OpenID Connect 构建了一个身份提供程序,以提供利用 OAuth2 访问令牌的身份验证和授权。服务器上的授权工作流程有效;但是,我似乎无法让我的 ASP.NET Core 客户端在身份验证失败时自动重定向到 OpenID Connect 提供程序。我目前刚收到 401。

这是我的 startup.cs:

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseCookieAuthentication();

        var options = new OpenIdConnectOptions
                          {
                              Authority = "http://localhost:63467",
                              AutomaticAuthenticate = true,
                              AutomaticChallenge = true,
                              AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet,
                              AuthenticationScheme = "oidc",
                              ClientId = "2",
                              ClientSecret = "alskghalsd",
                              Configuration =
                                  new OpenIdConnectConfiguration
                                      {
                                          AuthorizationEndpoint =
                                              "http://localhost:63467/connect/authorize",
                                          TokenEndpoint =
                                              "http://localhost:63467/connect/token"
                                      },
                              PostLogoutRedirectUri = "/",
                              ResponseType = "Code",
                              RemoteSignOutPath = "/signout",
                              UseTokenLifetime = true,
                              SaveTokens = true,
                              SignInScheme = "Cookies",
                              RequireHttpsMetadata = false
                          };
        options.Scope.AddRange(new[] { "openid name role profile" });
        app.UseOpenIdConnectAuthentication(options);

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

我最终通过使用 IdentityServer 托管一个应用程序作为身份端点解决了这个问题,并相应地配置了我的客户端。

        public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc(
            opts =>
                {
                    // custom api exception filter
                    opts.Filters.Add(typeof(ApiExceptionFilter));
                });
        services.Configure<IISOptions>(
            options =>
                {
                    options.AutomaticAuthentication = false;
                    options.ForwardClientCertificate = false;
                    options.ForwardWindowsAuthentication = false;
                });

        services.AddSingleton(this.Configuration);
        services.AddIdentityServer();
    }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {  
            app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookies" });
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

        // get values from config
        IConfigurationSection clientSettings = this.Configuration.GetSection("AppSettings:ClientSettings");
        string[] scopes = clientSettings["Scope"].Split(' ');
        var oidcOptions = new OpenIdConnectOptions
                          {
                              AuthenticationScheme = clientSettings["AuthenticationScheme"],
                              SignInScheme = clientSettings["SignInScheme"],
                              Authority = clientSettings["Authority"],
                              ClaimsIssuer = clientSettings["ClaimsIssuer"],
                              RequireHttpsMetadata =
                                  clientSettings.GetValue<bool>("RequireHttpsMetadata"),
                              ClientId = clientSettings["ClientId"],
                              ClientSecret = clientSettings["ClientSecret"],
                              ResponseType = clientSettings["ResponseType"],
                              GetClaimsFromUserInfoEndpoint = clientSettings.GetValue<bool>("GetClaimsFromUserInfoEndpoint"),
                              SaveTokens = clientSettings.GetValue<bool>("SaveTokens")
                          };
        foreach (var scope in scopes)
        {
            oidcOptions.Scope.Add(scope);
        }

        app.UseOpenIdConnectAuthentication(oidcOptions);

        app.UseStaticFiles();

        app.UseMvcWithDefaultRoute();
}

我会稍等片刻,然后将此标记为答案,以允许其他人提供替代解决方案。