Bin*_*nam 7 javascript request-headers response-headers cookie-httponly asp.net-core
我有一个基本的SPA(反应)<-> API(网络核心2.2)设置,带有2个环境:dev和prod(小型项目)。API侧面有一个身份验证机制,用于检查httponly每个包含JWT的请求中cookie 的存在。
在开发环境中,它可以正常运行okey-dokey:,allowCredentials()并且已withCredentials = true在API和react应用程序中进行了设置。两者都在我的本地主机的不同端口上运行。
但是在生产环境中(单独的Heroku dynos),它不会设置httponlycookie:我可以使用我的凭据登录,响应标题包含带有jwt的cookie,但是我要发出的其他每个请求都将不包含cookie。 cookie标头在请求标头中!
然后我得到一个401 Unauthorized ...错误(这是逻辑上的)。我花了数小时尝试所有事情,这让我发疯。
我的简单身份验证XHR(原始)调用:
var request = new XMLHttpRequest()
request.open('POST', apiAuthenticateUser, true)
request.setRequestHeader('Content-type', 'application/json')
request.withCredentials = true
request.send(postData)
Run Code Online (Sandbox Code Playgroud)
我Startup.cs在.net核心api中的配置:
var request = new XMLHttpRequest()
request.open('POST', apiAuthenticateUser, true)
request.setRequestHeader('Content-type', 'application/json')
request.withCredentials = true
request.send(postData)
Run Code Online (Sandbox Code Playgroud)
那就是我如何在api控制器动作响应中设置包含jwt的httponly cookie:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
IdentityModelEventSource.ShowPII = true;
} else {
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseCors(
options => options.WithOrigins(
"https://localhost:3000",
"*productionEnvUrl*").AllowAnyMethod().AllowCredentials().AllowAnyHeader()
);
app.UseMvc(routes => {
routes.MapRoute("MainRoute", "api/{controller}/{action}");
});
app.UseAuthentication();
}
Run Code Online (Sandbox Code Playgroud)
两种环境下的代码相同,只是产生不同的结果。在这两种情况下,api都会在身份验证响应标头中向我发送正确的cookie,但是在生产环境中,我的react应用程序只是不保留它,而是通过其他api调用将其发送回去。
这是从API接收到的cookie,永远不会从网络应用发送回该cookie:
Access-Control-Allow-Credentials :true
Access-Control-Allow-Origin :https://xxxxxxxxxx.com
Connection :keep-alive
Content-Type :application/json; charset=utf-8
Date :Mon, 09 Sep 2019 22:32:54 GMT
Server :Kestrel
Set-Cookie :jwt=xxxxxxxx; path=/; secure; samesite=lax; httponly
Transfer-Encoding :chunked
Vary :Origin
Via :1.1 vegur
Run Code Online (Sandbox Code Playgroud)
如果有人有任何线索,我将永远感激不已。
事实证明我做错了很多事情:
感谢@Crayon Violent 抽出时间:)
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |