我有两种解决方案,都不太理想。
当您使用 Ajax 调用时,第一个不起作用。 (我遇到了 CORS 错误,发现无法允许主机;预检调用失败。)
// middleware
public async Task Invoke(HttpContext context) {
if (userRolesHaveChanged) {
context.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme,
new AuthenticationProperties { RedirectUri = redirectUrl });
return;
}
// the normal flow
await next(context);
}
访问 XMLHttpRequest 在
'https://login.microsoftonline.com/XYZ/oauth2/v2.0/authorize?client_id=xyz&redirect_uri=https%3A%2F%2Flocalhost%3A8083%2FAuth%2FLogin%2FSignInOidc&response_type=id_token&/x-client-SKU=ID_NETSTANDARD2_0&x -客户端版本=5.5.0.0'
(重定向自“https://localhost:8083/PATH”)来自原点
“https://localhost:8083”已被 CORS 策略阻止:响应
预检请求未通过访问控制检查:否
'Access-Control-Allow-Origin' 标头出现在请求的
资源。
为了克服 CORS 问题,我提出了一个 HACK,通过使用
Cookie 过期时间。
首先配置 OpenIdConnect 使用 cookie 过期时间,
然后当用户角色发生变化时,只需删除控制 cookie。
// startup
services.Configure<OpenIdConnectOptions> (OpenIdConnectDefaults.AuthenticationScheme, options =>
options.UseTokenLifetime = false; // Expire time
options.SignInScheme = "hack";
// SNIPPED CODE
.AddCookie("hack", "hack", options =>
{
const int minute = 60;
const int hour = minute * 60;
const int day = hour * 24;
options.ExpireTimeSpan = TimeSpan.FromSeconds(day/2.0);
})
然后在中间件内
// middleware
public async Task Invoke(HttpContext context) {
if (userRolesHaveChanged) {
// force expire....
// causes the next page load to indirectly call ChallengeAsync
context.Response.Cookies.Delete(".AspNetCore.hack");
// also possibly set some other controlling variable,
// and deal with it, within the Ajax call
// e.g.
context.Response.Cookies.Append("autoSignIn", redirectUrl,
new CookieOptions { HttpOnly = false });
}
解决方案既糟糕又笨拙。