使用MSI从Azure函数将文件写入Azure Data Lake时出错

时间:2018-04-23 22:55:51

标签: azure-functions azure-data-lake azure-msi

我正在尝试创建一个写入Azure Data Lake Store的Azure功能。 我正在使用托管服务标识来管理身份验证。

我在Function应用程序上启用了MSI。我还启用了Function应用程序来访问所需的Data Lake Store。 我使用以下代码获取令牌并写入ADL。 我错过了什么?

var azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://datalake.azure.net");
var client = AdlsClient.CreateClient(_adlsAccountName, accessToken);
using (var stream = client.CreateFile(fileName, IfExists.Overwrite))
    {
        byte[] textByteArray = Encoding.UTF8.GetBytes("Winter is coming! \r\n");
        stream.Write(textByteArray, 0, textByteArray.Length);
    }

我的代码失败,出现以下错误。

with exception Microsoft.Azure.DataLake.Store.AdlsException: Error in creating file /Path/tempFile0.txt.

**Operation: CREATE failed with HttpStatus:Unauthorized Error: Uexpected error in JSON parsing.**

Last encountered exception thrown after 1 tries. [Uexpected error in JSON parsing]

[ServerRequestId:<Some ID>]

at Microsoft.Azure.DataLake.Store.AdlsClient.CreateFile(String filename, IfExists mode, String octalPermission, Boolean createParent)

2 个答案:

答案 0 :(得分:4)

添加&#34; Bearer&#34;访问令牌为我工作。就像这样(其他一切都保持不变),

var client = AdlsClient.CreateClient(_adlsAccountName, “Bearer “ + accessToken);

部分感谢Arturo Lucatero的Github doc提到了这一点。 https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/active-directory/managed-service-identity/tutorial-linux-vm-access-datalake.md

答案 1 :(得分:0)

我主要使用以下代码片段从Azure Functions验证和写入Data Lake:

var clientCredential = new ClientCredential(clientId, clientSecret);
var creds = ApplicationTokenProvider.LoginSilentAsync("domainId", clientCredential).Result;
_client = new DataLakeStoreFileSystemManagementClient(creds);

clientIdclientSecret的位置:

  • 来自AD的ObjectId
  • 附属于它的秘密

所以基本上你必须创建一个服务主体并从门户网站获取这些特定的属性。

然后我可以使用以下内容:

public async Task AppendToFile(string destinationPath, string content)
{
    using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
    {
        await _client.FileSystem.ConcurrentAppendAsync("datalakeaccount", destinationPath, stream, appendMode: AppendModeType.Autocreate);
    }
}

将数据写入ADLS。

您还可以参考this博文。