How to create refresh tokens?

I’m working on a twitter pack, already published at:

However, it’s oAuth2 sessions keep expiring. The Twitter docs says I can do:

POST 'https://api.twitter.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'refresh_token=redacted' \
--data-urlencode 'grant_type=refresh_token' \
--data-urlencode 'client_id=redacted'

However, the Coda docs don’t seem to offer any ability to do these automatic oauth refreshes.

Any suggestion would be great, here is the relevant oAuth2 code I’m currently using:

// https://developer.twitter.com/en/docs/authentication/oauth-2-0/user-access-token
// https://developer.twitter.com/en/docs/twitter-api/users/lookup/api-reference/get-users-me
pack.setUserAuthentication({
  type: coda.AuthenticationType.OAuth2,
  authorizationUrl: "https://twitter.com/i/oauth2/authorize",
  tokenUrl: "https://api.twitter.com/2/oauth2/token",
  scopes: ["tweet.read", "tweet.write", "users.read"],
  useProofKeyForCodeExchange: true,
  getConnectionName: async function (context) {
    let response = await context.fetcher.fetch({
      url: 'https://api.twitter.com/2/users/me',
      method: 'GET',
    });
    return response.body.data.username;
  }
});
1 Like

This comment may be useful: Simple recipe for adding per-user authentication for Google APIs to a Coda pack - #2 by Eric_Koleda

1 Like

Hi @balupton - If Coda gets refresh_token from the OAuth provider during the account connection, it will automatically use it to generate a new access_token when the previous one expires. There are a few caveats:

  • We only attempt a refresh when an execution fails due to a 401 error. It’s important that you don’t swallow those 401 errors in your code, but let them bubble up.
  • We don’t support using a different URL for refreshing tokens, but instead use the standard token URL (this works for most APIs).

In your case I think the issue is that you are missing the scope necessary for Twitter to provide a refresh token:

If the scope offline.access is applied an OAuth 2.0 refresh token will be issued.

1 Like

Hrmmm, my Twitter Pack is still requiring me to sign in each day, it does have offline.access applied. Any ideas?

CleanShot 2022-08-22 at 01.00.23

This answer helped me as well. Removing try catch around web requests did let Coda to regenerate refresh tokens. Thanks Eric for the tipp.

1 Like