在请求中使用访问令牌以获取禁止的用户403



我已经能够使用Google Admin API登录到Google Apps并检索用户列表。我需要使用httpclient做simiar。我早些时候创建了一个服务帐户,并能够使用JWT方法获得访问令牌。使用Admin Console Advance Secuurity设置授予了范围的授权权。

我需要使用此访问令牌来创建/更新/读取用户。尽管有授权请求给予服务帐户(这就是我能够获取令牌的方式),但我还是遇到了禁止错误。

   {
    "domain": "global",
    "reason": "forbidden",
    "message": "Not Authorized to access this resource/api"
   }
  ],
  "code": 403,
  "message": "Not Authorized to access this resource/api"
 }
}

我已经检查了此访问令牌针对

curl https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=#access_token

看到它是有效的令牌。

样本Java片段

     public void createUser()  {

        String params="{"
              +""name": {"
              +""familyName": "Smith","
              +""givenName": "John","
              +""fullName": "John Smith""
              +"},"
              +""password": "<some password>","
              +""primaryEmail": "john.smith@xyz.net","
              +""isAdmin": false,"
              +""isDelegatedAdmin": false,"
              +""isMailboxSetup": true"
              +"}";

        PostMethod method =null;
        try {
            JSONObject json=new JSONObject(params);
            String url="https://www.googleapis.com/admin/directory/v1/users";
            //+ "?access_token="+ accessToken;
            method = new PostMethod(url);
            method.addRequestHeader("Content-Type", "application/json");
            method.addRequestHeader("Authorization","Bearer " + accessToken);
            method.setRequestEntity(new StringRequestEntity(json.toString(),
                    "application/json", null));
            method.execute();
            System.out.println(method.getResponseBodyAsString());
            if (method.getStatusCode() == HttpStatus.SC_CREATED) {
                try {
                    JSONObject response = new JSONObject(method.getResponseBodyAsString());
                    if (response.getBoolean("success")) {
                        System.out..println( "User Account created Successfully. <br>");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection;
        }
        return null;
    }

这3个属性是只读的,不应在创建用户时设置。

+""isAdmin": false,"
+""isDelegatedAdmin": false,"
+""isMailboxSetup": true"

这可能不是根问题。错误消息表示权限问题,而不是身份验证问题。访问令牌来自哪里?您正在认证谁?如果是一个服务帐户,则需要授予对Google Apps实例的范围范围访问域,并在Google Apps域中模仿具有创建用户的权利的管理员。如果访问令牌是由常规Google帐户用户授权的,则该用户必须是Google Apps域中的管理员或具有正确权限的经销商。如果主邮件属性中有错字,您会经常看到此错误。

最新更新