c# - 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();
解决方案
推荐阅读
- php - 如何在浏览器中获取 php-rdkafka 消息我将在命令行中尝试给出输出但不在浏览器中
- python - 在与 c 扩展交互时,IPython 的行为与 CPython 不同
- java - 扫描仪 Java 的简单注册验证表
- regex - rubular中的多行java异常正则表达式
- wordpress - Wordpress 将内容编码为 html
- vhdl - 有线或未合成
- javascript - 如何改进我对对象对象的迭代?
- jquery - 为什么 :contains(text) 选择所有标签?
- python - 使用 Flask 获取主机方案和域
- javascript - React 中的内联 CSS 样式:添加随机变量