nuxt-community / auth-module

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

$auth.setUser from JWT token when using PKCE oauth2 flow #1753

Closed zakharov-ilia closed 2 years ago

zakharov-ilia commented 2 years ago

Hello!

I am having some trouble setting user in case of using PKCE oauth2 flow. Authorization server returns some JWT token from token endpoint.

/user endpoint is set to false

Now I'm trying to set user in page is specified as redirect.callback in config by parsing JWT:

/pages/auth.vue

<template>
  <div />
</template>

<script>
export default {
  created () {
    this.$auth.setUser({ ...some user object... }) // parsing JWT token from this.$auth.strategy.token.get() and creating user object
  }
}
</script>

This part of the code works correctly.

But, afret redirecting to main page $auth.user returns an empty object. Looks like $auth module is setting user object after executing code part above.

How to correctly set the user by $auth.setUser()?

Current configuration:

nuxt.config.js

...
auth: {
    watchLoggedIn: true,
    redirect: {
      login: '/login',
      callback: '/auth'
    },
    strategies: {
      oauth2: {
        scheme: 'oauth2',
        endpoints: {
          authorization: 'SOME_AUTH_URL',
          token: 'SOME_TOKEN_URL',
          user: false
        },
        token: {
          property: 'access_token',
          type: 'Bearer',
          maxAge: 1800
        },
        refreshToken: {
          property: 'refresh_token',
          maxAge: 60 * 60 * 24 * 30
        },
        redirectUri: 'http://localhost:3000/auth',
        responseType: 'code',
        grantType: 'authorization_code',
        accessType: 'offline',
        clientId: 'SOME_CLIENT_ID',
        scope: ['offline', 'openid'],
        codeChallengeMethod: 'S256'
      }
    }
  },
  router: {
    middleware: ['auth']
  }
...

/pages/login.vue

<template>
  <div>
    <button @click="handleLogin">
      Login
    </button>
  </div>
</template>

<script>
export default {
  methods: {
    async handleLogin () {
      await this.$auth.loginWith('oauth2')
    }
  }
}
</script>
zakharov-ilia commented 2 years ago

Solved by creating custom scheme and overwriting fetchUser method.