繁体   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#?

我有 Data Lake Store (Gen-2) 的 clientId 和 clientSecret,我正在寻找一种使用 C# 以编程方式为其创建 SAS 令牌的方法。 我已经阅读了文档,但还没有找到创建 SAS 令牌的方法。 任何指导将不胜感激。 谢谢。

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

它给了我状态 400 错误。

如果想使用Azure AD访问令牌访问Azure数据湖gen2,请参考以下代码

  1. 创建服务主体并为 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. 代码
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);

如果要创建sas token,请参考以下步骤

  1. 通过 Azure 门户获取帐户密钥在此处输入图片说明

  2. 代码

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

在此处输入图片说明

以下代码可用于使用服务原则为 datalake gen2 创建 SAS 令牌:

这里 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM