pocketbase / js-sdk

PocketBase JavaScript SDK
https://www.npmjs.com/package/pocketbase
MIT License
2.17k stars 127 forks source link

Question: oAuth Google Refresh Token #286

Closed haupt-pascal closed 7 months ago

haupt-pascal commented 7 months ago

Cheers! I am Searching for the ability to get the refresh token as well from a user with the pocketbase oauth2 login integration.

The current rough code (don't blame me, just the testing version) is the following. How exactly do I handle to get the refresh token as well? I know, I need to set the access type to offline and maybe the prompt to consent but the ability is inside the oauth ability missing.

async function oAuthLogin() {
  const authData = await pb.collection('users').authWithOAuth2({
    provider: 'google',
    scopes: [
      'https://www.googleapis.com/auth/userinfo.profile',
      'https://www.googleapis.com/auth/userinfo.email',
      'https://www.googleapis.com/auth/youtube',
      'https://www.googleapis.com/auth/youtubepartner',
      'https://www.googleapis.com/auth/youtube.readonly',
      'https://www.googleapis.com/auth/youtube.channel-memberships.creator',
    ],

  })

  //accessType: 'offline',
  //prompt: 'consent',

  console.log(authData)

  if (authData.meta) {
    const data = {
      accessToken: authData.meta.accessToken,
      refreshToken: authData.meta.refreshToken,
    }

    const record = await pb.collection('users').update(authData.record.id, data)
  }

  await navigateTo('/app/dashboard')

  /*
  if (user) {
    alert('Login erfolgreich')
  }
  */
}
ganigeorgiev commented 7 months ago

I don't think your issue is SDK related.

There is no universal control to force an OAuth2 provider to return a refresh token and this usually depends on the specific provider and its OAuth2 app configuration.

You may find useful https://stackoverflow.com/questions/10827920/not-receiving-google-oauth-refresh-token.

The refresh_token is only provided on the first authorization from the user. Subsequent authorizations, such as the kind you make while testing an OAuth2 integration, will not return the refresh_token again.

If you want to modify the query parameters of the OAuth2 auth url you can define your own urlCallback function:

const authData = await pb.collection('users').authWithOAuth2({
  provider: 'google',
  scopes: [
    'https://www.googleapis.com/auth/userinfo.profile',
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/youtube',
    'https://www.googleapis.com/auth/youtubepartner',
    'https://www.googleapis.com/auth/youtube.readonly',
    'https://www.googleapis.com/auth/youtube.channel-memberships.creator',
  ],
  urlCallback: (url) => {
    // modify the url, for example by parsing it into URL: https://developer.mozilla.org/en-US/docs/Web/API/URL 
    // ...
    window.open(url, "popup_window", "width=500,height=500,resizable,menubar=no"); // the last parameters are optional, adjust to your needs
  }  
})