You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Recommended way to re-inject renewed token for Management API in a long-running script? #164
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:
letcachedToken=nullconstgetToken()=>{if(cachedToken&&!isExpired(cachedToken)){returnPromise.resolve(cachedToken)}returngenerateToken()// will ask a token.then(token=>{cachedToken=tokenreturntoken})}constgetClient=>{returngetToken().then(token=>newManagementClient({domain: 'MY_DOMAIN',
token
}))}// usagegetClient().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:
constauth0=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
constauth0=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
Reacted by Marino, Simon Fenton, Fred Guth, dc, Derrick Liu, Nathan Cooke and Robert Washbourne
Activity
dcworldwide commentedon Apr 17, 2017
@alexstrat I have the same issue.
Do you mind sharing your implementation for
isExpired?alexstrat commentedon Apr 18, 2017
@dcworldwide here is what i'm using today. You'll find an implementation in
isCachedTokenValid.dcworldwide commentedon Apr 18, 2017
Thanks @alexstrat
mmazzarolo commentedon Jul 3, 2017
@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.
mmazzarolo commentedon Oct 7, 2017
If anyone else is still interested, this middleware is now running in a production ready app
luisrudge commentedon Apr 16, 2018
This is part of the SDK now: https://github.com/auth0/node-auth0#management-api-client