How to login with service account?
Closed this issue · 2 comments
feeops commented
How to login with service account?
about service account
https://developers.google.com/google-ads/api/docs/oauth/service-accounts
xnkjj commented
Hi @feeops, authorization is not included in this repository. You can use the google-auth library to authenticate with a service account just like other google services. Here is an example of how to authenticate with a service account:
keyPath := "./xxx-xxxx-xxxxxxxxx.json"
jsonCredentials, err := os.ReadFile(keyPath)
if err != nil {
log.Fatalf("failed to read credentials: %v", err)
}
config, err := google.JWTConfigFromJSON(jsonCredentials, "https://www.googleapis.com/auth/adwords")
if err != nil {
log.Fatalf("failed to load credentials: %v", err)
}
config.Subject = "admin@your-domain.com" // the email address of the user you want to impersonate
tokenSource := config.TokenSource(context.Background())
token, err := tokenSource.Token()
if err != nil {
log.Fatalf("failed to get token: %v", err)
}
accessToken := token.AccessToken
cred := grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, ""))
conn, err := grpc.Dial("googleads.googleapis.com:443", cred)
if err != nil {
panic(err)
}
defer conn.Close()
ctx := context.Background()
headers := metadata.Pairs(
"developer-token", "xxxxxxxxxxxxxxxxxxxxx",
"authorization", "Bearer "+accessToken,
)
ctx = metadata.NewOutgoingContext(ctx, headers)
svc := services.NewCustomerServiceClient(conn)
resp, err := svc.ListAccessibleCustomers(ctx, &services.ListAccessibleCustomersRequest{})
if err != nil {
apiErr := status.Convert(err)
log.Fatalf("code: %s, message: %s, details: %v", apiErr.Code(), apiErr.Message(), apiErr.Details())
}
for _, customer := range resp.ResourceNames {
log.Println(customer)
}
Please notice that it is only tested in my local environment. You may need to adjust the code to fit your needs. Btw, it is not recommended to use service accounts for the Google Ads API. Instead, you should use OAuth2.0.
feeops commented
Thanks a lot