Hi Samantha,
When integrating external APIs with bearer tokens in BC, tracking token expiry is essential to avoid failed calls and unnecessary re-authentication. Since AL doesn’t natively decode JWT tokens or expose expiry metadata, the cleanest approach is to store and compare timestamps manually.
Here’s a practical pattern:
When you first request the token, capture both the token string and its expiry time (usually returned in the response as expires_in or expires_at). Store these in a table or single-instance record:
AccessToken: Text
TokenCreatedAt: DateTime
TokenExpiresIn: Integer (seconds or minutes)
Then, before making any API call, check whether the current time exceeds the expiry threshold:
al
procedure IsTokenExpired(): Boolean
var
TokenCreatedAt: DateTime;
TokenExpiresIn: Integer;
CurrentTime: DateTime;
begin
// Retrieve stored values
TokenCreatedAt := GetTokenCreatedAt();
TokenExpiresIn := GetTokenExpiresIn();
CurrentTime := CurrentDateTime();
exit(CurrentTime > TokenCreatedAt + (TokenExpiresIn * 1000)); // Convert seconds to milliseconds
end;
If IsTokenExpired returns true, trigger a refresh or re-authentication flow. You can also add a buffer (e.g., 5 minutes) to avoid edge cases.
For JWT tokens, if you want to decode the payload and extract the exp claim directly, you’ll need a custom .NET interop or external service, AL alone doesn’t support base64 decoding or JSON parsing of JWT segments.
Helpful Reference
OAuth token expiry handling – Dynamics Community
Service-to-service authentication in BC – Andrei Lungu
Handling token timeouts in API calls – Microsoft Fabric Community
Authenticating users with Azure AD – Microsoft Learn
If you find this helpful, feel free to mark this as the suggested or verified answer.
Cheers
Jeffrey