相关文章推荐
痴情的墨镜  ·  c# - mailkit imap ...·  1 年前    · 
豪情万千的羽毛球  ·  android - Flutter ...·  1 年前    · 
奔放的萝卜  ·  使用Active Choice ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

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 .

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. Shivku Mar 10, 2022 at 4:03 This isn't to prevent users from manually including cookies. It's to prevent JS code from accessing cookies. Ignasi Mar 10, 2022 at 12:05

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question . Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers .