首页 文章

ASP .NET Core 2.0 - JWT外部认证

提问于
浏览
0

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

我的公司正在使用Ping Federate,我正在尝试使用公司登录页面验证我的用户,并使用我的签名密钥验证返回的令牌(此处为 X509SecurityKey ) .

登录页面链接如下所示:

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 方法(我认为因为用户需要先进行身份验证) .

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

(注意:在其他Web应用程序中,使用asp net framework,我在身份验证失败时在Authorize属性中使用重定向)

相关文章:Authorize attribute does not redirect to Login page when using .NET Core 2's AddJwtBearer - 从这篇文章中,是否意味着我没有使用正确的身份验证方法?我正在构建一个Web应用程序,而不是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?}");
            });
        }
    }
}

1 回答

  • 0

    遵循布拉德的建议,

    以下是在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

相关问题