Afolabi Omotoso
Afolabi Omotoso

Reputation: 21

Exception Error while reading from Azure Key Vault

We faced the below exception while trying to read a secret from Azure Key Vault from Service fabric application.

The application uses Client Certificate to authenticate with AAD and access the KeyVault to fetch the secret.

This issue is occurring intermittently.

Is there a way we could identify the root cause so that the same error can be prevented from further occurrences.

Message: AADSTS70002: Error validating credentials. AADSTS50012: Client assertion is not within its valid time range. 
Trace ID: 333ee9c1-c74f-432d-824a-000f38a0e400 
Correlation ID: 35b5cadf-c538-4f75-b1fb-56c4743088f4 
Timestamp: 2018-10-24 06:23:30Z

......

Upvotes: 0

Views: 789

Answers (1)

Joey Cai
Joey Cai

Reputation: 20067

Client assertion is not within its valid time range.

According to your error message and your issue occurs intermittently, I think it may be your token's region time cause the problem. Region time may have some time interval with your token valid time.

So, I suggest that you could use DateTime.UtcNow as standard to set your token start time and end time. Here is a code sample you could refer to.

private static async Task<string> GetClientAssertiotokenAsync(string tenantId,string clientId)
{
    X509Certificate2 cert = new X509Certificate2(@"D:\Joey\Documents\joey.pfx", "password", X509KeyStorageFlags.MachineKeySet);
    var now = DateTime.UtcNow;
    var tokenHandler = new JwtSecurityTokenHandler();
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Audience = $"https://login.microsoftonline.com/{tenantId}/oauth2/token",
        Issuer = clientId,
        NotBefore = now.AddHours(1),
        Expires = now.AddHours(3),
        Subject = new ClaimsIdentity(new[] {
        new Claim("sub",clientId)}),
        SigningCredentials = new X509SigningCredentials(cert)
    };
    SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
    string tokenString = tokenHandler.WriteToken(token);
}

For more details, you could refer to this article.

Upvotes: 0

Related Questions