Home > OS >  Is it better to split a bearer token in half between cookies and localstorage?
Is it better to split a bearer token in half between cookies and localstorage?

Time:01-04

I wanted to save a bearer token to authenticate APIs on the client. I read that http-only cookies and localstorage have different downsides, and felt that using both at the same time would improve security. Would it be wise to save half of the token in an http-only cookie and half in localstorage, or should I only use one of them?

CodePudding user response:

With SameSite being set to Lax or Strict, the cookie will get the CSRF protection that was the primary weakness that caused a move from cookies to bearer tokens. A cookie that is set to Secure, HttpOnly and SameSite=Lax/Strict will only be sent on HTTPS, not be available to script and have a decent protection against CSRF.

Bearer tokens saved in local storage will be accessible to script, and can thus be stolen in XSS attacks, just as with cookies lacking the HttpOnly flag.

If you store half in local storage and half as a cookie you are probably going to combine the parts before using it in a request header. In this case you can't set HttpOnly flag on the cookie, and you will lose the benefits that cookie storage can provide. Consequently it doesn't make sense to split the bearer token.

If you are in this situation because you use the implicit code flow of OAuth 2.0, please be adviced that this flow is now deprecated and you should use Authorization code with PKCE flow instead, and your authentication token should be stored in a cookie hardened as described above.

  • Related