0

I'm working on a small rest api project with user authentication. But I'm wondering whether I should store the users authentication token in a header or a cookie.

The general idea is as follows:

  1. User makes a POST request to /tokens/authentication with his/her login credentials (email and password).
  2. On a successful login an authentication token is placed in the header/cookie.
  3. Requests to certain endpoints check the token against the database.
  4. If this token exists and the corresponding user is authorized to access this endpoint, access is granted.

I'm unsure of whether a cookie or header is best for the job and would love to hear your input.

The API will be consumed by a single page application.

Also, could someone just clarify for me the duration for which a cookie and a header are active. I.e is a cookie present in the browser until cache and cookies are manually deleted. How long is a request header active?

2
  • Are you asking about how to store the token in the browser, or how so send the token, because as far as transmission goes, cookies are just headers.
    – Jack
    Nov 15, 2021 at 0:25
  • I was mainly asking about which would be better for my above case. But bk2204 answered it well. So I think I'm good for now. Thanks.
    – Bryan
    Nov 15, 2021 at 0:31

1 Answer 1

0

If you're using an API, you'll typically use a token in the Authentication header. Oftentimes the Bearer scheme will be used here.

That's because you want each individual request to be individually authenticated, and most HTTP clients used for APIs don't keep track of cookies across requests. However, cookies are a good approach for web applications because the browser knows how to send them automatically for requests to certain domains.

A request header is active for the duration of the request. Once the response has been sent, the header is forgotten. If you want to authenticate using a request header for a subsequent request, you must send another header as part of that request.

A cookie, on the other hand, has a set expiration date, and can also be expired by the server by sending an appropriate header. It will usually persist in the browser until that time has expired or the server expires it prematurely, but the user may also delete it for various reasons, and you should not rely on the expiration for security purposes.

1
  • Thank you, really appreciate it. So if the API was primarily used as the backend to a web application where I just wanted the user to login and then be able to access any endpoint for a duration of time. Storing it in a cookie would be best right? If it was in the request header, they'd have to login before every request?
    – Bryan
    Nov 14, 2021 at 13:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .