首页 > 解决方案 > JWTBearer 身份验证:一段时间后,JWTBearer 身份验证将不起作用

问题描述

我们使用托管在 Azure 中的 ASP.NET Core 2.2 服务。共有三种不同的身份验证类型:使用的 OpenId、JWTBearer 和 Cookie。

作为服务的一部分是一个 API,应用程序可以在其中发送请求并使用不记名令牌进行身份验证。

到目前为止一切正常:我们的应用程序向服务的 API 发送请求,并且身份验证运行良好。经过一段时间(1-2 天)的部署后,我们注意到 JWTBearer-Authentication 不再起作用。

因此,我们提高了日志级别以从 Azure Application Insights 获取更多信息。日志告诉我们 JWTBearer 将不再受到挑战,OpenId 将我们重定向到登录页面。当我们重新部署服务时,一切正常,直到接下来的 1-2 天。

现在我找到了解决该问题的方法,但我真的不明白有助于修复 JWTBearer 身份验证的重大更改是什么。

有人有想法吗?

旧版认证:

string audience = "https://test.test";
string azureActiveDirectoryInstance = "https://login.microsoftonline.com/";
string tenant = "DummyText";
string authority = $"{azureActiveDirectoryInstance}{tenant}";

services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
    .AddAzureAd(options => objConfiguration.Bind("Authentication:AzureAd", options))
    .AddCookie(cookieOptions =>
    {
        cookieOptions.ExpireTimeSpan = new TimeSpan(7, 0, 0);
    })
    .AddJwtBearer(jwt =>
    {
        jwt.Audience = audience;
        jwt.Authority = authority;

        jwt.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateLifetime = true,
            ValidAudience = audience,
            ClockSkew = TimeSpan.Zero,
        };
    }
);
}

新版认证:

services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
    .AddAzureAd(options => objConfiguration.Bind("Authentication:AzureAd", options))
    .AddCookie(cookieOptions =>
    {
        cookieOptions.ExpireTimeSpan = new TimeSpan(7, 0, 0);
    })
    .AddJwtBearer(jwt =>
    {
        jwt.Audience = audience;
        jwt.Authority = authority;

        jwt.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateLifetime = true,
            ValidAudience = audience,
            ValidateAudience = true,
            ValidateIssuer = true,
            RequireExpirationTime = true,
            ClockSkew = TimeSpan.Zero,
        };
    }
);
}

我更改了 DefaultScheme 和 DefaultChallengeScheme,并使用了 TokenValidationParameters 中的更多属性。

我还改变了 AuthorizationPolicy 来自:

AuthorizationPolicy policy = new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .Build();

AuthorizationPolicy policy = new AuthorizationPolicyBuilder(new[] { CookieAuthenticationDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme })
                        .RequireAuthenticatedUser()
                        .Build();

标签: c#authenticationasp.net-corebearer-token

解决方案


推荐阅读