【发布时间】: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 时,调试没有命中OnChallenge 或OnAuthenticationFailed 方法(我认为是因为用户需要先进行身份验证)。
那么,为了重定向到我的身份验证网站,我缺少什么?它是内置的还是我必须做一些手动配置?
(注意:在其他网络应用程序中,使用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