Giter Club home page Giter Club logo

Comments (14)

silvio-e avatar silvio-e commented on July 20, 2024 1

@PGLongo Awesome! Very kind of you! Thank you very much!

from nuxt-auth-utils.

PGLongo avatar PGLongo commented on July 20, 2024 1

@PGLongo Awesome! Very kind of you! Thank you very much!

Sharing is caring! 😊

If you have any questions or need further assistance, feel free to reach out. Happy coding!

from nuxt-auth-utils.

amandesai01 avatar amandesai01 commented on July 20, 2024

I believe there should be a refresh token implementation. Is this open to PR?

from nuxt-auth-utils.

Atinux avatar Atinux commented on July 20, 2024

Refresh tokens are not implemented so far as we just give back to the session what's needed and some OAuth does not handle refresh tokens.

Do you have an example of an implementation you would like to see?

from nuxt-auth-utils.

PGLongo avatar PGLongo commented on July 20, 2024

@septatrix I have successfully achieved the refresh of the session with the session hook for 'fetch'. If the session has expired and I have a valid refresh token, then the refresh workflow is initiated to obtain a new valid token.

from nuxt-auth-utils.

septatrix avatar septatrix commented on July 20, 2024

@septatrix I have successfully achieved the refresh of the session with the session hook for 'fetch'. If the session has expired and I have a valid refresh token, then the refresh workflow is initiated to obtain a new valid token.

Would you mind sharing the code for that?

from nuxt-auth-utils.

silvio-e avatar silvio-e commented on July 20, 2024

@PGLongo I would be also very interested in that! 😊

from nuxt-auth-utils.

PGLongo avatar PGLongo commented on July 20, 2024

Sure! Here I refresh the Microsoft Oauth. Note that in the auth handler I have stored the expirationDate in the session.user

// server/plugins/session.ts


import { useRuntimeConfig } from '#imports'
import type { OAuthMicrosoftConfig } from '~/server/api/auth/login.get'

export default defineNitroPlugin(() => {
  sessionHooks.hook('fetch', async (session, event) => {
    const now = new Date()
    const expirationDate = new Date(session.user.expirationDate)
    const jwt = getCookie(event, 'jwt')
    console.log(expirationDate < now, expirationDate, now)
    if (expirationDate < now || !jwt) {
      const config = useRuntimeConfig(event).oauth?.microsoft as OAuthMicrosoftConfig

      const tokenEndpoint = `https://login.microsoftonline.com/${config.tenant!}/oauth2/v2.0/token`
      const params = new URLSearchParams()
      const refreshToken = getCookie(event, 'refresh-token') || ''

      params.append('client_id', config.clientId!)
      params.append('client_secret', config.clientSecret!)
      params.append('refresh_token', refreshToken)
      params.append('grant_type', 'refresh_token')

      const data = await $fetch(tokenEndpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
      })
      const now = new Date()
      session.user.expirationDate = new Date(now.getTime() + data.expires_in * 1000)
      await setCookie(event, 'jwt', data.access_token, { httpOnly: true, secure: true, maxAge: data.expires_in })
    }
  })

  sessionHooks.hook('clear', async (session, event) => {
    await deleteCookie(event, 'jwt')
    await deleteCookie(event, 'refresh-token')
  })
})

from nuxt-auth-utils.

thijsw avatar thijsw commented on July 20, 2024

Thank you, @PGLongo, for providing an example implementation of the refresh dynamic!

Inspired by your code, I created a similar plugin that refreshes the tokens when the access token expires. The problem I'm facing is that the sealed session cookie is never updated, so the original contents remain unchanged. After the access token expires the first time, it refreshes the tokens on every subsequent page refresh. Do you have a solution for this issue?

My code:

// server/plugins/session.ts

export default defineNitroPlugin(() => {
  sessionHooks.hook('fetch', async (session, event) => {
    const authenticationConfig = getAuthenticationConfig(event) // Configuration helper
    const now = new Date()
    const expirationDate = new Date(session.expirationDate)

    if (expirationDate < now) {
      // Refresh session
      const body = new FormData()
      body.append('grant_type', 'refresh_token')
      body.append('refresh_token', session.refreshToken)
      body.append('response_type', 'id_token')
      body.append('client_id', authenticationConfig.clientId)
      body.append('client_secret', authenticationConfig.clientSecret)
      body.append('scope', authenticationConfig.scope)

      const token = await $fetch<AccessToken>(authenticationConfig.tokenURL, {
        method: 'post',
        body
      })

      session.accessToken = token.access_token
      session.refreshToken = token.refresh_token
      session.expirationDate = new Date(now.getTime() + token.expires_in * 1000)
    }
  })
})

from nuxt-auth-utils.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.