Azure Active Directory controls access to its hosted resources. External applications can request OAuth 2.0 access token from MS identity platform to access Azure resources by providing valid Azure Application Registration App Id and Secret, this application registration must be given permission to the specific resource it requires access to, otherwise Azure AD will reject the request.
As best practices, save both registration App Id and secret in Azure Key Vault to keep these information hidden and secured, for more information on using Key Vault and accessing it by code check my previous blog.
I am not going to discuss how to create Azure AD application registeration, if you need more information on this check this MS doc:
https://docs.microsoft.com/en-us/azure/storage/common/storage-auth-aad-app?tabs=dotnet
The Code
First, you will need to include couple libraries at the top of the class. Below code demonstrates how to acquire access token from Azure AD:
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Threading.Tasks;
class AZAzureAuthDemo
{
public static str acquireAuthToken(str _resourceUri)
{
str authority = 'https://sts.windows.net/AzureActiveDirectoryId/'; // Replace with Azure Active Directory
str appId = ''; // Set Azure Application Id
str appSecret = ''; // Set Azure Application Secret
ClientCredential clientCredentials = new ClientCredential(appId, appSecret);
AuthenticationContext authContext = new AuthenticationContext(authority, false);
System.Uri uriHost = new System.Uri(_resourceUri);
str resourceUrl = uriHost.Uri;
AuthenticationResult result = authContext.AcquireToken(resourceUrl, clientCredentials);
accessToken = result.CreateAuthorizationHeader();
return accessToken;
}
}