Google admin sdk 通过Java使用AdminSDK执行组操作
我有一个与Google Apps for Work域集成的应用程序,需要从oauth 1迁移到oauth 2 是一个服务器应用程序,它只需要:Google admin sdk 通过Java使用AdminSDK执行组操作,google-admin-sdk,google-oauth,google-oauth-java-client,Google Admin Sdk,Google Oauth,Google Oauth Java Client,我有一个与Google Apps for Work域集成的应用程序,需要从oauth 1迁移到oauth 2 是一个服务器应用程序,它只需要: 列出域中的所有组 列出指定组中的用户 将成员添加到指定的组 从指定的组中删除成员 鉴于上述情况,我认为这应该使用服务帐户来完成。我已经创建了这个,下载了P12令牌(P12和JSON令牌之间有什么区别?),并通过开发者控制台启用了AdminSDK API。API访问在域的控制面板中启用,并且我已启用与服务帐户关联的客户端ID的作用域 我尝试了一些随机操作,
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Insufficient Permission",
"reason" : "insufficientPermissions"
} ],
"message" : "Insufficient Permission"
}
无论如何,首先,我正在寻找有关正确实现上述操作所需代码的帮助,然后将查看是否仍然存在权限问题:
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import org.apache.commons.httpclient.HttpException;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.admin.directory.Directory;
import com.google.api.services.admin.directory.model.Group;
import com.google.api.services.admin.directory.model.Groups;
import com.google.api.services.admin.directory.model.Users;
public class GoogleAppsService {
HttpTransport httpTransport;
JsonFactory jsonFactory;
public GoogleAppsService() throws GeneralSecurityException, IOException {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
jsonFactory = JacksonFactory.getDefaultInstance();
}
public GoogleCredential getCredentials() throws HttpException, IOException, GeneralSecurityException {
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("179997031769-pf4t5hifo7dmtbqul1dbl9rulneijl7o@developer.gserviceaccount.com")
.setServiceAccountScopes(Collections.singleton("https://www.googleapis.com/auth/admin.directory.group.member"))
.setServiceAccountPrivateKeyFromP12File(
new File(this.getClass().getResource("/google_apps/google-apps-key.p12").getPath())).build();
return credential;
}
public void listGroups() throws Exception{
GoogleCredential credentials = getCredentials();
Directory directory = new Directory.Builder(
httpTransport, jsonFactory, credentials)
.setApplicationName("xyz")
.build();
//403 insufficient permissions thrown below is the above correct??
Groups result = directory.groups().list().execute();
System.out.println(result);
//iterate and print id/alias of each group
}
public void listUsers(String groupName) throws Exception {
GoogleCredential credentials = getCredentials();
//iterate and print email of each member for specified group
}
public void addUser(String groupname, String emailAddress)throws Exception {
GoogleCredential credentials = getCredentials();
}
public void removeUser(String groupName, String emailAddress)throws Exception {
GoogleCredential credentials = getCredentials();
}
public static void main(String[] args) throws Exception {
try {
GoogleAppsService service = new GoogleAppsService();
service.listGroups();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
好的,最后使用下面的完整解决方案进行此操作。关键是指定服务帐户用户(Google Apps帐户上管理员用户的电子邮件地址)并在获取组列表时调用setCustomer(“my_customer”)
public class GoogleAppsService {
private static final Logger LOGGER = Logger.getLogger(GoogleAppsService.class);
private static final String SERVICE_ACCOUNT_ID = "SERVICE_ACCOUNT_KEY";
private static final String SERVICE_ACCOUNT_USER = "EMAIL_ADDRESS_OF_ADMIN_ACCOUNT_ON_GOOGLE_APPS";
private static final String APPLICATION_NAME = "APP_NAME";
private HttpTransport httpTransport;
private JsonFactory jsonFactory;
private String googleAppsAllEmailListName;
private String googleAppsCommitteeEmailListName;
public GoogleAppsService() throws GeneralSecurityException, IOException {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
jsonFactory = JacksonFactory.getDefaultInstance();
}
protected Directory getDirectory() throws HttpException, IOException, GeneralSecurityException {
InputStream in = this.getClass().getResourceAsStream("/google_apps/google-apps-key.p12");
PrivateKey privateKey = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(), in, "notasecret",
"privatekey", "notasecret");
GoogleCredential credentials = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_ID)
.setServiceAccountScopes(Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_GROUP))
.setServiceAccountUser(SERVICE_ACCOUNT_USER).setServiceAccountPrivateKey(privateKey).build();
Directory directory = new Directory.Builder(httpTransport, jsonFactory, credentials).setApplicationName(APPLICATION_NAME)
.build();
return directory;
}
protected Groups listGroups(Directory directory) throws Exception {
//IF SPECIFYING THE SERVICE_ACCOUNT_USER WHEN CONNECTING YOU CAN USE setCustomer("my_customer")
return directory.groups().list().setCustomer("my_customer").execute();
}
protected Group getGroup(Directory directory, String emailAddress) throws IOException {
Group group = directory.groups().get(emailAddress).execute();
LOGGER.debug("Returning Group: " + group != null ? group.getEmail() + "(" + group.getDirectMembersCount() + " members)"
: "! no group loaded");
return group;
}
protected Members listGroupMembers(Directory directory, Group group) throws Exception {
return directory.members().list(group.getEmail()).execute();
}
protected boolean isMemberInGroup(Directory directory, Group group, String emailAddress) throws IOException {
boolean exists = false;
Members memberList = directory.members().list(group.getEmail()).execute();
List<Member> members = memberList.getMembers();
if (members != null) {
for (Member member : members) {
if (member.getEmail().equals(emailAddress)) {
exists = true;
break;
}
}
}
return exists;
}
protected void addMemberToGroup(Directory directory, Group group, String emailAddress) throws Exception {
Member member = new Member();
member.setEmail(emailAddress);
LOGGER.debug("Attempting Insert of Member to Group: " + group != null ? group.getEmail() : "! no group loaded");
directory.members().insert(group.getEmail(), member).execute();
}
protected void removeMemberFromGroup(Directory directory, Group group, String emailAddress) throws Exception {
LOGGER.debug("Attempting Deletetion of Member to Group: " + group != null ? group.getEmail() : "! no group loaded");
directory.members().delete(group.getEmail(), emailAddress).execute();
}
public void addMemberToMembersList(String emailAddress) throws MailingListException {
addMemberToList(googleAppsAllEmailListName, emailAddress);
}
public void addMemberToCommitteeList(String emailAddress) throws MailingListException {
addMemberToList(googleAppsCommitteeEmailListName, emailAddress);
}
protected void addMemberToList(String listAddress, String emailAddress) throws MailingListException {
try {
Directory directory = getDirectory();
Group group = getGroup(directory, listAddress);
if (!isMemberInGroup(directory, group, emailAddress)) {
addMemberToGroup(directory, group, emailAddress);
}
} catch (Exception e) {
LOGGER.error("Error adding member (" + emailAddress + ") to mailing list " + listAddress, e);
throw new MailingListException(e);
}
}
public void removeMemberFromMembersList(String emailAddress) throws MailingListException {
removeMemberFromList(googleAppsAllEmailListName, emailAddress);
}
public void removeMemberFromCommitteeList(String emailAddress) throws MailingListException {
removeMemberFromList(googleAppsCommitteeEmailListName, emailAddress);
}
protected void removeMemberFromList(String listAddress, String emailAddress) throws MailingListException {
try {
Directory directory = getDirectory();
Group group = getGroup(directory, listAddress);
if (isMemberInGroup(directory, group, emailAddress)) {
removeMemberFromGroup(directory, group, emailAddress);
}
} catch (Exception e) {
LOGGER.error("Error removing member (" + emailAddress + ") from mailing list " + listAddress, e);
throw new MailingListException(e);
}
}
public void setHttpTransport(HttpTransport httpTransport) {
this.httpTransport = httpTransport;
}
public void setJsonFactory(JsonFactory jsonFactory) {
this.jsonFactory = jsonFactory;
}
public void setGoogleAppsAllEmailListName(String googleAppsAllEmailListName) {
this.googleAppsAllEmailListName = googleAppsAllEmailListName;
}
public void setGoogleAppsCommitteeEmailListName(String googleAppsCommitteeEmailListName) {
this.googleAppsCommitteeEmailListName = googleAppsCommitteeEmailListName;
}
}
公共类服务{
私有静态最终记录器Logger=Logger.getLogger(GoogleAppsService.class);
私有静态最终字符串服务\u帐户\u ID=“服务\u帐户\u密钥”;
私有静态最终字符串服务\u ACCOUNT\u USER=“电子邮件\u地址\u谷歌应用程序上的\u ADMIN\u ACCOUNT\u”;
私有静态最终字符串应用程序\u NAME=“APP\u NAME”;
私人HttpTransport HttpTransport;
私人JsonFactory JsonFactory;
私有字符串googleAppsAllEmailListName;
私有字符串googleAppsCommitteeEmailListName;
public GoogleAppsService()引发GeneralSecurityException,IOException{
httpTransport=GoogleNetHttpTransport.newTrustedTransport();
jsonFactory=JacksonFactory.getDefaultInstance();
}
受保护目录getDirectory()引发HttpException、IOException、GeneralSecurityException{
InputStream in=this.getClass().getResourceAsStream(“/google_apps/google apps key.p12”);
PrivateKey PrivateKey=SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(),在“notasecret”中,
“私钥”、“非秘密”);
GoogleCredential credentials=new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
.setServiceAccountId(服务帐户ID)
.setServiceAccountScopes(Arrays.asList(DirectoryScopes.ADMIN\u DIRECTORY\u GROUP))
.setServiceAccountUser(服务\帐户\用户).setServiceAccountPrivateKey(privateKey).build();
Directory Directory=new Directory.Builder(httpTransport、jsonFactory、credentials)。setApplicationName(应用程序名称)
.build();
返回目录;
}
受保护组列表组(目录)引发异常{
//如果在连接时指定服务\帐户\用户,则可以使用setCustomer(“我的\用户”)
return directory.groups().list().setCustomer(“我的客户”).execute();
}
受保护组getGroup(目录目录,字符串emailAddress)引发IOException{
Group Group=directory.groups().get(emailAddress.execute();
LOGGER.debug(“返回组:“+Group!=null?Group.getEmail()+”(“+Group.getDirectMembersCount()+”成员)”
:“!未加载组”);
返回组;
}
受保护的成员listGroupMembers(目录目录,组组)引发异常{
返回directory.members().list(group.getEmail()).execute();
}
受保护的布尔isMemberInGroup(目录目录、组组、字符串电子邮件地址)引发IOException{
布尔存在=假;
Members memberList=目录.Members().list(group.getEmail()).execute();
List members=memberList.getMembers();
如果(成员!=null){
代表(成员:成员){
if(member.getEmail().equals(emailAddress)){
存在=真;
打破
}
}
}
回报存在;
}
受保护的void addMemberToGroup(目录目录、组组、字符串emailAddress)引发异常{
成员=新成员();
成员.setEmail(emailAddress);
LOGGER.debug(“正在尝试将成员插入组:“+Group!=null?Group.getEmail():”!未加载组”);
directory.members().insert(group.getEmail(),member.execute();
}
受保护的void removeMemberFromGroup(目录目录、组组、字符串emailAddress)引发异常{
LOGGER.debug(“正在尝试将成员删除到组:”+Group!=null?Group.getEmail():“!未加载组”);
directory.members().delete(group.getEmail(),emailAddress).execute();
}
public void addMemberToMembersList(字符串emailAddress)引发MailingListException{
addMemberToList(googleAppsAllEmailListName、emailAddress);
}
public void addMemberToCommitteeList(字符串emailAddress)引发MailingListException{
addMemberToList(googleAppsCommitteeEmailListName,电子邮件地址);
}
受保护的void addMemberToList(字符串listAddress,字符串emailAddress)引发MailingListException{
试一试{
Directory=getDirectory();
Group Group=getGroup(目录,列表地址);
如果(!isMemberInGroup(目录、组、电子邮件地址)){
addMemberToGroup(目录、组、电子邮件地址);
}
}捕获(例外e){
LOGGER.error(“将成员(“+emailAddress+”)添加到邮件列表“+listAddress,e”时出错);
抛出新的MailingListException(e);
}
}