AngularJS 忽略 HTTP 标头中的 Set-Cookie [英] Set-Cookie in HTTP header is ignored with AngularJS
问题描述
我正在开发基于 AngularJS 的客户端应用程序和基于 Java 的服务器端 API(Tomcat + Jersey for WS).
我的API的某些路径被限制,如果用户没有会话,返回的响应状态为401.在客户端,拦截401 http状态以将用户重定向到登录页面.
一旦用户通过身份验证,我会在服务器端创建一个会话
httpRequest.getSession(true);
并且发送到客户端的响应在其标头中确实包含 Set-cookie 指令:
<前>设置-Cookie:JSESSIONID=XXXXXXXXXXXXXXXXXXXXX;域=本地主机;路径=/api/;仅Http问题是 cookie 永远不会放在客户端.当我检查 localhost 域的 cookie 时,它是空的,所以下一个请求的标头中没有这个 cookie,客户端仍然无法访问我的 API 的受限路径.
客户端和服务器在同一个域中,但它们没有相同的路径和相同的端口号:
客户端:http://localhost:8000/app/index.html
服务器:http://localhost:8080/api/restricted/
附加信息:两边都启用了 CORS :
"Access-Control-Allow-Methods", "GET, POST, OPTIONS"访问控制允许来源",*""Access-Control-Allow-Credentials", true
有没有让 Set-cookie 正常工作的想法?这是 AngularJS 相关的问题吗?
我发现了一个 问题在 AngularJS 中 帮助我前进.
似乎 "Access-Control-Allow-Credentials" : true
没有在客户端设置.指令 $httpProvider.defaults.withCredentials = true
被忽略.
我用配置参数中的 {withCredentials:true} 用一个简单的 $http 调用替换了 $resource 调用.
I'm working on an application based on AngularJS on client side and Java for my API (Tomcat + Jersey for WS) on server side.
Some path of my API are restricted, if the user doesn't have a session the response status returned is 401. On the client side, 401 http status are intercepted to redirect the user to the login page.
Once the user is authenticated, I create a session on the server side
httpRequest.getSession(true);
and the response send to the client does have the Set-cookie instruction in its header :
Set-Cookie:JSESSIONID=XXXXXXXXXXXXXXXXXXXXX; Domain=localhost; Path=/api/; HttpOnly
The problem is that the cookie is never put on the client side. When I inspect cookie for localhost domain it's empty, so the next requests don't have this cookie in their header and client side still couldn't access to the restricted path of my API.
The client and the server are on the same domain but they don't have the same path and the same port number :
Client : http://localhost:8000/app/index.html
Server : http://localhost:8080/api/restricted/
Additional info : CORS is enabled on the both side :
"Access-Control-Allow-Methods", "GET, POST, OPTIONS" "Access-Control-Allow-Origin", "*" "Access-Control-Allow-Credentials", true
Any idea for making the Set-cookie works properly ? Is it an AngularJS related issue ?
I found an issue in AngularJS that help me to move forward.
It seems that "Access-Control-Allow-Credentials" : true
was not set on the client side.
Instruction $httpProvider.defaults.withCredentials = true
was ignored.
I replace $resource call by a simple $http call with {withCredentials:true} in the config parameter.
这篇关于AngularJS 忽略 HTTP 标头中的 Set-Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!