API 403 Google Apps with service account
I am trying to make a request against the Google Admin API to list all users in my Google Apps organization. I have permissions to make this request in the sample web interface and get the results, but I will try to make the request with a service account.
import (
"fmt"
"io/ioutil"
"log"
"golang.org/x/net/context"
"golang.org/x/oauth2/google"
directory "google.golang.org/api/admin/directory_v1"
)
func main() {
serviceAccountJSON, err := ioutil.ReadFile(serviceAccountFile)
if err != nil {
log.Fatalf("Could not read service account credentials file, %s => {%s}", serviceAccountFile, err)
}
config, err := google.JWTConfigFromJSON(serviceAccountJSON,
directory.AdminDirectoryUserScope,
directory.AdminDirectoryUserReadonlyScope,
)
client, err := directory.New(config.Client(context.Background()))
if err != nil {
log.Fatalf("Could not create directory service client => {%s}", err)
}
users, err := client.Users.List().ViewType(publicDataView).Domain(domain).Do()
if err != nil {
log.Fatalf("Failed to query all users => {%s}", err)
}
for _, u := range users.Users {
fmt.Println(u.Name.FullName)
}
}
Every time I execute I get 403. The same query parameters are working in the section Try it!
here , so I'm not sure why it is failing.
result: Failed to query all users => {googleapi: Error 403: Not Authorized to access this resource/api, forbidden}
source to share
I know this question has been around for a year now, but I couldn't find anything about it anywhere, but I was just able to fix it after facing the same error as you.
basically you need to set a delegate for the user like:
func main() {
serviceAccountJSON, err := ioutil.ReadFile(serviceAccountFile)
if err != nil {
log.Fatalf("Could not read service account credentials file, %s => {%s}", serviceAccountFile, err)
}
config, err := google.JWTConfigFromJSON(serviceAccountJSON,
directory.AdminDirectoryUserScope,
directory.AdminDirectoryUserReadonlyScope,
)
// Add me
config.Subject = "someone@example.com"
client, err := directory.New(config.Client(context.Background()))
if err != nil {
log.Fatalf("Could not create directory service client => {%s}", err)
}
users, err := client.Users.List().ViewType(publicDataView).Domain(domain).Do()
if err != nil {
log.Fatalf("Failed to query all users => {%s}", err)
}
for _, u := range users.Users {
fmt.Println(u.Name.FullName)
}
}
See https://github.com/golang/oauth2/blob/master/google/example_test.go#L118
hope this helps someone else!
source to share