简体   繁体   English

如何在 C# 中使用服务主体(clientId 和 clientSecret)为 Azure Data Lake Store(Gen-2)创建 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#.我有 Data Lake Store (Gen-2) 的 clientId 和 clientSecret,我正在寻找一种使用 C# 以编程方式为其创建 SAS 令牌的方法。 I have gone through the documentation but have not find a way to create a SAS token.我已经阅读了文档,但还没有找到创建 SAS 令牌的方法。 Any guidance will be appreciated.任何指导将不胜感激。 Thanks.谢谢。

As suggested by Md Farid Uddin Kiron, I used this code but unsuccessful:正如 Md Farid Uddin Kiron 所建议的,我使用了这个代码但没有成功:

//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.它给了我状态 400 错误。

If you want to use Azure AD access token to access Azure data lake gen2, please refer to the following code如果想使用Azure AD访问令牌访问Azure数据湖gen2,请参考以下代码

  1. create a service principal and assign Azure RABC role for the sp.创建服务主体并为 sp 分配 Azure RABC 角色。
az login
az account set --subscription "<your subscription id>"
# it will assign Storage Blob Data Contributor to the sp at subscription level
az ad sp create-for-rbac -n "mysample" --role Storage Blob Data Contributor

在此处输入图片说明

  1. Code代码
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://storage.azure.com/"
            });

            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);

If you want to create sas token, please refer to the following steps如果要创建sas token,请参考以下步骤

  1. get the account key via Azure Portal通过 Azure 门户获取帐户密钥在此处输入图片说明

  2. code代码

var key = account key you copy";
            var accountName = "testadls05";
            StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, key);
            AccountSasBuilder sas = new AccountSasBuilder
            {
                Protocol = SasProtocol.None,
                Services = AccountSasServices.Blobs,
                ResourceTypes = AccountSasResourceTypes.All,
                StartsOn = DateTimeOffset.UtcNow.AddHours(-1),
                ExpiresOn = DateTimeOffset.UtcNow.AddHours(1),

            };
            sas.SetPermissions(AccountSasPermissions.All);

            var uri = $"https://{accountName}.dfs.core.windows.net/";

            UriBuilder sasUri = new UriBuilder(uri);
            sasUri.Query = sas.ToSasQueryParameters(credential).ToString();

            DataLakeServiceClient service = new DataLakeServiceClient(sasUri.Uri);
            var result =service.GetFileSystems().First();
            Console.WriteLine(result.Name);

在此处输入图片说明

Following code can be used to create SAS token for datalake gen2 using service principles:以下代码可用于使用服务原则为 datalake gen2 创建 SAS 令牌:

Here Password is Client Secret and Username is ClientId .这里 Password 是Client Secret , Username 是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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Azure KeyVault:如何创建clientId和clientSecret? - Azure KeyVault: how to create clientId and clientSecret? 在 ASP.net/C# 中使用刷新令牌、ClientId 和 ClientSecret 获取 Google Drive API 的 UserCredential - Get UserCredential of Google Drive API using Refresh token, ClientId and ClientSecret in ASP.net/C# Azure Data Lake存储通过C#脚本创建文件夹 - Azure Data Lake store create folder via C# script Azure Data Lake Gen2 - 如何使用 C# 将文件从文件夹移动到另一个文件夹 - Azure Data Lake Gen2 - How do I move files from folder to another folder using C# 如何使用C#复制Azure Data Lake存储中的文件 - how to Copy files inside Azure Data lake store using C# 通过 Azure 函数中的 C# 将文件从一个 DataLake Gen2 复制到另一个 Data Lake Gen 2 - Copy file from one DataLake Gen2 to another Data Lake Gen 2 via C# in Azure Functions 对于 Azure Key Vault,我应该将tenantId、clientId 和clientSecret 存储在哪里? - For Azure Key Vault, where should I store the tenantId, clientId and clientSecret? Read CSV From Azure Data lake storage Gen 1 in c# .net API - Read CSV From Azure Data lake storage Gen 1 in c# .net API 使用服务主体从 Azure Function 连接到 Data Lake Gen 2 会引发 AuthorizationPermissionMismatch 错误 - Connecting to Data Lake Gen 2 from Azure Function using Service Principal is throwing AuthorizationPermissionMismatch error 如何创建文件或将文件上传到Azure Data Lake Storage Gen2 - How to create a file or upload a file to Azure Data Lake Storage Gen2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM