The expectation here is that the token expiration is 24h. You can check it in Applications > API > Settings > Token Settings.
What I did is refreshing the token every 12 hours.
In my case, I use Spring Boot 3.
package dev.aleixmorgadas.example.configuration; | |
import com.auth0.client.auth.AuthAPI; | |
import com.auth0.client.mgmt.ManagementAPI; | |
import com.auth0.exception.Auth0Exception; | |
import jakarta.validation.constraints.NotBlank; | |
import lombok.RequiredArgsConstructor; | |
import lombok.extern.slf4j.Slf4j; | |
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; | |
import org.springframework.boot.context.properties.ConfigurationProperties; | |
import org.springframework.boot.context.properties.EnableConfigurationProperties; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.scheduling.annotation.EnableScheduling; | |
import org.springframework.scheduling.annotation.Scheduled; | |
import org.springframework.validation.annotation.Validated; | |
@Slf4j | |
@EnableScheduling | |
@Configuration | |
@EnableConfigurationProperties(Auth0Configuration.Auth0Properties.class) | |
@RequiredArgsConstructor | |
@ConditionalOnProperty(value = "auth0.enabled", havingValue = "true") | |
public class Auth0Configuration { | |
final Auth0Properties properties; | |
@Bean | |
AuthAPI authAPI() { | |
return AuthAPI.newBuilder(properties.domain, properties.clientId, properties.clientSecret).build(); | |
} | |
@Bean | |
ManagementAPI managementAPI(AuthAPI authAPI) throws Auth0Exception { | |
var tokenHolder = authAPI.requestToken(properties.audience).execute().getBody(); | |
return ManagementAPI.newBuilder(properties.domain, tokenHolder.getAccessToken()).build(); | |
} | |
@Configuration | |
@RequiredArgsConstructor | |
@EnableConfigurationProperties(Auth0Configuration.Auth0Properties.class) | |
@ConditionalOnProperty(value = "auth0.enabled", havingValue = "true") | |
static class RefreshToken { | |
final Auth0Properties properties; | |
final AuthAPI authAPI; | |
final ManagementAPI managementAPI; | |
@Scheduled(cron = "0 0 0/12 * * ?") | |
void refreshManagementToken() throws Auth0Exception { | |
var token = authAPI.requestToken(properties.audience).execute().getBody(); | |
managementAPI.setApiToken(token.getAccessToken()); | |
} | |
} | |
@Validated | |
@ConfigurationProperties(prefix = "auth0") | |
record Auth0Properties( | |
@NotBlank String domain, | |
@NotBlank String clientId, | |
@NotBlank String clientSecret, | |
@NotBlank String audience | |
) { | |
} | |
} |