在运行msgraph-sdk-go训练示例代码时,出现了获取访问令牌为空的错误。

huangapple go评论73阅读模式
英文:

Getting Access token is empty error while running msgraph-sdk-go training example code

问题

在尝试运行来自此处的msgraph-sdk-go训练代码时:https://github.com/microsoftgraph/msgraph-training-go,我在执行Graph API调用时遇到了InvalidAuthenticationTokenmsg: Access token is empty的错误。
我使用一个Microsoft开发者帐户配置了即时沙盒以进行试用。
我按照教程这里中的说明创建了一个应用程序注册,并为该应用程序授予了所需的权限。
代码能够获取AppToken,但是在获取用户的调用中,出现了上述错误。我是否遗漏了什么?

在运行msgraph-sdk-go训练示例代码时,出现了获取访问令牌为空的错误。
我尝试了msgraph-training示例中的以下代码

func (g *GraphHelper) InitializeGraphForAppAuth() error {
    clientId := os.Getenv("CLIENT_ID")
    tenantId := os.Getenv("TENANT_ID")
    clientSecret := os.Getenv("CLIENT_SECRET")
    credential, err := azidentity.NewClientSecretCredential(tenantId, clientId, clientSecret, nil)
    if err != nil {
        return err
    }

    g.clientSecretCredential = credential

    // 使用凭据创建身份验证提供程序
    authProvider, err := auth.NewAzureIdentityAuthenticationProviderWithScopes(g.clientSecretCredential, []string{
        "https://graph.microsoft.com/.default",
    })
    if err != nil {
        return err
    }

    // 使用身份验证提供程序创建请求适配器
    adapter, err := msgraphsdk.NewGraphRequestAdapter(authProvider)
    if err != nil {
        return err
    }

    // 使用请求适配器创建Graph客户端
    client := msgraphsdk.NewGraphServiceClient(adapter)
    g.appClient = client

    return nil
}

// 这部分是有效的,我使用所需的范围获取了AppToken,一旦解码。
func (g *GraphHelper) GetAppToken() (*string, error) {
    token, err := g.clientSecretCredential.GetToken(context.Background(), policy.TokenRequestOptions{
        Scopes: []string{
            "https://graph.microsoft.com/.default",
        },
    })
    if err != nil {
        return nil, err
    }
    fmt.Println("expires on : ", token.ExpiresOn)
    return &token.Token, nil
}

// GetUsers函数出错
func (g *GraphHelper) GetUsers() (models.UserCollectionResponseable, error) {
    var topValue int32 = 25
    query := users.UsersRequestBuilderGetQueryParameters{
        // 仅请求特定属性
        Select: []string{"displayName", "id", "mail"},
        // 最多获取25个结果
        Top: &topValue,
        // 按显示名称排序
        Orderby: []string{"displayName"},
    }

    resp, err := g.appClient.Users().
        Get(context.Background(),
            &users.UsersRequestBuilderGetRequestConfiguration{
                QueryParameters: &query,
            })
    if err != nil {
        fmt.Println("Users.Get got Error", err.Error(), resp)
        printOdataError(err)
    }
    resp, err = g.appClient.Users().
        Get(context.Background(),
            nil)
    if err != nil {
        fmt.Println("Users.Get got Error with nil", err.Error(), resp)
    }
    return resp, err
}

我已经按照教程在应用程序中添加了User.Read.All权限。
但是,我没有获取到用户列表,而是收到了以下错误:

Users.Get got Error error status code received from the API <nil>
error: error status code received from the API
code: InvalidAuthenticationTokenmsg: Access token is empty.Users.Get got Error with nil error status code received from the API <nil>
英文:

While trying to run the msgraph-sdk-go training code from here: https://github.com/microsoftgraph/msgraph-training-go, I'm getting InvalidAuthenticationTokenmsg: Access token is empty while executing the Graph API calls.
I configured a Microsoft developer account with instant sandbox for trial purpose.
I created an app registration as mentioned in the tutorial here and granted required permissions for the app.
The code is able to get the AppToken, but for calls to get Users, it fails with the above error. Am I missing something here?

在运行msgraph-sdk-go训练示例代码时,出现了获取访问令牌为空的错误。
I tried below code from the example for msgraph-training

