Skip to content

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

Closed

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

Activity

  1. dcworldwide commented on Apr 17, 2017

    @dcworldwide

    @alexstrat I have the same issue.

    Do you mind sharing your implementation for isExpired?

  2. alexstrat commented on Apr 18, 2017

    @alexstrat
    Author

    @dcworldwide here is what i'm using today. You'll find an implementation inisCachedTokenValid.

  3. dcworldwide commented on Apr 18, 2017

    @dcworldwide

    Thanks @alexstrat

  4. mmazzarolo commented on Jul 3, 2017

    @mmazzarolo

    @alexstrat thank you for your snippet, I just embraced your solution and created a simple Koa middleware with it.

    I can clean it up a bit and post it on GitHub if anyone is interested.

  5. mmazzarolo commented on Oct 7, 2017

    @mmazzarolo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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