How can I tell when a Azure AD client secret expires?
I have many applications registered in Azure AD Tenant and many of these are having client secret keys issued for 1 or 2 years. Is there a way to get an alert before the expiry as expired keys will cause an outage.
We can also query the application
to get the end-date of secret key. Here is a code sample using client credentials flow via the Azure Graph client for your reference. And please ensure that you have grant the app with Directory.Read.All
permission to this API for using client credentials flow.
var graphResourceId = "https://graph.windows.net";
var appId= "";
var appObjectId = "";
var secret = "";
var clientCredential = new ClientCredential(appId,secret);
var tenantId = "xxx.onmicrosoft.com";
AuthenticationContext authContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenantId}");
var accessToken = authContext.AcquireTokenAsync(graphResourceId, clientCredential).Result.AccessToken;
Uri servicePointUri = new Uri(graphResourceId);
Uri serviceRoot = new Uri(servicePointUri, tenantId);
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await Task.FromResult(accessToken));
var app = activeDirectoryClient.Applications.GetByObjectId(appObjectId).ExecuteAsync().Result;
foreach (var passwordCredential in app.PasswordCredentials)
{
Console.WriteLine($"KeyID:{passwordCredential.KeyId}\r\nEndDate:{passwordCredential.EndDate}\r\n");
}
At this time, there is no out of the box mechanism for alerting when client secrets are expiring.
You can vote for this ask in the Azure AD Feedback Entry: Need email alert option when keys are about to expire
Alternatively, you can build your own alerting mechanism by polling the Graph (currently the Azure AD Graph and eventually the Microsoft Graph once /servicePrincipals is in /v1.0/ in there).
Query /servicePrincipals
and filter on PasswordCredentials.EndDate
and KeyCredentials.EndDate
.
You'll need to do your filtering client side since Graph doesn't support filtering on these values yet.
2021-12-07 Update
Azure AD Graph has been deprecated.
Query Microsoft Graph's /servicePrincipals
and filter on the EndDate
property of the PasswordCredentials
object.