Как создать токен SAS для Azure хранилища озера данных (Gen-2) с использованием принципалов службы (clientId и clientSecret) в C#? - PullRequest
0 голосов
/ 19 марта 2020

У меня есть clientId и clientSecret Data Lake Store (Gen-2), и я ищу способ создать для него токен SAS программным способом c с использованием C#. Я просмотрел документацию, но не нашел способа создать токен 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 ошибка.

1 Ответ

0 голосов
/ 26 марта 2020

Если вы хотите использовать Azure токен доступа AD для доступа к Azure озеру данных gen2, обратитесь к следующему коду

  1. , создайте субъект службы и назначьте Azure RAB * 1041. * роль для sp.
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

enter image description here

Код
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, выполните следующие действия:

  1. получите ключ учетной записи через Azure Портал enter image description here

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

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...