How to secure private routes in SPA while using httpOnly cookies
Asked Answered
B

1

13

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?

Balsamic answered 7/8, 2018 at 8:44 Comment(0)
D
31

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.

Deoxyribonuclease answered 22/8, 2018 at 11:16 Comment(6)
I like the idea. Thanks :)Balsamic
I know that a causal user will be unable to access the secure pages, but this does not prevent a user from adding the 'SPA cookie' manually and accessing the secure pages.Delsiedelsman
This isn't to prevent users from manually including cookies. It's to prevent JS code from accessing cookies.Deoxyribonuclease
Correct me if I'm wrong. A user manually updates spa cookie, he can access other routes in this SPA, But he could not make any API call from it(as long as the http cookie is expired or cleared)Carbazole
That is correct @CarbazoleDeoxyribonuclease
In this scenario, how would the user pass the session_cookie in subsequent api endpoint requests if it does not have access to the session_cookie?Lido

© 2022 - 2024 — McMap. All rights reserved.