Unable to exchange cookie between Spring and Angul

2019-07-25 20:44发布

I got following oauth2 implementation:

  1. My front-end (SPA), written in angular2 is served from frontend.mydomain.com .
  2. When user is logging in, he is connecting to auth.mydomain.com, backend responds with access token, and set httpOnly cookie containing refresh token.

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];
}
  1. Data is retrieved from resources.mydomain.com (requests are send with access token)
  2. 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.

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

Why? What can I do to force browser to save and send this cookie?

When I take a look inside my browser (developer tooles) I can see that rest response sends cookie: enter image description here

But no cookie is stored in the browser: enter image description here

1条回答
别忘想泡老子
2楼-- · 2019-07-25 21:21

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:

retrieving cookie:

this.http.get(
    AUTHENTICATION_ENDPOINT + "/retrieve?username=" + login + "&password=" + password + "&remember=" + remember, 
    new RequestOptions({withCredentials: true})
)

sending cookie:

this.http.get(
     AUTHENTICATION_ENDPOINT + "/refresh", 
     new RequestOptions({withCredentials: true})
)
查看更多
登录 后发表回答