使用服务主体调用 Azure Data Lake Storage Gen 2 的 REST API 的 OAuth 令牌

OAuth token for REST API call to Azure Data Lake Storage Gen 2 using service principal

我正在开发一个应用程序(核心微服务之一),它将调用 Azure ADLS Gen 2 来存储文件(在文件系统中)以供其他组件进一步处理。

我正在尝试通过使用初步创建的服务主体调用 Azure 身份验证端点来获取用于身份验证的 OAuth 令牌。

我用来创建服务主体的 PowerShell 代码:

Add-AzAccount -Subscription <SUBSCRIPTION ID>
$sp = New-AzADServicePrincipal -DisplayName <PRINCIPAL NAME>
Sleep 20
New-AzRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $sp.ApplicationId
$sp.ApplicationId
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($sp.Secret)
$UnsecureSecret = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
$UnsecureSecret  

我将 $sp.ApplicationId 的值用作 $UnsecureSecret 作为

然后为 Azure AD 应用程序配置 API 权限:

我已将 Azure AD 应用程序作为 STORAGE BLOB DATA CONTRIBUTOR 添加到存储帐户的 IAM blade。

接下来,我要为您获取一个 OAuth 令牌。
以下是我使用 Postman 进行的调用:

获取

https://login.microsoftonline.com/<TENANT ID>/oauth2/token

Headers

Content-Type: application/x-www-form-urlencoded

请求body

grant_type:client_credentials
client_id: <Azure AD application client ID>
client_secret: <Azure AD application client secret>
scope: https://storage.azure.com/.default

在这次调用之后,我能够得到成功的响应:

{
    "token_type": "Bearer",  
    "expires_in": "3600",  
    "ext_expires_in": "3600",  
    "expires_on": "1574686915",  
    "not_before": "1574683015",  
    "resource": "00000002-0000-0000-c000-000000000000",  
    "access_token": "eyJ0eX<..>" . 
}

然后我尝试使用以下请求创建文件系统:

放置

https://<STORAGE ACCOUNT NAME>.dfs.core.windows.net/<FILESYSTEM NAME>?resource=filesystem

Headers

Authorization: Bearer <JWT token>
x-ms-date: Mon, 25 Nov 2019 12:00:00 GMT
x-ms-version: 2019-02-02

并不断出现以下错误:

        {
            "error": {
                "code": "InvalidAuthenticationInfo",
                "message": "Server failed to authenticate the request.   
    Please refer to the information in the www-authenticate header.
\nRequestId:a6bf42d7-a01f-0006-1d88-a304da000000\nTime:2019-11-25T12:05:32.3049492Z"
            }
        }

我尝试了不同的范围,但没有帮助:

https://dfs.core.windows.net/.default
https://blob.core.windows.net/.default

我可以重现你的问题,Contributor RBAC 角色就足够了,不需要添加任何 API permission,问题是你请求令牌的方式导致的,当使用 v1.0端点,需要使用resource: https://storage.azure.com/.

GET https://login.microsoftonline.com/<TENANT ID>/oauth2/token

grant_type:client_credentials
client_id: <Azure AD application client ID>
client_secret: <Azure AD application client secret>
resource: https://storage.azure.com/

或者您可以将请求 URL 更改为 v2.0 端点,它也会起作用。

GET https://login.microsoftonline.com/<TENANT ID>/oauth2/v2.0/token

grant_type:client_credentials
client_id: <Azure AD application client ID>
client_secret: <Azure AD application client secret>
scope: https://storage.azure.com/.default

测试: