Search code examples
c#azure-active-directoryservice-principalazure-data-lake-gen2azure-sas

How to create SAS token for Azure Data Lake Store (Gen-2) using service principals (clientId and clientSecret) in C#?


I have the clientId and clientSecret of Data Lake Store (Gen-2) and I am looking for a way to create SAS token for it in a programmatic way using C#. I have gone through the documentation but have not find a way to create a SAS token. Any guidance will be appreciated. Thanks.

As suggested by Md Farid Uddin Kiron, I used this code but unsuccessful:

//Token Request End Point
string tokenUrl = $"https://login.microsoftonline.com/<tenantId>.onmicrosoft.com/oauth2/token";
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

//I am Using client_credentials as It is mostly recommended
tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                ["grant_type"] = "client_credentials",
                ["client_id"] = "--------",
                ["client_secret"] = "-------",
                ["resource"] = "https://<datalake gen2 name>.dfs.core.windows.net/"
            });

            dynamic json;
AccessTokenClass results = new AccessTokenClass();
HttpClient client = new HttpClient();

var tokenResponse = client.SendAsync(tokenRequest).GetAwaiter();

json = tokenResponse.GetResult().Content.ReadAsStringAsync().GetAwaiter();
results = JsonConvert.DeserializeObject<AccessTokenClass>(json);

It is giving me status 400 error.


Solution

  • Following code can be used to create SAS token for datalake gen2 using service principles:

    Here Password is Client Secret and Username is ClientId.

    $securePassword = ConvertTo-SecureString -AsPlainText -Force -String $Password
    $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $UserName, $securePassword
    Connect-AzAccount -Credential $Credential -ServicePrincipal -Tenant $Tenant -Subscription $SubscriptionName
    
    Write-Host -ForegroundColor Green "Creating an account level SAS Token.."
    ## Get the storage account
    $storageAcc=Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccName
    ## Get the storage account context
    $ctx=$storageAcc.Context
    ## Creates an account-level SAS token.
    New-AzStorageAccountSASToken -Context $ctx -Service Blob,File,Table,Queue -ResourceType Service,Container,Object -Permission "racwdlup" -StartTime "2020-06-18" -ExpiryTime "2022-06-18"