401 Unauthorized - 使用服务帐户的Google Directory API

时间:2018-03-13 22:24:22

标签: java google-admin-sdk google-directory-api

我正在尝试使用Google Directory API来从域中检索某些用户数据。同时省略Google身份验证,使用先前创建的Service account和G Suite域范围的委派,根据参考委派。但是在消费时,.execute()服务时出现错误:

-------------- RESPONSE --------------
HTTP/1.1 401 Unauthorized
Transfer-Encoding: chunked
Alt-Svc: hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303335,quic=":443"; ma=2592000; v="41,39,35"
Server: ESF
X-Content-Type-Options: nosniff
Pragma: no-cache
Date: Tue, 13 Mar 2018 22:12:25 GMT
X-Frame-Options: SAMEORIGIN
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Encoding: gzip
Expires: Mon, 01 Jan 1990 00:00:00 GMT
X-XSS-Protection: 1; mode=block
Content-Type: application/json; charset=utf-8

2018-03-13 16:12:25.023:WARN:oejs.ServletHandler:qtp157627094-30: /google
com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized

如果我try this API执行相同的参数,数据信息就可以正常工作。所以任何细节设置不好或任何想法?

public class GoogleDirectory {

    /** Email of the Service Account */
    private static final String SERVICE_ACCOUNT_EMAIL = "id@sanm-gcp-gae-qisdev.iam.gserviceaccount.com";

    /** Path to the Service Account's Private Key file */
    //public static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = dataP12.getPath();

    private static final List<String> SCOPES =
            Arrays.asList("https://www.googleapis.com/auth/admin.directory.user.readonly", "https://www.googleapis.com/auth/admin.directory.user");

    public GoogleDirectory() throws IOException {
    }

    /**
     * Build and returns a Directory service object authorized with the service accounts
     * that act on behalf of the given user.
     *
     * @param userEmail The email of the user. Needs permissions to access the Admin APIs.
     * @return Directory service object that is ready to make requests.
     */
    public static Directory getDirectoryService(String userEmail) throws GeneralSecurityException,
            IOException, URISyntaxException {
        File fileP12 = new ClassPathResource("file-638bb905b35d.p12").getFile();

        HttpTransport httpTransport = new NetHttpTransport();
        JacksonFactory jsonFactory = new JacksonFactory();
        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountScopes(SCOPES)
                .setServiceAccountUser(userEmail)
                .setServiceAccountPrivateKeyFromP12File(fileP12)
                .build();
        Directory service = new Directory.Builder(httpTransport, jsonFactory, null)
                .setHttpRequestInitializer(credential).build();
        return service;
    }


    public void execute() throws IOException, GeneralSecurityException, URISyntaxException {
        // Build a new authorized API client service.
        Directory service = getDirectoryService("emailRegisteredInOAuthConsentScreen");

        // Print the first 10 users in the domain.
        Users result = service.users().list()
                .setDomain("domainexample.com")
                .setOrderBy("email")
                .setQuery("email@example.com")
                .setViewType("domain_public")
                .execute();
        List<User> users = result.getUsers();
        if (users == null || users.size() == 0) {
            System.out.println("No users found.");
        } else {
            System.out.println("Users:");
            for (User user : users) {
                System.out.println(user.getName().getFullName());
            }
        }
    }

}

有关项目的更多细节:

  • Java:8
  • google-api-client:1.23.0

1 个答案:

答案 0 :(得分:0)

在Google帐户中设置其他应用使用帐户的权限 登录帐户。
转到:登录&amp;安全菜单
下一页:具有帐户访问权限的应用
启用:允许安全性较低的应用:关闭 - &gt; ON