Let me provide a comprehensive solution covering all the OAuth2 token lifecycle aspects:
Token Lifecycle Management Strategy:
Implement token management at your middleware/integration layer, not in D365 batch jobs. This keeps your OAuth2 logic centralized and reusable across multiple jobs.
Refresh Token Implementation:
Create a TokenManager class that handles the complete OAuth2 token lifecycle:
// Pseudocode - Token Manager Pattern:
1. Store access token, refresh token, and expiry timestamp
2. Before each API call, check if token expires in <5 minutes
3. If expiring soon, use refresh token to get new access token
4. Update stored tokens and reset expiry timestamp
5. If refresh fails, fall back to full re-authentication
6. Implement retry logic with exponential backoff (2s, 4s, 8s)
API Job Configuration Best Practices:
For your asset management scheduled jobs:
-
Token Acquisition: Obtain initial OAuth2 token before job execution starts, not during first API call
-
Proactive Refresh: Set refresh trigger at 50 minutes (3000 seconds) to stay well ahead of 60-minute expiry
-
Error Handling: Wrap all API calls in try-catch that specifically handles 401 errors. On 401, immediately attempt token refresh before retrying the failed operation
-
Logging Strategy: Log these events separately:
- Initial token acquisition
- Proactive refresh operations
- Failed API calls due to auth
- Refresh token failures
- Fallback to full re-authentication
-
Configuration Parameters: Make these configurable:
- Token refresh threshold (default 3000s)
- Maximum retry attempts (default 3)
- Backoff multiplier (default 2s base)
Azure AD Considerations:
Verify your Azure AD token lifetime policies:
- Access token lifetime: typically 60-90 minutes
- Refresh token lifetime: 90 days inactive, 180 days active use
- Ensure your app registration has offline_access scope for refresh tokens
Implementation for Long-Running Jobs:
For asset management operations exceeding 1 hour:
// Pseudocode - Job Execution Pattern:
1. Acquire initial OAuth2 token with refresh token scope
2. Process assets in batches (e.g., 100 assets per batch)
3. Before each batch, check token expiry
4. If <5 min remaining, refresh proactively
5. Execute batch with current valid token
6. Log batch completion with token status
Monitoring and Diagnostics:
Implement these metrics:
- Token refresh frequency per job
- Failed refresh attempts
- API calls rejected due to auth (should approach zero)
- Average job duration vs token lifetime
This approach ensures your scheduled jobs handle OAuth2 token lifecycle properly, implement robust refresh token logic, and configure API jobs to prevent authentication failures. The key is proactive refresh rather than reactive error handling.
One final note: test your implementation with jobs that deliberately exceed 60 minutes to verify the refresh mechanism works correctly under real conditions.
This draft is based on general Microsoft Dynamics 365 knowledge. It has not been verified against your specific version and environment. Practitioners: verify the steps and share your experience below.