These .NET Core samples show how to use Azure AD Service Principals and Managed Identities to authenticate to Azure DevOps using Microsoft Authentication Library for .NET (MSAL.NET) and the Azure DevOps .NET client libraries.
Project | Description |
---|---|
0-SimpleConsoleApp-AppRegistration | It uses an Azure AD Application Service Principal to create get a work item. |
1-ConsoleApp-AppRegistration | It uses an Azure AD Application Service Principal to perform multiple operations in Azure DevOps. It also shows how to use the MSAL in-memory token cache and handle the access token expiration. |
2-ConsoleApp-ManagedIdentity | It uses an Azure AD Managed Identity to get a work item. |
3-AzureFunction-ManagedIdentity | It uses an Azure AD Managed Identity to get a work item using an Azure Function. |
Learn how to use Azure AD Service Principals with the client libs.
Creating Azure DevOps credentials is very similar in both cases:
// Azure DevOps PAT
var credentials = new VssBasicCredential(string.Empty, "pat_secret");
// Azure AD Service Principal access token
var token = new VssAadToken("Bearer", "aad_access_token");
var credentials = new VssAadCredential(token);
Then any of them can be used to create an instance of VssConnection
(remember that this instance should be a singleton in the application):
var organizationUrl = "http://dev.azure.com/Fabrikam";
var vssConnection = new VssConnection(organizationUrl, credentials);
var adoClient = vssConnection.GetClient<_AdoHttpClient_>();
As Azure AD access tokens are short-lived, you can provide a delegate to VssAadToken
to acquire a new access token when the existing one expires. Microsoft Authentication Library for .NET (MSAL.NET) has a token cache and handles automatically the token acquisition when an access token is expired.
For example, using an Azure AD application with a client secret:
Note: At the moment of writing this,
VssAadToken
does not support asynchronous delegates
var app = ConfidentialClientApplicationBuilder.Create("client_id")
.WithClientSecret("client_secret")
.WithAuthority("https://login.microsoftonline.com/tenant_id")
.Build();
// It uses Azure DevOps default scope (499b84ac-1321-427f-aa17-267ca6975798/.default)
var token = new VssAadToken((scopes) => app.AcquireTokenForClient(scopes).ExecuteAsync().SyncResultConfigured());
var credentials = new VssAadCredential(token);
See 1-ConsoleApp-AppRegistration for more information.