使用flow_from_clientsecrets()指定access_type = online

时间:2014-10-16 18:01:03

标签: google-api-python-client

我有一个我已批准为具有openidemail范围的授权API客户端的应用程序。我仍然会收到“您的域管理员已批准访问权限”的初始屏幕as documented here。解决方案是不通过access_type参数请求离线访问。

我的授权流程是使用flow_from_clientsecrets()构建的,我没有看到任何方法将访问类型作为参数传递给OAuth2WebServerFlow。有没有办法指定应用程序不需要使用客户端库刷新令牌?

1 个答案:

答案 0 :(得分:1)

我自己开始使用Google API Python客户端库,发现自己处于完全相同的状态。从我所阅读的内容flow_from_clientsecrets()仅返回Flow,其中应用了一组基本参数。事实证明,制作自己的OAuth2WebServerFlow对象并应用你需要的任何额外参数要简单得多。

这是我在googleapiclient和oauth2client库中对样本进行仔细研究后能够拼凑出来的解决方案:

# Returns a flow that will prompt for offline access, thus receiving
# a refresh_token in the auth object that gets returned
def prepare_flow(secrets_path, scope):
    # Grab settings from the client_secrets.json file provided by Google
    with open(secrets_path, 'r') as fp:
        obj = json.load(fp)

    # The secrets we need are in the 'web' node
    secrets = obj['web']

    # Return a Flow that requests a refresh_token
    return OAuth2WebServerFlow(
        client_id=secrets['client_id'],
        client_secret=secrets['client_secret'],
        scope=scope,
        redirect_uri=secrets['redirect_uris'][0],
        access_type='offline',
        approval_prompt='force')

您可以通过调用上述功能替换已调用的flow_from_clientsecrets

flow = prepare_flow(client_secrets, scope)

我刚刚使用此Flow运行了一个干净的身份验证,并验证了从Google返回的auth有效负载中是否存在refresh_token。