aspnetcore 2.0 JWT和Open ID Connect身份验证位于同一网站

时间:2018-01-24 15:16:56

标签: jwt asp.net-core-2.0 openid-connect hangfire

我们有一个aspnetcore 2.0网站。该网站的大部分内容是WebAPI,包含2个UI组件:swagger和hangfire信息中心。

我们正在尝试使用JWT和带有Open ID的UI(hangfire仪表板)组件来保护Web API端点。

这是我们的设置

services
.AddSingleton<IConfigureOptions<JwtBearerOptions>, ConfigureJwtBearerOptions>()
.AddSingleton<IConfigureOptions<OpenIdConnectOptions>, ConfigureOpenIdOptions>()
.AddAuthentication(options =>
 {
    var openId = OpenIdConnectDefaults.AuthenticationScheme;
    var jwt = JwtBearerDefaults.AuthenticationScheme;

    options.DefaultScheme = jwt;
    //options.DefaultAuthenticateScheme = openId;
 })
 .AddJwtBearer()
 .AddCookie()
 .AddOpenIdConnect(options =>
 {
     var cookies = CookieAuthenticationDefaults.AuthenticationScheme;

     options.SignInScheme = cookies;
     options.SignOutScheme = cookies;
 });

services
.AddAuthorization(options => options.AddPolicy(...))
.AddMvcCore(config =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
        .Build();

    config.Filters.Add(new AuthorizeFilter(policy));
});
....

app.Map(new PathString("/hangfire"), _ => _.UseMiddleware<HangfireDashboardMiddleware>(...));

为了保护hangfire仪表板,我们必须创建一个委派处理程序,以使用OpenIdConnectDefaults.AuthenticationScheme进行身份验证和质询。

问题是我们只能让JWT或OpenID成功授权并获得所有相关声明。 当//options.DefaultAuthenticateScheme = openId;被注释掉时,JWT可以工作,但是OpenId会陷入localhost和AAD之间的永久循环中。 设置options.DefaultAuthenticateScheme = openId;时,Open ID身份验证正常,但JWT无法获取声明。它似乎确实在验证。

我们如何为每条路线设置身份验证方案?

1 个答案:

答案 0 :(得分:0)

我们终于弄明白了。 aspnetcore只能按设计处理1个方案。因此,要处理多个方案,我们需要实现自定义方案。

我们使用此方法https://gist.github.com/profet23/da146bfee5e2daa45bc4f9746aba69e0来选择bewteen scheme