Search code examples
powershelljwtazure-virtual-machineazure-data-lakeazure-managed-identity

How to access Azure storage account Via Azure windows Virtual Machine Through Managed Identity


I am Trying to Access Azure Storage Account Via Azure Windows VM. I followed This Microsoft Document Link: https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/tutorial-windows-vm-access-datalake

I followed almost All steps That Mentioned In the above Document Link& JWT Access Token also Generated Successfully But My Commands For Uploading/Downloading Files are Throwing Errors.

Error: InvalidAuthenticationInfoAuthentication information is not given in the correct format

enter image description here

Please Correct me if i Used any wrong Commands For Download/Upload Files Via Virtual Machines Through Managed Identity

Commands Used For Generating JSW Token: $response = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://adlsrg.blob.core.windows.net/' -Method GET -Headers @{Metadata="true"} $content = $response.Content | ConvertFrom-Json $AccessToken = $content.access_token


Solution

  • To access storage accounts, you need to generate access token for https://storage.azure.com resource.

    I tried to reproduce the same in my environment and got below results:

    I created one VM and enabled system-assigned managed identity like below:

    enter image description here

    Assign Storage Blob Data Contributor role to VM under your storage account as below:

    Go to Azure Portal -> Storage accounts -> Your account -> Access Control (IAM) -> Add role assignment

    enter image description here

    Now connect to VM and run below PowerShell commands to get access token:

    $response = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://storage.azure.com' -Method GET -Headers @{Metadata="true"} 
    $content = $response.Content | ConvertFrom-Json 
    $AccessToken = $content.access_token
    

    Response:

    enter image description here

    To upload file to storage account, you can use below script:

    $file = "C:\Users\sri\Desktop\hello.txt" #File path
    $name = (Get-Item $file).Name
    
    $url="https://sristorageacc5.blob.core.windows.net/sri/$($name)"
    
    $RequestHeader = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
    $RequestHeader.Add("Authorization", "Bearer $AccessToken")
    $RequestHeader.Add("x-ms-version", "2019-02-02")
    $RequestHeader.Add("x-ms-blob-type", "BlockBlob")
    
    $result = Invoke-WebRequest -Uri $url -Method Put -Headers $RequestHeader -InFile $file
    

    Response:

    enter image description here

    When I checked the same in Portal, file uploaded to container successfully like below:

    enter image description here