如何在 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 access token访问Azure data lake gen2,请参考以下代码
- 创建服务主体并为 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
- 代码
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,请参考以下步骤
通过 Azure 门户获取帐户密钥
代码
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 令牌:
这里的密码是 Client Secret 用户名是 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"
我有 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 access token访问Azure data lake gen2,请参考以下代码
- 创建服务主体并为 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
- 代码
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,请参考以下步骤
通过 Azure 门户获取帐户密钥
代码
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 令牌:
这里的密码是 Client Secret 用户名是 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"