Home > Enterprise >  400 Bad request when generating the Google API access token using Go iamcredentials client API
400 Bad request when generating the Google API access token using Go iamcredentials client API

Time:09-29

I am trying to implement iamcredentials Go API client to generate an Access Token to access some Google APIs via REST API, I am using this code

    package main

    import (
        "context"
        "log"

        "google.golang.org/api/iamcredentials/v1"
    )

    func main() {
        iamcredentialsService, err := iamcredentials.NewService(context.Background())
        if err != nil {
            log.Println("error initialize iamcredential Service ", err)
            return
        }
        accessTokenCall := iamcredentialsService.Projects.ServiceAccounts.GenerateAccessToken(
            "projects/-/serviceAccounts/[email protected]:generateAccessToken",
            &iamcredentials.GenerateAccessTokenRequest{
                Scope: []string{
                    iamcredentials.CloudPlatformScope,
                },
            },
        )

        iamResp, err := accessTokenCall.Do()
        if err != nil {
            log.Println("error generate access token", err)
            return
        }

        log.Println(iamResp)
    }

But when I tried to run the above snippet, I got this message

go run main.go 

error generate access token googleapi: Error 400: Request contains an invalid argument., badRequest

Is there any way to check which one is causing the above response? I am not sure since there isn't any good example of implementation. Any help would be appreciated, Thanks.

Notes :

CodePudding user response:

@DanielFarrell is right, you need to remove the :generateAccessToken at the end. Here the documentation in the code. Don't hesitate to explore it, it's open source ;)

// GenerateAccessToken: Generates an OAuth 2.0 access token for a
// service account.
//
// - name: The resource name of the service account for which the
//   credentials are requested, in the following format:
//   `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-`
//   wildcard character is required; replacing it with a project ID is
//   invalid.
func (r *ProjectsServiceAccountsService) GenerateAccessToken(name string, generateaccesstokenrequest *GenerateAccessTokenRequest) *ProjectsServiceAccountsGenerateAccessTokenCall {
    c := &ProjectsServiceAccountsGenerateAccessTokenCall{s: r.s, urlParams_: make(gensupport.URLParams)}
    c.name = name
    c.generateaccesstokenrequest = generateaccesstokenrequest
    return c
}
  • Related