2

I am using Spring boot with Angular 9 with STATELESS session implementation. The application is successfully performing login and registration functionality. String boot generates token(JWT) on each and every request of login. After login when I tried to run the application of second TAB then it is again asking me to log in. To overcome the issue I have saved the token in Localstorageand then while clicking on another TAB the angular code is able to pick token from Localstorage. But after some R&D I came to know that HTTPOnly Cookie should use in place of Localstorage. Can someone help me using an HTTP-only cookie with Angular 9 and Spring Boot. Thanks

Ajay Mishra
  • 21
  • 1
  • 2

2 Answers2

1

Here is sample code to create and attach an HTTP Only cookie to your response. At minimum you need to pass in HttpServletResponse to attach the cookies to the headers. You can use ResponseEntity or something else to return any content in the body of the response.

@PostMapping("/refresh_token")
public ResponseEntity refreshToken(HttpServletResponse response)
{
   //create cookie for refresh token
   Cookie refreshTokenCookie = new Cookie("refresh_token", refreshToken);
   refreshTokenCookie.setHttpOnly(true);
   refreshTokenCookie.setSecure(true); //only allows HTTPS
   refreshTokenCookie.setPath("/");
   refreshTokenCookie.setDomain("api.lsp.com"); //restrict domain

   response.addCookie(refeshTokenCookie);

   return ResponseEntity(HttpStatus.OK);
}
user521990
  • 669
  • 1
  • 5
  • 21
0

Indeed, refresh token should be set as cookie http only instead of local storage, as it is well explained here JWT refresh token flow To answer you question, response of @user521990 is a good example of cookie implementation:

  • Just be carreful to set refreshTokenCookie.setSecure(false); in development mode because you are not using HTTPS
  • Also if you don't setDomain() explicitly, then the domain of the request will be the default one
  • Then setting path to refreshTokenCookie.setPath("/"); will make it a global cookie accessible everywhere

In development mode, you will need some CORS configuration to enable cookies to be set in the browser. At least you need the following config in your Java controller @CrossOrigin(origins = "http://localhost:4200", allowCredentials = "true") (or you can do this configuration more globally in a different file)
Finally in the Angular app, add options { withCredentials: true } to your requests that need to set or use your httponly cookie

TCH
  • 421
  • 1
  • 6
  • 25
  • 1
    HttpOnly has nothing to do with HTTP or HTTPS, it means that the cookie is accessed by client code or not (I guess you wanted to say `setSecure(false)` ? ) – Abdessamad ABOUKDIR Jun 07 '21 at 14:21