无法在Spring和Angular2之间交换Cookie [英] Unable to exchange cookie between Spring and Angular2
问题描述
我执行了以下oauth2实现:
I got following oauth2 implementation:
- 用angular2编写的我的前端(SPA)由
frontend.mydomain.com
提供. - 用户登录时,他正在连接到
auth.mydomain.com
,后端使用访问令牌进行响应,并设置包含刷新令牌的httpOnly cookie.
- My front-end (SPA), written in angular2 is served from
frontend.mydomain.com
. - When user is logging in, he is connecting to
auth.mydomain.com
, backend responds with access token, and set httpOnly cookie containing refresh token.
这是我设置cookie的方式:
this is how I set cookie:
@RequestMapping(path="/retrieve", method = RequestMethod.GET)
public String getToken(HttpServletResponse resp, @RequestParam("username") String username, @RequestParam("password") String password) {
String[] tokens = //retrieve tokens logic, values are not important
Cookie cookie = new Cookie("token", tokens[1]);
resp.addCookie(cookie);
return tokens[2];
}
- 从
resources.mydomain.com
中检索数据(请求与访问令牌一起发送) - 令牌过期后,我想通过向
auth.mydomain.com
发送请求来刷新令牌-服务器应从cookie中检索刷新令牌并以新的访问令牌进行响应.
- Data is retrieved from
resources.mydomain.com
(requests are send with access token) - when token expires I want to refresh it via sending request to
auth.mydomain.com
- server should retrieve refresh token from cookie and respond with new access token.
我认为我在第2点有问题,这影响了第4点-没有发送cookie. org.springframework.web.bind.ServletRequestBindingException:类型为Object的方法参数缺少cookie'token'
I think that I have issue in point 2, which is affecting point 4 - no cookie is sent.
org.springframework.web.bind.ServletRequestBindingException: Missing cookie 'token' for method parameter of type Object
为什么?如何强制浏览器保存并发送此Cookie?
Why? What can I do to force browser to save and send this cookie?
当我在浏览器(开发人员工具)中浏览时,我可以看到rest响应发送了cookie:
When I take a look inside my browser (developer tooles) I can see that rest response sends cookie:
但是浏览器中没有存储cookie:
But no cookie is stored in the browser:
推荐答案
问题出在前端.我没有使用"withCredentials"选项.对于正在设置Cookie的请求和正在发送Cookie的请求,也应该使用它:
The problem was in front-end side. I was not using 'withCredentials' option. It should be used as well for request which is setting up cookie, and for request which is sending cookie:
获取Cookie:
this.http.get(
AUTHENTICATION_ENDPOINT + "/retrieve?username=" + login + "&password=" + password + "&remember=" + remember,
new RequestOptions({withCredentials: true})
)
发送cookie:
this.http.get(
AUTHENTICATION_ENDPOINT + "/refresh",
new RequestOptions({withCredentials: true})
)
这篇关于无法在Spring和Angular2之间交换Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!