Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle JWT token on client side of Spring MVC?

There is Spring MVC application - the server produces HTML, the client is not SPA (i.e. this is not about API in any form).
During authentication JWT token is generated and returned to the client. During authorization the server verifies JWT token.

How to store JWT token on client side and pass it via all further requests to the server? Remember this is Spring MVC application and not SPA.

I tried to google for any examples but the only findings relate to REST authentication, that doesn't relate to this case at all.

In worst case we can perform authentication from JavaScript and store JWT token in cache/cookie. But maybe Spring MVC supports this out of the box and we need just to set some checkbox in configuration :-)

like image 257
nickolay.laptev Avatar asked Nov 07 '22 17:11

nickolay.laptev


1 Answers

For non-SPAs, the usual approach is to store the authentication token in the server session. When the client makes a request, the appropriate session is retrieved via the JSESSIONID cookie (or the JSESSIONID is added to the URL if cookies are disabled).

I'm not sure why you can't use the approach above, but if you want to store the JWT on the client, a common approach is:

  • store the token in the browser's local or session storage when it's generated, e.g. window.sessionStorage.authToken = 'token_value';
  • add the token to each subsequent request by setting the Authorization HTTP header to the value of the token
  • when the user logs out, delete the token from browser storage
like image 133
Dónal Avatar answered Nov 14 '22 11:11

Dónal