Authentication with HttpOnly JWT via cookies using an external API
Does someone maybe know a good tutorial or guide on how to implement authentication in a Nuxt app? I found this website (https://www.pacificcodeline.com/blog/tech/how-to-implement-server-side-jwt-auth-with-nuxt-3-vue-3-and-httponly-cookies) which seems to solve a similar problem as I do: handle authentication via JWT using HttpOnly cookies and persisting the logged-in state over multiple sessions with the cookie. When navigating to a protected page, I want to check if the access and refresh tokens are still valid and refetch the user data if that wasn't already done (in case of a new browser window or tab).
My current solution works partly as the token was first stored in localStorage to persist it, but as this solution is vulnerable to XSS attacks I wanted to switch to using HttpOnly cookies. My API server already returns the cookies after having logged in successfully, but the problem now is, that I want to somehow check if the JWT tokens (access and refresh) are valid and if so, allow routing to a protected page and that user-data fetching mentioned earlier. I just don't know how one would create such a middleware, or if that would even be the ideal workflow. My current approach works besides the fact, that when opening a new tab, the user needs to re-login because in the middleware I don't know how to correctly fetch the user data (can I simply use $fetch in a middleware?).
Ideally, I want to prevent page flickering if a user navigates to a protected page and the client has to check if the user is still logged in. Therefore, the server part of Nuxt should validate the JWT tokens on navigation and redirecting the unauthenticated user to the login page if that's the case.
The problem is, that I don't find any good tutorials or guides, so hopefully someone here can point me to such a resource.
2 Replies