atinux / nuxt-auth-utils

Add Authentication to Nuxt applications with secured & sealed cookies sessions.
MIT License
974 stars 91 forks source link

Failed redirect authentication request to http://localhost/api/_auth/session on start #124

Closed HoldenMalinchock closed 3 months ago

HoldenMalinchock commented 4 months ago

I am trying to setup auth to a locally hosted key cloak application in my nuxt app. I had it working with the nuxt-oidc-auth module just fine. However that module didn't seem to have server utils for auth sessions so I am trying to use this module instead.

My goal is to to have all pages check if they are auth'd and if not go request oidc auth to key cloak and then come back, and then use the server utils like getUserSession with server/middleware to control api access.

I have gone through the basic setup and followed the guide however I can't seem to figure out why is it doing what it is doing.

I setup a runtime with my configuration:

runtimeConfig {
  oath: {
    keycloak: {
      clientId: "my-id",
      clientSecret: "My-Secret",
      serverUrl: "https://my-serverurl/auth/realms",
...

I also configured a api auth route for key cloak server/api/auth/keycloak.get.ts and changed the GitHub example to match key cloak so oauth.keycloakEventHandler({...})

However my problem is when I open the application to route / it immediately makes a call to: http://localhost/api/_auth/session

Which returns a 401 and then the application just loads as normal. So keycloak server is never even sent a request to auth. Reviewing the reason that endpoint fails it is because that endpoint calls requireUserSession() which returns 401 unauthorized. But this is my first request to the app so of course there is no user yet so that is intended behavior.

What am I missing? it feels like I am missing a config because I don't feel that http://localhost/api/_auth/session should be the first request when opening the page.

atinux commented 4 months ago

The request to /api/_auth/session is to decode the current user session to know if the user is authenticated or not.

This is how we can provide:

const { loggedIn, user } = useUserSession()