Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to secure private routes in SPA while using httpOnly cookies

I'd like to secure my SPA private routes with JWT authentication. To make everything as much secure as it's possible, I wanted to use httpOnly cookie to store my access_token on the client-side.

Using httpOnly cookies protect me a lot from XSS attacks, but unfortunately this approach does not allow me to check if the cookie actually exists in the browser.

In this case - how can I implement some logic to prevent unlogged users to visit private, secure routes of my SPA?

Am I forced to use non-httpOnly cookies or localStorage for this?

like image 309
sarneeh Avatar asked Aug 07 '18 08:08

sarneeh


People also ask

Can a cookie be HttpOnly and secure?

HttpOnly and secure flags can be used to make the cookies more secure. When a secure flag is used, then the cookie will only be sent over HTTPS, which is HTTP over SSL/TLS.

Can HttpOnly prevent XSS?

If a browser that supports HttpOnly detects a cookie containing the HttpOnly flag, and client side script code attempts to read the cookie, the browser returns an empty string as the result. This causes the attack to fail by preventing the malicious (usually XSS) code from sending the data to an attacker's website.


1 Answers

Am I forced to use non-httpOnly cookies or localStorage for this?

No. Keep your access_token in a cookie with the httpOnly flag, and (if possible) with the secure flag. Let's call this cookie session_cookie.

When a user does a successful login you could return 2 cookies: the session_cookie and another one which informs to JS the user has been authenticated (let's call as SPA cookie).

Your session_cookie is not accessible by JS so it's not vulnerable to XSS. This cookie is sent on each request to the server, which checks is a valid token, otherwise an unauthorized error is returned.

Your SPA cookie hasn't httpOnly flag so it's accessible by JS but the server doesn't use it to authenticate the user, so fake this cookie is useless.

Whenever you receive an unauthorized error on your SPA you can remove the SPA cookie.

like image 147
ilopezluna Avatar answered Sep 20 '22 16:09

ilopezluna