ASP .NET Core 2.0 - JWT 外部验证

ASP .NET Core 2.0 - JWT External Auth

我正在尝试在 ASP.NET Core 2.0 网络应用程序上开始身份验证。

我的公司正在使用 Ping Federate,我正在尝试使用公司登录页面对我的用户进行身份验证,并在 return 中使用我的签名密钥验证 returned 令牌(X509SecurityKey在这里)。

登录页面 link 如下所示:

https://companyname.com/authorization.oauth2?response_type=code&redirect_uri=https%3a%2f%2fJWTAuthExample%2fAccount%2fLogin&client_id=CompanyName.Web.JWTAuthExample&scope=&state=<...state...>

开箱即用,我将 Startup.cs 配置为能够登录并挑战此站点。

我用 [Authorize(Policy="Mvc")] 装饰了我的 HomeController,但是当我访问其中一个页面时,我只得到一个空白页面。

当我将它添加到 options.Events 时,调试没有命中 OnChallengeOnAuthenticationFailed 方法(我想是因为用户需要先进行身份验证)。

那么,为了重定向到我的身份验证网站,我缺少什么?它是内置的还是我必须进行一些手动配置?

(注意:在其他网络应用程序中,使用 asp 网络框架,当身份验证失败时,我在 Authorize 属性中使用重定向)

相关post: - 从这个 post 来看,是否意味着我没有使用正确的身份验证方法?我正在构建一个网络应用程序,而不是 API.

namespace JWTAuthExample
{
    public class Startup
    {
        public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
        {
            Configuration = configuration;
            HostingEnvironment = hostingEnvironment;

            string certificatepath = Path.Combine(HostingEnvironment.ContentRootPath, $"App_Data\key.cer");
            KEY = new X509SecurityKey(new X509Certificate2(certificatepath));
        }

        public IConfiguration Configuration { get; }
        public IHostingEnvironment HostingEnvironment { get; }
        private string AUTH_LOGINPATH { get; } = Configuration["DefaultAuth:AuthorizationEndpoint"];
        private X509SecurityKey KEY { get; }


        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
                {
                    options.IncludeErrorDetails = true;
                    options.SaveToken = true;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {   
                        // Ensure token expiry
                        RequireExpirationTime = true,
                        ValidateLifetime = true,
                        // Ensure token audience matches site audience value
                        ValidateAudience = false,
                        ValidAudience = AUTH_LOGINPATH,
                        // Ensure token was issued by a trusted authorization server
                        ValidateIssuer = true,
                        ValidIssuer = AUTH_LOGINPATH,
                        // Specify key used by token
                        RequireSignedTokens = true,
                        IssuerSigningKey = KEY
                    };
                });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Mvc", policy =>
                {
                    policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
                    policy.RequireAuthenticatedUser();                    
                });
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();

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

根据 Brad 的建议,

这是在 ASP NET 2.0

上执行 OpenId Connect 配置的代码示例
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddOpenIdConnect(options =>
    {
        options.Authority = Configuration["AuthoritySite"];
        options.ClientId = Configuration["ClientId"];
        options.ClientSecret = Configuration["ClientSecret"];
        options.Scope.Clear();
        // options.Scope.Add("Any:Scope");
        options.ResponseType = OpenIdConnectResponseType.CodeIdTokenToken;
        options.SaveTokens = true;

        options.GetClaimsFromUserInfoEndpoint = true;

        options.TokenValidationParameters = new TokenValidationParameters
        {
            // Compensate server drift
            ClockSkew = TimeSpan.FromHours(12),
            // Ensure key
            IssuerSigningKey = CERTIFICATE,

            // Ensure expiry
            RequireExpirationTime = true,
            ValidateLifetime = true,                    

            // Save token
            SaveSigninToken = true
        };                

    });

    services.AddAuthorization(options =>
    {
        options.AddPolicy("Mvc", policy =>
        {
            policy.AuthenticationSchemes.Add(OpenIdConnectDefaults.AuthenticationScheme);
            policy.RequireAuthenticatedUser();
        });
    });
}

此处有更多详细信息:https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x?view=aspnetcore-2.1