Skip to content

Commit 68169cc

Browse files
committed
add code
1 parent c0017eb commit 68169cc

File tree

1 file changed

+54
-65
lines changed

1 file changed

+54
-65
lines changed

articles/batch/batch-aad-auth.md

Lines changed: 54 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
title: Authenticate Azure Batch services with Azure Active Directory
33
description: Learn how to authenticate Azure Batch service applications with Azure AD by using integrated authentication or a service principal.
44
ms.topic: how-to
5-
ms.date: 03/30/2023
5+
ms.date: 04/03/2023
66
ms.custom: has-adal-ref, subject-rbac-steps
77
---
88

@@ -182,7 +182,7 @@ The code examples in this section show how to authenticate with Azure AD by usin
182182

183183
To authenticate with integrated authentication from Batch .NET:
184184

185-
1. Install the [Azure Batch .NET](https://www.nuget.org/packages/Microsoft.Azure.Batch/) package and the [MSAL](https://www.nuget.org/packages/Microsoft.Identity.Client/) NuGet packages.
185+
1. Install the [Azure Batch .NET](https://www.nuget.org/packages/Microsoft.Azure.Batch/) and the [MSAL](https://www.nuget.org/packages/Microsoft.Identity.Client/) NuGet packages.
186186

187187
1. Include the following `using` statements in your code:
188188

@@ -222,43 +222,38 @@ To authenticate with integrated authentication from Batch .NET:
222222
private const string RedirectUri = "https://<redirect-uri>";
223223
```
224224

225-
1. Write a callback method to acquire the authentication token from Azure AD. The following [ConfidentialClientApplicationBuilder.Create](/dotnet/api/microsoft.identity.client.confidentialclientapplicationbuilder.create) method calls MSAL to authenticate a user who's interacting with the application. The MSAL [IConfidentialClientApplication.AcquireTokenByAuthorizationCode](/dotnet/api/microsoft.identity.client.iconfidentialclientapplication.acquiretokenbyauthorizationcode) method prompts the user for their credentials. The application proceeds once the user provides the credentials, unless the app has already cached the credentials.
225+
1. Write a callback method to acquire the authentication token from Azure AD. The following example calls MSAL to authenticate a user who's interacting with the application. The application proceeds once the user provides credentials, unless the app has already cached the credentials.
226+
227+
This method uses [ConfidentialClientApplicationBuilder.Create](/dotnet/api/microsoft.identity.client.confidentialclientapplicationbuilder.create) to instantiate `IConfidentialClientApplication`. The MSAL [IConfidentialClientApplication.AcquireTokenByAuthorizationCode](/dotnet/api/microsoft.identity.client.iconfidentialclientapplication.acquiretokenbyauthorizationcode) method prompts the user for their credentials.
228+
229+
`WithRedirectUri` specifies the redirect URI that the authorization server redirects the user to after authentication. The *authorizationCode* parameter is the authorization code obtained from the authorization server after the user authenticates.
226230

227231
```csharp
228-
public IConfidentialClientApplication CreateApplication()
229-
{
230-
IConfidentialClientApplication app;
231-
232-
app = ConfidentialClientApplicationBuilder.Create(ClientId)
233-
.WithAuthority(AuthorityUri)
234-
.WithRedirectUri(RedirectUri.ToString())
235-
.Build();
236-
237-
return app;
238-
}
239-
240-
// Called from 'code received event'.
241-
public async Task<AuthenticationResult> GetAuthenticationResult(
242-
string authorizationCode)
243-
{
244-
IConfidentialClientApplication app = CreateApplication();
245-
246-
var authResult = await app.AcquireTokenByAuthorizationCode(
247-
new[] { BatchResourceUri },
248-
authorizationCode)
249-
.ExecuteAsync()
250-
.ConfigureAwait(false);
251-
252-
return authResult;
253-
}
254-
```
232+
public static async Task<string> GetTokenUsingAuthorizationCode(string authorizationCode, string redirectUri, string[] scopes)
233+
{
234+
var app = ConfidentialClientApplicationBuilder.Create(ClientId)
235+
.WithAuthority(new Uri(AuthorityUri))
236+
.WithRedirectUri(RedirectUri)
237+
.Build();
238+
239+
var authResult = await app.AcquireTokenByAuthorizationCode(scopes, authorizationCode).ExecuteAsync();
240+
return authResult.AccessToken;
241+
}
242+
```
243+
244+
1. Call this method with the following code, replacing `<authorization-code>` with the authorization code obtained from the authorization server. The `.default` scope ensures that the user has permission to access all the scopes for the resource.
245+
246+
```csharp
247+
248+
var token = await GetTokenUsingAuthorizationCode("<authorization-code>", "RedirectUri", new string[] { "BatchResourceUri/.default" });
249+
```
255250

256251
1. Construct a **BatchTokenCredentials** object that takes the delegate as a parameter. Use those credentials to open a **BatchClient** object. Then use the **BatchClient** object for subsequent operations against the Batch service:
257252

258253
```csharp
259254
public static void PerformBatchOperations()
260255
{
261-
Func<Task<string>> tokenProvider = () => GetAuthenticationTokenAsync();
256+
Func<Task<string>> tokenProvider = () => GetAccessTokenAsync();
262257

263258
using (var client = BatchClient.Open(new BatchTokenCredentials(BatchAccountUrl, tokenProvider)))
264259
{
@@ -273,7 +268,7 @@ To authenticate with a service principal from Batch .NET:
273268

274269
1. Install the [Azure Batch .NET](https://www.nuget.org/packages/Azure.Batch/) and the [MSAL](https://www.nuget.org/packages/Microsoft.Identity.Client/) NuGet packages.
275270

276-
1. Include the following `using` statements in your code:
271+
1. Declare the following `using` statements in your code:
277272

278273
```csharp
279274
using Microsoft.Azure.Batch;
@@ -311,42 +306,32 @@ To authenticate with a service principal from Batch .NET:
311306
private const string ClientKey = "<secret-key>";
312307
```
313308

314-
1. Write a callback method to acquire the authentication token from Azure AD. The following [ConfidentialClientApplicationBuilder.Create](/dotnet/api/microsoft.identity.client.confidentialclientapplicationbuilder.create) method calls MSAL for unattended authentication:
309+
1. Write a callback method to acquire the authentication token from Azure AD. The following [ConfidentialClientApplicationBuilder.Create](/dotnet/api/microsoft.identity.client.confidentialclientapplicationbuilder.create) method calls MSAL for unattended authentication.
315310

316-
```csharp
317-
public IConfidentialClientApplication CreateApplication()
318-
{
319-
IConfidentialClientApplication app;
320-
321-
{
322-
app = ConfidentialClientApplicationBuilder.Create(ClientId)
323-
.WithSecret(ClientKey)
324-
.WithAuthority(AuthorityUri)
325-
.Build();
326-
}
327-
328-
// Called from 'code received event'.
329-
public async Task<AuthenticationResult> GetAuthenticationResult(
330-
string BatchResourceUri,
331-
string tokenUsedToCallTheWebApi)
332-
333-
var userAssertion = new UserAssertion(tokenUsedToCallTheWebApi);
334-
335-
var authResult = await app.AcquireTokenOnBehalfOf(
336-
new [] { $"BatchResourceUri/.default" },
337-
userAssertion)
338-
.ExecuteAsync()
339-
340-
return authResult;
341-
}
342-
```
311+
```csharp
312+
public static async Task<string> GetAccessToken(string[] scopes)
313+
{
314+
var app = ConfidentialClientApplicationBuilder.Create(clientId)
315+
.WithClientSecret(ClientKey)
316+
.WithAuthority(new Uri(AuthorityUri))
317+
.Build();
318+
319+
var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
320+
return result.AccessToken;
321+
}
322+
```
323+
1. Call this method by using the following code. The `.default` scope ensures that the application has permission to access all the scopes for the resource.
324+
325+
```csharp
326+
var token = await GetAccessToken(new string[] { "BatchResourceId/.default" });
327+
```
343328

344329
1. Construct a **BatchTokenCredentials** object that takes the delegate as a parameter. Use those credentials to open a **BatchClient** object. Then use the **BatchClient** object for subsequent operations against the Batch service:
345330

346331
```csharp
347332
public static void PerformBatchOperations()
348333
{
349-
Func<Task<string>> tokenProvider = () => GetAuthenticationTokenAsync();
334+
Func<Task<string>> tokenProvider = () => GetAccessToken();
350335

351336
using (var client = BatchClient.Open(new BatchTokenCredentials(BatchAccountUrl, tokenProvider)))
352337
{
@@ -359,14 +344,14 @@ To authenticate with a service principal from Batch .NET:
359344

360345
To authenticate with a service principal from Batch Python:
361346

362-
1. Install and reference the [azure-batch](https://pypi.org/project/azure-batch/) and [azure-common](https://pypi.org/project/azure-common/) Python modules.
347+
1. Install the [azure-batch](https://pypi.org/project/azure-batch/) and [azure-common](https://pypi.org/project/azure-common/) Python modules. Reference the modules:
363348

364349
```python
365350
from azure.batch import BatchServiceClient
366351
from azure.common.credentials import ServicePrincipalCredentials
367352
```
368353

369-
1. When you use a service principal, you must provide a tenant-specific endpoint. You can get your tenant ID from the **Properties** page of your Azure AD in the Azure portal.
354+
1. When you use a service principal, you must provide a tenant-specific endpoint. You can get your tenant ID from the Azure AD **Overview** page or **Properties** page in the Azure portal.
370355

371356
```python
372357
TENANT_ID = "<tenant-id>"
@@ -416,13 +401,17 @@ To authenticate with a service principal from Batch Python:
416401
)
417402
```
418403

404+
For a Python example of how to create a Batch client authenticated by using an Azure AD token, see the [Deploying Azure Batch Custom Image with a Python Script sample](https://github.com/azurebigcompute/recipes/blob/master/Azure%20Batch/CustomImages/CustomImagePython.md).
405+
419406
## Next steps
420407

421408
- For in-depth examples that show how to use MSAL, see the [Azure code samples library](/samples/browse/?products=microsoft-authentication-library).
422-
- For a Python example of how to create a Batch client authenticated by using an Azure AD token, see the [Deploying Azure Batch Custom Image with a Python Script sample](https://github.com/azurebigcompute/recipes/blob/master/Azure%20Batch/CustomImages/CustomImagePython.md).
423409

424410
For more information, see:
425411

412+
- [Authenticate Batch Management solutions with Active Directory](batch-aad-auth-management.md)
413+
- [Client credential flows in MSAL.NET](/entra/msal/dotnet/acquiring-tokens/web-apps-apis/client-credential-flows)
414+
- [Using MSAL.NET to get tokens by authorization code (for web sites)](/entra/msal/dotnet/acquiring-tokens/web-apps-apis/authorization-codes)
426415
- [Application and service principal objects in Azure Active Directory](/azure/active-directory/develop/app-objects-and-service-principals)
427416
- [How to create an Azure AD application and service principal that can access resources](/azure/active-directory/develop/howto-create-service-principal-portal)
428-
- [Authenticate Batch Management solutions with Active Directory](batch-aad-auth-management.md)
417+
- [Microsoft identity platform code samples](/azure/active-directory/develop/sample-v2-code)

0 commit comments

Comments
 (0)