【问题标题】:Unable to exchange cookie between Spring and Angular2无法在 Spring 和 Angular2 之间交换 cookie
【发布时间】:2017-05-24 22:37:11
【问题描述】:

我得到了以下 oauth2 实现:

  1. 我用 angular2 编写的前端 (SPA) 由 frontend.mydomain.com 提供。
  2. 当用户登录时,他正在连接到auth.mydomain.com,后端以访问令牌响应,并设置包含刷新令牌的httpOnly cookie。

这就是我设置 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];
}
  1. resources.mydomain.com 检索数据(使用访问令牌发送请求)
  2. 当令牌过期时,我想通过向 auth.mydomain.com 发送请求来刷新它 - 服务器应该从 cookie 中检索刷新令牌并使用新的访问令牌进行响应。

我认为我在第 2 点有问题,这会影响第 4 点 - 没有发送 cookie。 org.springframework.web.bind.ServletRequestBindingException: Missing cookie 'token' for method parameter of type Object

为什么?如何强制浏览器保存并发送此 cookie?

当我查看我的浏览器(开发人员工具)时,我可以看到 rest 响应发送 cookie:

但浏览器中没有存储 cookie:

【问题讨论】:

  • 由于 cookie 显然已经正确发送,这可能根本不是 Spring 问题。我猜这是您的 Angular 代码的问题(在第 4 步中)——您在执行刷新请求时是否设置了 "withCredentials" RequestOption
  • 不,我不是。我应该吗?
  • 我相应地更改了我的代码:this.http.post(AUTHENTICATION_ENDPOINT + "/refresh", new RequestOptions({withCredentials: true})) 仍然是同样的问题

标签: spring rest spring-mvc angular cookies


【解决方案1】:

问题出在前端。我没有使用“withCredentials”选项。它也应该用于设置 cookie 的请求和发送 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})
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 2021-12-24
    相关资源
    最近更新 更多