无法在Spring和Angular2之间交换cookie

时间:2017-01-10 12:24:30

标签: spring rest spring-mvc angular cookies

我遵循oauth2实施:

  1. 我的前端(SPA),以angular2编写,由frontend.mydomain.com提供。
  2. 当用户登录时,他正在连接auth.mydomain.com,后端使用访问令牌进行响应,并设置包含刷新令牌的httpOnly cookie。
  3. 这就是我设置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检索刷新令牌并使用新的访问令牌进行响应。
    3. 我认为我在第2点遇到问题,影响了第4点 - 没有发送cookie。 org.springframework.web.bind.ServletRequestBindingException: Missing cookie 'token' for method parameter of type Object

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

      当我查看我的浏览器(开发人员)时,我可以看到其他响应发送cookie: enter image description here

      但浏览器中没有存储cookie: enter image description here

1 个答案:

答案 0 :(得分: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})
)