I'm developing an SPA (React) application, and I want to implement authentication using cookies to keep track of active sessions, and only allow access to certain routes if the user is authenticated.
I want to know how I can develop the SPA in a way that, following best practices, ensures that protected routes (routes that require user authentication) cannot be viewed unless the session cookie is set.
I'm looking at different authentication solutions, and most of them seem to, upon successful authentication, set an HTTP cookie with the attributes: SameSite, Secure, and HttpOnly. The authentication solution will be on the same domain as the SPA, so SameSite makes sense to me. The domain has an SSL certificate, so communication will be over HTTPS, and therefore Secure makes sense to me.
However, as the SPA is javascript, it does not have access to HttpOnly cookies, and therefore not the session cookie.
I can see a few possible solutions to this problem:
- Serve the SPA from a NodeJS app route that requires the session cookie to be set (/app):
Upon succesful authentication from the authentication service, redirect user to the /app endpoint of a NodeJS app, which then validates the cookie sent by the browser. If the cookie is valid, serve the SPA. If not, redirect to authentication service login screen.
This approach is what i suppose most SSR web apps use for each of their routes. However, as this is a SPA, it will only have to be done on the top level route that serves the application.
- Disable HttpOnly flag on session cookie from authentication service
I havn't researched this in depth, but if it is possible to do so, it will open the SPA to XSS attacks, which is something i'd like to avoid.
Is either of these approaches the right way to go? I realize there are multiple ways to solve this problem, but i suspect that best practices exist to solve this, as it is quite common in a lot of web applications today that are developed as an SPA.
A final question - regarding HttpOnly, Secure and SameSite cookies, I realize that browsers such as Chrome, Firefox, Safari, and Edge, prevent people from creating cookies with these attributes. But isn't it possible for someone to somehow, outside of a popular browser, create cookies with these attributes, and thereby getting access to a web app that otherwise requires users to go through an authentication process?