【发布时间】:2019-09-18 09:54:11
【问题描述】:
如果用户发送的令牌已过期,我将尝试返回更改后的标头,以便在过期时重新发送我的刷新令牌。
我正在使用带有“进程内”托管的 .NET Core 2.2,以防万一。
这是我的ConfigureServices 方法,来自我的Startup.cs。
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "bearer";
options.DefaultChallengeScheme = "bearer";
}).AddJwtBearer("bearer", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration["serverSigningPassword"])),
ValidateLifetime = true,
ClockSkew = System.TimeSpan.Zero //the default for this setting is 5 minutes
};
options.Events = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return System.Threading.Tasks.Task.CompletedTask;
}
};
});
然后,当我尝试使用以下内容从 javascript 获取“授权”端点时。
async function fetchWithCredentials(url, options) {
options.headers['Authorization'] = 'Bearer ' + jwtToken;
var response = await fetch(url, options);
if (response.ok) { //all is good, return the response
return response;
}
console.log(response.headers) //nothing in this array
// it will never do this "if" statement because there are no headers
if (response.status === 401 && response.headers.has('Token-Expired')) {
// refresh the token
return await fetchWithCredentials(url, options); //repeat the original request
} else { //status is not 401 and/or there's no Token-Expired header
return response;
}
}
这张图片来自于将鼠标悬停在标题上。它确实达到了我的断点(对于context.Response.Headers.Add(),我可以看到计数 = 1(当我检查它时,它是“令牌过期”)。
最后,这是 Postman 在请求失败后的屏幕截图,因此响应正在发送,但在我的 JS 中没有收到。
关于为什么我的标头不符合我在 javascript 中的响应的任何想法?
【问题讨论】:
标签: javascript c# api asp.net-core http-headers