-
Notifications
You must be signed in to change notification settings - Fork 317
Description
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 requestAlternatively, 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