如何通过服务账号(服务器端)在Google Admin中创建用户
如何通过服务账号凭证使用Google SDK创建Google Admin用户?
问题描述
我正尝试通过API在Google Admin中创建用户,已经完成以下操作:
- 创建服务账号及凭证
- 安装SDK库
- 阅读多篇关于服务账号/OAuth凭证、Google SDK认证、Admin API的文档
- 编写了初步代码(如下)
我的疑问:找不到说明如何通过SDK在Google Admin中创建用户的文档,仅找到REST API文档,但REST调用似乎需要OAuth2认证。是否可以仅使用服务账号凭证文件通过SDK完成用户创建及域/组织单元分配?
class Gcp: def __init__(self): SERVICE_ACCOUNT_FILE = "core/gcp/XXX.json" read_domain_scope = 'https://www.googleapis.com/auth/admin.directory.domain.readonly' admin_user_scope = 'https://www.googleapis.com/auth/admin.directory.user' read_ou_scope = 'https://www.googleapis.com/auth/admin.directory.orgunit.readonly' SCOPES = [read_domain_scope, admin_user_scope, read_ou_scope,] self.credential = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES) def list_user(self): res = googleapiclient.discovery.build('users', 'v1', credentials=self.credential) return 'OK'
解决方案
可以仅用服务账号凭证实现,需完成域范围授权配置和代码调整两步:
1. 配置服务账号的域范围授权
这是核心前提,必须由域管理员操作:
- 登录Google Admin控制台,进入「安全 > API控制 > 域范围授权」
- 添加新客户端ID(即服务账号凭证JSON里的
client_id字段值) - 授权代码中用到的所有Scopes(比如
admin.directory.user、admin.directory.orgunit) - 确保授权的Scopes包含读写权限,而非仅readonly
2. 调整代码实现用户创建与OU分配
服务账号本身无法直接操作Admin API,需模拟一个拥有Admin目录权限的域管理员账号,代码调整如下:
from google.oauth2 import service_account from googleapiclient.discovery import build class Gcp: def __init__(self): SERVICE_ACCOUNT_FILE = "core/gcp/XXX.json" # 替换为你的域管理员邮箱 DELEGATED_ADMIN_EMAIL = "admin@your-domain.com" # 按需配置所需权限的Scopes SCOPES = [ 'https://www.googleapis.com/auth/admin.directory.user', 'https://www.googleapis.com/auth/admin.directory.orgunit' ] # 加载服务账号凭证 self.credential = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES ) # 模拟域管理员账号(关键步骤) self.credential = self.credential.with_subject(DELEGATED_ADMIN_EMAIL) def create_user(self): # 正确构建Admin Directory API服务,而非'users'服务 service = build('admin', 'directory_v1', credentials=self.credential) # 构造用户数据(按Admin API要求格式) user_data = { "primaryEmail": "new-user@your-domain.com", "name": { "givenName": "John", "familyName": "Doe" }, "password": "TempPass123!", "changePasswordAtNextLogin": True } # 调用API创建用户 created_user = service.users().insert(body=user_data).execute() return created_user def assign_user_to_ou(self, user_email, ou_path): service = build('admin', 'directory_v1', credentials=self.credential) # 将用户移动到指定组织单元 service.users().update( userKey=user_email, body={"orgUnitPath": ou_path} ).execute() return "用户已成功分配到目标OU"
关键注意事项
- 之前的代码错误构建了
users服务,正确的是构建admin的directory_v1服务,对应Admin Directory API - 模拟的管理员账号必须拥有「用户管理」和「组织单元管理」的权限
- Scopes要根据实际需求调整,比如需要修改OU时,要使用
admin.directory.orgunit而非只读版本
内容的提问来源于stack exchange,提问作者Peeraphong Smanthap
相关产品推荐
相关产品推荐

