数值错误:客户端密钥必须用于Web或已安装的应用程序。

56

我正在运行Python Quickstart下的quickstart.py示例代码,但是出现了以下错误:

ValueError: 客户端密钥必须为Web或已安装的应用程序。

我使用具有项目所有者权限的credentials.json文件创建了它。

该错误发生在以下代码段中:

if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
        creds = flow.run_local_server()
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

我还注意到token.pickle文件没有被创建。以下是错误输出:

  File "updateSlidev01.py", line 51, in <module>
    main()
  File "updateSlidev01.py", line 31, in main
    flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
  File "/Library/Python/2.7/site-packages/google_auth_oauthlib/flow.py", line 174, in from_client_secrets_file
    return cls.from_client_config(client_config, scopes=scopes, **kwargs)
  File "/Library/Python/2.7/site-packages/google_auth_oauthlib/flow.py", line 147, in from_client_config
    'Client secrets must be for a web or installed app.')
ValueError: Client secrets must be for a web or installed app.

1
你是如何创建那个credentials.json文件的? - Linda Lawton - DaImTo
嗨!那正是问题所在。我已经回答了下面的问题。非常感谢! - PaoloAgVa
3个回答

62

如果有人来到这里是因为他们想通过服务账号连接到GCP日历API而不是使用此OAuth2客户端ID,请按照以下原始示例创建creds对象:

```python creds = service_account.Credentials.from_service_account_file( 'path/to/service.json', scopes=['https://www.googleapis.com/auth/calendar']) ```
from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
SERVICE_ACCOUNT_FILE = '/path/to/service.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
假设服务账户已经配置了正确的访问权限,这将无需提示用户确认即可访问日历。

4
愿神保佑你。 - ivanibash
如果我们想要连接到GCP日历API,为什么要使用“sqlservice.admin”的范围?我认为你的意思是“calendar.readonly”。如果我说得对,请纠正一下。 - macetw
可能 - 我认为这只是我当时使用的范围。但是,显然要根据手头的任务使用适当的范围。 - Adam Hughes

49

如果JSON是作为服务帐户创建的,您可以使用什么替代它? - Kajsa
9
在这里找到了解决方案 https://developers.google.com/identity/protocols/OAuth2ServiceAccount#authorizingrequests - Kajsa
@Kajsa 谢谢你,总是很感激有人回答他们的问题。 - ricekab
1
嗨 - 那么我可以问一下,这是否意味着普通服务账户不能用于这样的应用程序? - Adam Hughes

1
在我的情况下,credentials.json文件的键名错误。
文件看起来像这样:
{"SCc":{"client_id":"****","project_id":"****","wnc":"****","dVc":"****","vnc":"****","p2a":"****","kNc":["http://localhost"]}}

我把它改成了:
{"installed":{"client_id":"****","project_id":"****","auth_uri":"****","token_uri":"****","auth_provider_x509_cert_url":"****","client_secret":"****","redirect_uris":["http://localhost"]}}

工作得很好。

1
谢谢!我遇到了完全相同的问题。用这种方法修复键盘问题确实有效。但这个问题太奇怪了。 - Chris Mungall
我也遇到了同样的问题。 - Hampus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接