Skip to content

Recommended way to re-inject renewed token for Management API in a long-running script? #164

@alexstrat

Description

@alexstrat

I got a script running indefinitely (a web server actually) that needs to access the Management API. I manually generate a token, like described here, use it, but after 24h it's expired. Normal.

I understood I got to automate the process of periodically generate a new token and inject it in my running script (right?), but can't find any recommended way to do it, nor come up with an elegant solution.

The solution I'm using now looks like this:

let cachedToken = null

const getToken () => {
  if (cachedToken && !isExpired(cachedToken)) {
    return Promise.resolve(cachedToken)
  }
  return generateToken() // will ask a token
    .then(token => {
      cachedToken = token
      return token
    }) 
}

const getClient => {
  return getToken()
    .then(token => new ManagementClient({
      domain: 'MY_DOMAIN',
      token
    }))
}

// usage
getClient()
  .then(c => c.getUsers())
  .then(users => doSomething(users))

It's clumsy and un-elegant, esp. because I got to asynchronously get the client each time I need it.

Has anyone found a better method?

It would be much better if the ManagementClient could hide that logic and asynchronousity:

const auth0 = ManagementClient({ domain, clientId, clientSecret })
auth0.getUsers() // will get a token or use the one cached before actually making the API request

Alternatively, the ManagementClient could add the possibility to dynamically inject the token and let the developer responsible for generating and caching the token

const auth0 = ManagementClient({
  domain,
  token: () => getTokenFromCacheOrGenerate()
})
// getTokenFormCacheOrGenerate is implemented by developer
// it should return a promise that resolves to a valid token to be used in API calls

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions