Spring Security - REST API - Token vs. Cookie

I wrote a REST-API in Java and I got this API using Spring Security. The procedure is as follows:

  • Frontend calls / login RestService in Backend
  • Backend returns a token for an interface
  • each time the REST API is accessed, the token must be placed in the header

This works fine, but I read that it is also possible (with Node.JS / Passport.js / Express.js) that a session object with a cookie inside can be moved out of the box without any custom code.

Now my question will be if there is a better approach, so the interface / client does not need to constantly set the token in the header for any request.

+5
source share
2 answers

Typically, token-based authentication has advantages over cookies.

You can achieve this using the middle layer.

Here is a good post - https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/

+2
source

On the server side, I usually check the headers first if there is an auth token. If not, I then check the cookies as a reserve.

If you want to use cookies, then in step 2 you need to add the Set-Cookie header in the response so that the browser knows that they need to store cookies. After that, you do not need to add the client part of the header, as browsers will send cookies every request. You will need to add CSRF protection though ( here is a good example).

+2
source

All Articles