func (g *GraphHelper) InitializeGraphForAppAuth() error {
clientId := os.Getenv(&quot;CLIENT_ID&quot;)
tenantId := os.Getenv(&quot;TENANT_ID&quot;)
clientSecret := os.Getenv(&quot;CLIENT_SECRET&quot;)
credential, err := azidentity.NewClientSecretCredential(tenantId, clientId, clientSecret, nil)
if err != nil {
return err
}
g.clientSecretCredential = credential
// Create an auth provider using the credential
authProvider, err := auth.NewAzureIdentityAuthenticationProviderWithScopes(g.clientSecretCredential, []string{
&quot;https://graph.microsoft.com/.default&quot;,
})
if err != nil {
return err
}
// Create a request adapter using the auth provider
adapter, err := msgraphsdk.NewGraphRequestAdapter(authProvider)
if err != nil {
return err
}
// Create a Graph client using request adapter
client := msgraphsdk.NewGraphServiceClient(adapter)
g.appClient = client
return nil
}
// This part works, and I get the AppToken with required scope, once decoded.
func (g *GraphHelper) GetAppToken() (*string, error) {
token, err := g.clientSecretCredential.GetToken(context.Background(), policy.TokenRequestOptions{
Scopes: []string{
&quot;https://graph.microsoft.com/.default&quot;,
},
})
if err != nil {
return nil, err
}
fmt.Println(&quot;expires on : &quot;, token.ExpiresOn)
return &amp;token.Token, nil
}
// The GetUsers function errors out
func (g *GraphHelper) GetUsers() (models.UserCollectionResponseable, error) {
var topValue int32 = 25
query := users.UsersRequestBuilderGetQueryParameters{
// Only request specific properties
Select: []string{&quot;displayName&quot;, &quot;id&quot;, &quot;mail&quot;},
// Get at most 25 results
Top: &amp;topValue,
// Sort by display name
Orderby: []string{&quot;displayName&quot;},
}
resp, err := g.appClient.Users().
Get(context.Background(),
&amp;users.UsersRequestBuilderGetRequestConfiguration{
QueryParameters: &amp;query,
})
if err != nil {
fmt.Println(&quot;Users.Get got Error&quot;, err.Error(), resp)
printOdataError(err)
}
resp, err = g.appClient.Users().
Get(context.Background(),
nil)
if err != nil {
fmt.Println(&quot;Users.Get got Error with nil&quot;, err.Error(), resp)
}
return resp, err
}

I have added the User.Read.All permission in the app as mentioned in the tutorial.
Instead of getting the list of users, I'm getting below error:

Users.Get got Error error status code received from the API &lt;nil&gt;
error: error status code received from the API
code: InvalidAuthenticationTokenmsg: Access token is empty.Users.Get got Error with nil error status code received from the API &lt;nil&gt;

答案1

得分: 0

由于您正在使用客户端凭据流,您可以在 Azure 门户中验证您的权限。如果您具有 User.Read.All 委派权限,在运行msgraph-sdk-go训练示例代码时,出现了获取访问令牌为空的错误。请删除委派权限,并添加相应的应用程序权限,然后不要忘记点击授予管理员同意。然后应该可以正常工作。

希望对您有所帮助。

谢谢。

英文:

As you are using client Credential Flow ,you can verify your permission in azure portal , if you have User.Read.All delegated permission ,在运行msgraph-sdk-go训练示例代码时,出现了获取访问令牌为空的错误。 Removes the delegated ones and add the corresponding application ones and don't forget to click on grant administrator consent after that. It should then work.

Hope this helps

Thanks.

答案2

得分: 0

好的,我会为你翻译以下内容:

好的,所以在尝试了一番后,对我有效的修复方法是示例代码和我尝试的实际应用程序之间的版本不匹配。
我使用的 beta msgraph 应用程序版本是 v0.49,而 msgraphsdk 教程使用的是 v0.48。我猜测 go mod 命令最初选择了最新的 v0.49,但在查看了 msgraph-training 仓库的 go.mod 文件后,我更新了 go.mod 文件以使用 v0.48,然后事情开始正常工作。
希望这对其他人有所帮助。

英文:

Okay, so the fix that did work for me after trial and error was a version mismatch in the example and the actual application I was trying out.
The version of the beta msgraph application I was using was v0.49, whereas the msgraphsdk tutorial was using v0.48. The go mod command picked up the latest v0.49 initially I guess, I updated the go.mod file to use v0.48 after looking at the go.mod file from msgraph-training repository and things started working.<br/>
Hope this helps someone else later on.

huangapple
  • 本文由 发表于 2023年1月5日 16:26:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75015618.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定