我已经能够使用google admin api登录谷歌应用程序并检索用户列表。我需要使用HTTPClient进行simiar。我之前创建了一个服务帐户,并且能够使用JWT方法获取访问令牌。 已使用管理控制台提前安全设置授予范围的授权权限。
我需要使用此访问令牌来创建/更新/读取用户。尽管有授权服务帐户的授权请求(这就是我如何获得令牌)我得到了禁止的错误。
{
"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;
}
答案 0 :(得分:0)
这三个属性是只读的,在创建用户时不应设置。
+"\"isAdmin\": false,"
+"\"isDelegatedAdmin\": false,"
+"\"isMailboxSetup\": true"
但这可能不是根本问题。该错误消息表示权限问题,而不是身份验证问题。访问令牌来自哪里?你是谁认证的?如果是服务帐户,则服务帐户需要been granted domain-wide access到Google Apps实例,be impersonating an admin in the Google Apps domain有权创建用户。如果访问令牌由常规Google帐户用户授权,则该用户必须是Google Apps域中的管理员或具有正确权限的经销商。如果primaryEmail属性中存在拼写错误,您将经常看到此错误。