Azure AD Go SDK 守护程序应用程序列表用户 returns "Access Token missing or malformed"

Azure AD Go SDK daemon application list users returns "Access Token missing or malformed"

我正在尝试通过图 API Go SDK 检索用户详细信息。我有一个 daemon application 已经设置了足够的权限,我已经通过 curl 验证,如下所示:

获取令牌

curl \
  -X POST \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --data 'client_id={client_id}&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret={client_secret}&grant_type=client_credentials' \

https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token

请求

curl -X GET \
 -H "Authorization: Bearer XYZ...." \
"https://graph.microsoft.com/v1.0/users"

成功获取用户列表


但是,当我通过 Go SDK 尝试这样做时,它失败了。

我已经根据 https://github.com/Azure/azure-sdk-for-go#more-authentication-details:

设置了身份验证所需的环境变量
- `AZURE_TENANT_ID`: Specifies the Tenant to which to authenticate.
- `AZURE_CLIENT_ID`: Specifies the app client ID to use.
- `AZURE_CLIENT_SECRET`: Specifies the app secret to use

代码

func main() {

    authorizer, err := auth.NewAuthorizerFromEnvironment()
    if err != nil {
        fmt.Println(err)
    }

    client := graphrbac.NewUsersClient(os.Getenv("AZURE_TENANT_ID"))
    client.Authorizer = authorizer

    if _, err := client.List(context.Background(), "", ""); err != nil {
        fmt.Println("list users", err)
    }
}

错误

list users graphrbac.UsersClient#List: Failure responding to request: StatusCode=401 -- Original Error: autorest/azure: Service returned an error. Status=401 Code="Unknown" Message="Unknown service error" Details=[{"odata.error":{"code":"Authentication_MissingOrMalformed","message":{"lang":"en","value":"Access Token missing or malformed."}}}]

我的文档 here 建议身份验证和令牌由 auth 包处理。

更新 1

我 运行 它通过设置 AZURE_GO_SDK_LOG_LEVEL=DEBUG 调试模式,发现 GET 请求 URL 与我在 curl 命令中使用的不同:

(2020-06-16T15:31:49.3790420+10:00) INFO: REQUEST: GET https://graph.windows.net/{tenant_id}/users?api-version=1.6
User-Agent: Go/go1.13.11 (amd64-darwin) go-autorest/v14.1.1 Azure-SDK-For-Go/v43.2.0 graphrbac/1.6
Authorization: **REDACTED**
(2020-06-16T15:31:50.5191120+10:00) INFO: RESPONSE: 401 https://graph.windows.net/{tenant_id}/users?api-version=1.6

如果我在我的 curl 命令中使用那个 URL 我得到:

{"odata.error":{"code":"Authentication_ExpiredToken","message":{"lang":"en","value":"Your access token has expired. Please renew it before submitting the request."}}}%

似乎 sdk 在后端使用了 azure ad graph api 而不是 microsoft graph api。

Azure AD 图 api 显示如下:https://graph.windows.net/{tenant_id}/users?api-version=1.6

Microsoft 图 api 显示如下:https://graph.microsoft.com/v1.0/users

所以你需要为你的azure ad中注册的应用添加azure ad graph权限,而不是添加microsoft graph权限。请按照以下步骤添加权限:

1. 在您的 Azure 广告中转到您的应用程序并单击 "API permissions" --> "Add a permission" --> "Azure Active Directory Graph"。

2.添加"Directory"权限。

3. 不要忘记授予管理员许可。

虽然 MSAL 尚未准备好(在 SDK 中),但似乎 ADAL 已被弃用。

Azure 控制台

microsoft-authentication-library-for-go:

这意味着 @hury-shen 答案仍然有效。