nuxt-community / auth-module

Zero-boilerplate authentication support for Nuxt 2
https://auth.nuxtjs.org
MIT License
1.93k stars 924 forks source link

Keycloak OIDC doesn't work with auth middleware #1737

Closed tu-pm closed 2 years ago

tu-pm commented 2 years ago

Version

module: 5.0.0 nuxt: 2.15.8

Nuxt configuration

mode:

auth: {
  strategies: {
    local: false,
    keycloak: {
      scheme: 'openIDConnect',
      endpoints: {
        authorization: `${KEYCLOAK_OIDC_URL}/auth`,
        token: '/token',
        userInfo: `${KEYCLOAK_OIDC_URL}/userinfo`,
        logout: `${KEYCLOAK_OIDC_URL}/logout`
      },
      clientId: process.env.KEYCLOACK_CLIENT_ID,
    },
  },
  redirect: {
    login: '/login',
    callback: '/callback',
    logout: '/',
    home: '/home',
  },
},

Reproduction

Steps to reproduce

Use auth module with openIDConnect authentication strategy configured as above and Keycloak as the identity provider (or any OIDC IDP as I suspect).

What is expected?

After a user is authenticated and redirected to /home page, the $auth.loggedIn flag should be set to true.

What is actually happening?

Instead, after the /home page is loaded, $auth.loggedIn is false and only switches to true a few hundred milliseconds later. This causes the middleware to redirect user to the /login page even when user is properly authorized.

Additional information

After switching to oauth2 strategy, this bug disappears. Looking at the auth module source code, I think there's something wrong with the logic of the _handleCallback() method causing the different in behavior of the two closely-related strategies.

tu-pm commented 2 years ago

I found out where I went wrong: I didn't configure configuration endpoint properly, causing the mounted method to fail on server side. Here's the working configuration with OIDC on keycloak for anyone stumbling upon this:

const KEYCLOAK_BASE_URL = `${process.env.KEYCLOAK_API_URL}/realms/${process.env.KEYCLOAK_REALM}`
const KEYCLOAK_OIDC_URL = `${KEYCLOAK_BASE_URL}/protocol/openid-connect`

export default { 
  ...
  axios: {
    // Workaround to avoid enforcing hard-coded localhost:3000: https://github.com/nuxt-community/axios-module/issues/308
    baseURL: '/',
    proxy: true,
  },
  proxy: {
    '/token': KEYCLOAK_OIDC_URL,
  },
  auth: {
    strategies: {
      local: false,
      keycloak: {
        scheme: 'openIDConnect',
        endpoints: {
          authorization: `${KEYCLOAK_OIDC_URL}/auth`,
          token: '/token',
          userInfo: `${KEYCLOAK_OIDC_URL}/userinfo`,
          logout: `${KEYCLOAK_OIDC_URL}/logout`,
          configuration: `${KEYCLOAK_BASE_URL}/.well-known/openid-configuration`
        },
        clientId: process.env.KEYCLOACK_CLIENT_ID,
      },
    },
    redirect: {
      login: '/login',
      callback: '/callback',
      logout: '/',
      home: '/home',
    },
  },