使用Microsoft Java SDK连接Azure时遇AADSTS凭证验证错误求助
Hey there, let's work through this "Client assertion is not within its valid time range" error you're hitting. This issue almost always ties back to time synchronization problems or certificate validity, so let's break down the fixes step by step:
Common Causes & Fixes
1. Local System Time is Out of Sync with UTC
Azure AD enforces strict time checks (max 5-minute offset from UTC) for client assertions—this is the most frequent culprit:
- Check your system time: Verify your local machine/server's time matches UTC. Even a small drift can trigger this error.
- Enable automatic time sync:
- On Windows: Go to Settings > Time & Language > Date & Time, enable "Set time automatically".
- On Linux: Use
chronyorntpdto sync with a reliable NTP server (e.g., pool.ntp.org).
2. Your P12 Certificate Has an Invalid Validity Period
Double-check that your certificate is active (not expired and already valid):
- Use this
keytoolcommand to inspect your P12 certificate's details:keytool -list -v -keystore your-certificate.p12 -storetype PKCS12 - Look for the
Valid fromandValid untilfields. If the current time isn't within this window:- Generate a new certificate with a valid expiration (e.g., using OpenSSL with
-days 365to set a 1-year validity). - Re-upload the new public
.crtfile to your Azure AD App Registration > Certificates & secrets. - Update your Java code to use the new P12 file.
- Generate a new certificate with a valid expiration (e.g., using OpenSSL with
3. Incorrect Azure Environment Configuration
If you're using a regional Azure cloud (like Azure China, Government), make sure you're passing the right AzureEnvironment in your code:
- For global Azure:
AzureEnvironment.AZURE - For Azure China:
AzureEnvironment.AZURE_CHINA
Mismatched environments can sometimes lead to time zone or validation discrepancies.
4. Test with Azure CLI to Isolate Issues
To rule out code-specific problems, test your certificate authentication using Azure CLI:
az login --service-principal -u <your-client-id> -t <your-tenant-id> --cert @your-public-cert.crt --key @your-private-key.key
If this login fails with the same time range error, the issue is definitely with your certificate or system time—not your Java code.
Verify Your Code Setup
Quick sanity check on your code snippet:
Ensure you're initializing ApplicationTokenCredentials correctly with all required parameters:
ApplicationTokenCredentials credentials = new ApplicationTokenCredentials( "your-client-id", "your-tenant-id", Files.readAllBytes(Paths.get("path/to/your-cert.p12")), "your-p12-password", AzureEnvironment.AZURE // Use the correct environment for your region ); Azure azure = Azure.authenticate(credentials).withSubscription("your-subscription-id");
AADSTS70002: Error validating credentials. AADSTS50012: Client assertion is not within its valid time range.
内容的提问来源于stack exchange,提问作者Kumar

