See all posts

Azure AD Service Principal with long expiry

1 year ago

I use MacOS, so the commands below are for MacOS. If you are using Windows, you can use the Azure CLI in the Cloud Shell. Or follow instructions to install the Azure CLI on Windows.

As a developer working in Azure, you may often need to work with Azure AD Service Principals to authenticate to Azure resources or other services that use Azure AD as an identity provider. In this case, the goal is to create a client secret that will last for a long time and can be used for authentication with NextAuth.js.

It is generally recommended to use service principals with short expiries and to rotate secrets regularly. However, this tutorial provides a workaround for creating a service principal with a longer expiry for use in development and test environments.

By default, Azure only allows you to create service principals with a maximum expiry of 2 years. To create a service principal with a longer expiry, you can use the Microsoft Graph API and the Azure CLI.

Login to the correct Azure subscription

First, make sure you are logged in to the correct Azure subscription for your project:

az login -t {INPUT_YOUR_SUBSCRIPTION} --allow-no-subscriptions

List all applications in Azure subscription

To find the application ID that you will need to create the service principal, you can either look for the Object ID in the Azure Portal under Overview, or you can list all applications in your subscription using the following command:

az rest \
--method GET \
--uri 'https://graph.microsoft.com/v1.0/{INPUT_YOUR_SUBSCRIPTION}/applications'

Create a service principal

Once you have the application ID, you can use the Azure CLI and the addPassword endpoint to create a new secret with a specific name and a custom expiry date:

az rest \
--method POST \
--headers "Content-Type=application/json" \
--uri 'https://graph.microsoft.com/v1.0/{INPUT_YOUR_SUBSCRIPTION}/applications/{INPUT_YOUR_SERVICE_PRINCIPAL_ID}/addPassword' \
--body '{"passwordCredential":{"displayName":"fitting-password-name","endDateTime":"2222-12-31T00:00:00.000Z"}}'

Be sure to copy the secretText from the response, as you will not be able to retrieve it again.