Auth0 M2M tokens in NestJS backend: how to renew?

  Kiến thức lập trình

I’ve successfully created an @Injectable that holds an access token returned by Auth0 (which I will use in an instance of ManagementClient):

auth0.module.ts (ignoring imports)

@Module({
  imports: [HttpModule],
  providers: [
    {
      provide: 'ACCESS_TOKEN',
      useFactory: async (
        configService: ConfigService,
        httpService: HttpService,
      ) => {
        const issuer = configService.get<string>('AUTH0_ISSUER');
        const clientId = configService.get<string>('AUTH0_M2M_CLIENT_ID');
        const clientSecret = configService.get<string>(
          'AUTH0_M2M_CLIENT_SECRET',
        );

        const result = await firstValueFrom(
          httpService
            .post(`${issuer}/oauth/token`, {
              grant_type: 'client_credentials',
              client_id: clientId,
              client_secret: clientSecret,
              audience: `${issuer}/api/v2/`,
            })
            .pipe(
              map((response) => response.data), // get rid of circular reference
              catchError((error: AxiosError) => {
                return throwError(() => error); // return an observable
              }),
            ),
        );

        return result.access_token;
      },
      inject: [ConfigService, HttpService],
    },

But I understand that this is going to be run during backend startup, and then ACCESS_TOKEN will have its value that eventually will expire.

How is it handled the case in which this token needs to be renewed (as I understand, just by asking a new one)?

Am I using a wrong approach in this case? (and instead of getting the access token like this, I may need to “ask” for it in each request and I’m going to get either a new one or the same one, but by using directly clientId and clientSecret instead of generating a token).

Thanks.

LEAVE A COMMENT