【发布时间】:2019-02-17 16:53:42
【问题描述】:
我正在尝试编写一个添加 G Suite 帐户的脚本,但我想在每次提交表单时不重定向到 Google 进行授权。有没有办法在脚本中授权?我尝试使用 API 密钥进行授权,但得到了 401 Error - Login Required
使用 oAuth 并被重定向到 Google 的工作原理:
from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/admin.directory.user'
def main():
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('creds.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('admin', 'directory_v1', http=creds.authorize(Http()))
print('Adding user...')
#create a user
service.users().insert(body={
"name": {
"givenName": "John",
"fullName": "John Smith",
"familyName": "Smith",
},
"password": "password",
"primaryEmail": "testuser@domain.com",
"changePasswordAtNextLogin": True,
}).execute()
if __name__ == '__main__':
main()
使用我的 API 密钥返回 401 Error
API_KEY = 'key'
def main():
service = build('admin', 'directory_v1', developerKey=API_KEY)
print('Adding user...')
#create a user
service.users().insert(body={
"name": {
"givenName": "John",
"fullName": "John Smith",
"familyName": "Smith",
},
"password": "password",
"primaryEmail": "testuser@domain.com",
"changePasswordAtNextLogin": True,
}).execute()
if __name__ == '__main__':
main()
【问题讨论】:
标签: oauth oauth-2.0 google-oauth google-admin-sdk google-directory-api