【问题标题】:ASP .NET Core 2.0 - JWT External AuthASP .NET Core 2.0 - JWT 外部认证
【发布时间】:2018-11-08 14:39:08
【问题描述】:

我正在尝试开始在 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 方法(我认为是因为用户需要先进行身份验证)。

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

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

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

【问题讨论】:

  • 您使用了错误的身份验证方法。 JWT 用于使用包含在 Authorization 标头中的令牌进行 API 访问。如果您的身份验证服务器支持 OpenId Connect,请考虑使用带有 Cookie 的身份验证方法。
  • 好的,将对其进行研究并返回我所做的实现作为解决方案分享。谢谢。

标签: c# asp.net-core oauth-2.0 asp.net-core-2.0 pingfederate


【解决方案1】:

按照布拉德的建议,

这是在 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

【讨论】:

  • 如果我们可以看到您的配置变量的内容,这将是一个更有用的答案,即使您修改了这些值以保护您的隐私。
  • @P.Roe 我无法再访问代码库,但如果您正在寻找如何格式化配置文件,您可以查看此处,例如:codeproject.com/Articles/14744/…。然后使用配置 API 检索配置字符串,如下所示:Configuration["KEY"];
猜你喜欢
  • 2021-02-19
  • 1970-01-01
  • 2017-09-11
  • 2018-06-22
  • 2019-01-21
  • 2018-01-22
  • 2018-07-03
  • 2023-04-01
  • 2018-03-29
相关资源
最近更新 更多