Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Azure Storage - On-Behalf-Of token and audit log
Flavio Campelo
Flavio Campelo

Posted on

     

Azure Storage - On-Behalf-Of token and audit log

📮 Contact 🇧🇷 🇺🇸 🇫🇷

Twitter
LinkedIn

Setting Up Front-End and Back-End Applications with Azure Blob Storage Access

This document provides a step-by-step guide to configure Front-End (FE) and Back-End (BE) applications to access Azure Blob Storage using the On-Behalf-Of (OBO) flow.

Prerequisites

  • Azure Subscription
  • Azure CLI
  • Visual Studio or any C# development environment

Steps

1. Register Back-End (BE) Application in Azure AD

  1. Register the BE Application:

    • Navigate to "Microsoft Entra ID" > "App registrations".
    • Click on "New registration".
    • Note theApplication (client) ID andDirectory (tenant) ID.
  2. Add Client Secret:

    • Go to "Certificates & secrets".
    • Add a new client secret and note it down.
  3. Expose API:

    • Go to "Expose an API".
    • Add a new scope, e.g.,api://{client_id_be}/user_impersonation.
  4. Add API Permissions:

    • Go to "API Permissions".
    • Add delegated and application permissions forhttps://storage.azure.com/.default.

2. Register Front-End (FE) Application in Azure AD

  1. Register the FE Application:

    • Navigate to "Microsoft Entra ID" > "App registrations".
    • Click on "New registration".
    • For this sample we are using mobile and desktop applications.
    • Note theApplication (client) ID andDirectory (tenant) ID.
  2. Configure Redirect URI:

    • Go to "Authentication" under the FE application.
    • Add a Redirect URI (e.g.,http://localhost).
  3. Add API Permissions:

    • Go to "API Permissions".
    • Click on "Add a permission".
    • Select "Microsoft Graph" and add delegated permissions such asuser.read.
    • Click on "Add a permission" again.
    • Select "APIs My organization uses" and find the BE application.
    • Add the delegated permissionapi://{client_id_be}/user_impersonation.
  4. Grant Admin Consent:

    • Ensure admin consent is granted for the added permissions.

3. Configure Azure Blob Storage

  1. Create a Storage Account:

    • Navigate to "Storage accounts" and create a new storage account.
    • Note the storage account name.
  2. Create a Container:

    • Inside the storage account, create a new container.
    • Note the container name.
  3. Assign Roles:

    • Go to the storage account.
    • Navigate to "Access Control (IAM)".
    • Click on "Add role assignment".
    • Assign roles likeStorage Blob Data Reader orStorage Blob Data Contributor to the appropriate users or service principals.
  4. Enable logging in Azure Storage Container:

    • Go to the storage account.
    • Navigate to "Diagnostics settings".
    • Click on the resource to view diagnostic settings.
    • Click on "Add diagnostic setting".
    • Select "StorageAccountLog" and "Blob".
    • Click on "Review + create" and then "Create".
    • This will enable logging for the Azure Storage Container.

img0

4. Implement the Code

This sample uses a console application for demo purposes only. After creating a new application, you have to install these nuget packages.

Azure.Storage.BlobsMicrosoft.Identity.Client
Enter fullscreen modeExit fullscreen mode

You can get the sample codehere.

usingAzure.Core;usingAzure.Storage.Blobs;usingMicrosoft.Identity.Client;usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;stringtenantId="tenant_id";// FEstringclientIdFE="fe_id";string[]scopesFE={"user.read","api://be_id/user_impersonation"};// BEstringclientIdBE="be_id";stringclientSecretBE="be_secret";string[]scopesBE=new[]{"https://storage.azure.com/.default"};// BLOBstringstorageAccountName="storage_name";stringcontainerName="container_name";stringblobName="blob_name";stringuserAccessToken=awaitGetUserAccessTokenAsync();Console.WriteLine($"User Access Token:{userAccessToken}");stringoboToken=awaitGetOboTokenAsync(userAccessToken);Console.WriteLine($"OBO Token:{oboToken}");awaitAccessBlobStorageAsync(oboToken);asyncTask<string>GetUserAccessTokenAsync(){varapp=PublicClientApplicationBuilder.Create(clientIdFE).WithAuthority(newUri($"https://login.microsoftonline.com/{tenantId}")).WithRedirectUri("http://localhost").Build();varaccounts=awaitapp.GetAccountsAsync();AuthenticationResultresult;try{result=awaitapp.AcquireTokenSilent(scopesFE,accounts.FirstOrDefault()).ExecuteAsync();}catch(MsalUiRequiredException){result=awaitapp.AcquireTokenInteractive(scopesFE).ExecuteAsync();}returnresult.AccessToken;}asyncTask<string>GetOboTokenAsync(stringuserAccessToken){varconfidentialClient=ConfidentialClientApplicationBuilder.Create(clientIdBE).WithClientSecret(clientSecretBE).WithAuthority(newUri($"https://login.microsoftonline.com/{tenantId}")).Build();varoboResult=awaitconfidentialClient.AcquireTokenOnBehalfOf(scopesBE,newUserAssertion(userAccessToken)).ExecuteAsync();returnoboResult.AccessToken;}asyncTaskAccessBlobStorageAsync(stringoboToken){TokenCredentialtokenCredential=newObTokenCredential(oboToken);BlobServiceClientblobServiceClient=newBlobServiceClient(newUri($"https://{storageAccountName}.blob.core.windows.net"),tokenCredential);BlobContainerClientcontainerClient=blobServiceClient.GetBlobContainerClient(containerName);BlobClientblobClient=containerClient.GetBlobClient(blobName);varresponse=awaitblobClient.DownloadAsync();using(varstream=response.Value.Content){Console.WriteLine("Blob content read successfully.");}}classObTokenCredential:TokenCredential{privatereadonlystring_token;publicObTokenCredential(stringtoken){_token=token;}publicoverrideAccessTokenGetToken(TokenRequestContextrequestContext,CancellationTokencancellationToken){returnnewAccessToken(_token,DateTimeOffset.MaxValue);}publicoverrideValueTask<AccessToken>GetTokenAsync(TokenRequestContextrequestContext,CancellationTokencancellationToken){returnnewValueTask<AccessToken>(newAccessToken(_token,DateTimeOffset.MaxValue));}}
Enter fullscreen modeExit fullscreen mode

5. Check OBO and logs

Run the code and check the logs to see all information about who accessed the file.

img1

Conclusion

By following these steps, you can configure FE and BE applications to access Azure Blob Storage using the On-Behalf-Of (OBO) flow. Ensure all permissions and configurations are correctly set in Azure AD and the Blob Storage account.


Typos or suggestions?

If you've found a typo, a sentence that could be improved or anything else that should be updated on this blog post, you can access it through a git repository and make a pull request. If you feel comfortable with github, instead of posting a comment, please go directly tohttps://github.com/campelo/documentation and open a new pull request with your changes.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Fullstack developer | Using dev.to to sharing my experiences, studies and curiosities with you.
  • Location
    Québec, Québec
  • Education
    Bachelor's degree in computer science
  • Work
    Software engineer, entrepreneur
  • Joined

More fromFlavio Campelo

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp