How to get refresh token using 'auth0-js' popup and google connection

Hi. I’m running a Next.js application which is an SPA app with SSR. I’m able to log users in and retrieve an access token, but how do I get the refresh token? As a second problem, all the access tokens are invalid.

I followed the steps at https://auth0.com/docs/libraries/auth0js/v9#webauth-popup-authorize- and those parts work. Here’s the code below.

  var webAuth = new auth0.WebAuth({
    domain: activeConfig.client.auth.domain,
    clientID: activeConfig.client.auth.clientId
  });
  const google = () => {
    webAuth.popup.authorize({
      domain: activeConfig.client.auth.domain,
      redirectUri: 'http://localhost:8443/checkout-social-auth',
      connection: 'google-oauth2',
      responseType: 'token id_token',
      scope: 'openid profile email offline_access',
    }, (_err: auth0.Auth0Error | null, authRes: auth0.Auth0Result) => {
      // authRes.accessToken = "vrdRNvvU8quDuu1y0JD1uM2j4l48RLXR"
      // authRes.refreshToken is null
      console.log(authRes);
    });
  }
1 Like

Hi simonlvuong and welcome to the community! :partying_face:

You are using the implicit flow which won’t return refresh tokens because it isn’t secure. If you want to get a refresh token in a SPA, you need to use the PKCE flow: https://auth0.com/docs/api-auth/tutorials/authorization-code-grant-pkce

Otherwise, you will need to use a backend server to fetch it, and switch to a different flow.

Thanks. Gotcha. So I actually did switch to backend to fetch it with authorization-code flow. That does the trick.

However I’m still having issues with my tokens. I get the following responses. Any idea why these tokens would be empty?

access_token: 'hEFv2T5yi4zz2VARU1EimLlZTV9-x6a5',
refresh_token: 'XZ5oZMv3H0nFswVEyJhiQ4rDakQ8hqT2gEO3-tLjktXHy'

With “empty” do you mean why you’re getting an opaque token (string) instead of a JWT ? That’s because you’re not passing an audience parameter in the request.
The audience parameter would be the API identifier for the backend/API (resource server) that the access token would be used for.

If it’s not something you need in your use case (in case you’re just interested in authentication but not authorization), the opaque access token you’ve got will work just fine for retrieving the user information from the Auth0 (https://YOUR_TENANT.auth0.com/userinfo endpoint)

2 Likes