使用项目所有者服务帐户凭据获取拒绝访问

使用项目所有者服务帐户凭据获取拒绝访问

我有一个查询活动日志的应用程序。我正在使用具有项目所有者角色的服务帐户凭据,还尝试了“日志管理员”、“私人日志查看器”、“日志查看器”和“组织管理员”

服务创建代码是:

private  Reports createActivityService() throws GeneralSecurityException, IOException {  
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();  
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();  
    GoogleCredentials credential = createCredential(ReportsScopes.all());  
    HttpRequestInitializer httpInitializer = new HttpCredentialsAdapter(credential);  
    return new Reports.Builder(httpTransport, jsonFactory, httpInitializer).setApplicationName("My App").build();  
}  

public GoogleCredentials createCredential(Set<String> scopes) throws IOException {  
    String clientCredentialFile = <path/to/credential>credential.json;  
    InputStream clientCredentionalFIS = new FileInputStream(clientCredentialFile);  
    GoogleCredentials credential = GoogleCredentials.fromStream(clientCredentionalFIS);  
    if (credential.createScopedRequired() == true) {  
        credential = credential.createScoped(scopes);  
    }  
    return credential;  
}

查询代码为:

private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

private List<Activity> getActivityList() throws IOException {
    Activities response = null;
    Report report = createActivityService();
    com.google.api.services.reports.Reports.Activities.List list = report.activities().list("all", "admin");
    list.setStartTime(simpleDateFormat.format(startTime));
    list.setStartTime(simpleDateFormat.format(endTime));
    List<Activity> activityList = new ArrayList<Activity>();
    do {
        response = list.execute();
        // do something
        list.setPageToken(response.getNextPageToken());
    } while (response.getNextPageToken() != null);
    return activityList;
}

答复是:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
{
  "code" : 401,
  "errors" : [ {
    "domain" : "global",
    "location" : "Authorization",
    "locationType" : "header",
    "message" : "Access denied. You are not authorized to read activity records.",
    "reason" : "authError"
  } ],
  "message" : "Access denied. You are not authorized to read activity records."
}

答案1

你可能想看这个

我认为您的问题是由凭证文件的传递方式引起的。

客户端库可以确定您的凭据隐式 当您将环境变量“GOOGLE_APPLICATION_CREDENTIALS”设置为您的.json 文件时。

以下是一个例子如何测试凭证

答案2

我知道我来晚了,但为了大家的利益,你可以尝试以下方法:

    package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "time"

    "golang.org/x/net/context"
    "golang.org/x/oauth2/google"

    //admin "google.golang.org/api/admin/directory/v1"
    admin "google.golang.org/api/admin/reports/v1"
    "google.golang.org/api/option"
)

// Path to the Service Account's Private Key file
var ServiceAccountFilePath = “/path/to/keyfile.json"

// Build and returns an Admin SDK Directory service object authorized with
// the service accounts that act on behalf of the given user.
// Args:
//    user_email: The email of the user. Needs permissions to access the Admin APIs.
// Returns:
//    Admin SDK directory service object.
func CreateReportsService(userEmail string) (*admin.Service, error) {
    ctx := context.Background()

    jsonCredentials, err := ioutil.ReadFile(ServiceAccountFilePath)
    if err != nil {
        return nil, err
    }

    config, err := google.JWTConfigFromJSON(jsonCredentials, "https://www.googleapis.com/auth/admin.reports.audit.readonly")
    if err != nil {
        return nil, fmt.Errorf("JWTConfigFromJSON: %v", err)
    }
    config.Subject = userEmail

    ts := config.TokenSource(ctx)

    srv, err := admin.NewService(ctx, option.WithTokenSource(ts))
    if err != nil {
        return nil, fmt.Errorf("NewService: %v", err)
    }
    return srv, nil
}

func main() {
    srv, err := CreateReportsService(“<admin_user_email_id>") // Here please enter the admin user email id; it is the admin user who has the permission
    if err != nil {
        log.Fatalf("Unable to retrieve reports Client %v", err)
        return
    }

    var userKey = "all"
    //var appName = "admin"
    var appName = "login"
    //var appName = "token"
    r, err := srv.Activities.List(userKey, appName).MaxResults(10).Do()
    if err != nil {
        log.Fatalf("Unable to retrieve logins to domain: userKey=%s, appName=%s, error: %v", userKey, appName, err)
        return
    }

    if len(r.Items) == 0 {
        fmt.Println("No logins found.")
    } else {
        fmt.Println("Logins:")
        for _, a := range r.Items {
            t, err := time.Parse(time.RFC3339Nano, a.Id.Time)
            if err != nil {
                fmt.Println("Unable to parse login time.")
                // Set time to zero.
                t = time.Time{}
            }
            fmt.Printf("%s: %s %s\n", t.Format(time.RFC822), a.Actor.Email,
                a.Events[0].Name)
        }
    }
}

相关内容