Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-Google OAuth从授权代码生成令牌_Python_Oauth 2.0_Google Cloud Functions_Google Auth Library - Fatal编程技术网

Python-Google OAuth从授权代码生成令牌

Python-Google OAuth从授权代码生成令牌,python,oauth-2.0,google-cloud-functions,google-auth-library,Python,Oauth 2.0,Google Cloud Functions,Google Auth Library,我有一个python google cloud函数,它接收OAuth授权代码作为参数。我想用这段代码交换一个令牌,该令牌可用于对服务对象进行身份验证 代码在外部生成,并作为字符串参数传递给此函数 我已经看了好几年的文档了。但它需要创建一个流对象来处理身份验证。在我的情况下,我只有代码作为结果 如何将授权码作为字符串交换为令牌?您需要的信息不仅仅是授权码。谷歌关于如何将授权码转换为访问令牌的文档如下: 具体而言,除了代码,您还需要: client_id:从API控制台[凭据页]|()获取的客户端

我有一个python google cloud函数,它接收OAuth授权代码作为参数。我想用这段代码交换一个令牌,该令牌可用于对服务对象进行身份验证

代码在外部生成,并作为字符串参数传递给此函数

我已经看了好几年的文档了。但它需要创建一个流对象来处理身份验证。在我的情况下,我只有代码作为结果


如何将授权码作为字符串交换为令牌?

您需要的信息不仅仅是授权码。谷歌关于如何将授权码转换为访问令牌的文档如下:

具体而言,除了
代码
,您还需要:

  • client_id
    :从API控制台[凭据页]|()获取的客户端id
  • client\u secret
    :从API控制台获取的客户端机密
  • 授权类型
    授权码
  • 重定向\u uri
    :初始授权请求中使用的重定向uri。如果这是针对可能是
    urn:ietf:wg:oauth:2.0:oob
    (用于带外)的CLI(或类似CLI)
其中大多数(
client\u id
client\u secret
grant\u type
)是静态的,因此您可以将它们用作云功能中的配置。如果您确定生成
代码的流,则
重定向uri
可能是静态的

有了这些信息,您应该能够在链接的示例中创建流对象并获取令牌


作为在云功能中存储所有这些配置的替代方案,您可以使用托管OAuth服务,如(我工作的地方),它处理授权过程,并允许您从任何地方(包括云功能)检索访问令牌只需一个API密钥。

除了授权代码,您还需要更多的信息。谷歌关于如何将授权码转换为访问令牌的文档如下:

具体而言,除了
代码
,您还需要:

  • client_id
    :从API控制台[凭据页]|()获取的客户端id
  • client\u secret
    :从API控制台获取的客户端机密
  • 授权类型
    授权码
  • 重定向\u uri
    :初始授权请求中使用的重定向uri。如果这是针对可能是
    urn:ietf:wg:oauth:2.0:oob
    (用于带外)的CLI(或类似CLI)
其中大多数(
client\u id
client\u secret
grant\u type
)是静态的,因此您可以将它们用作云功能中的配置。如果您确定生成
代码的流,则
重定向uri
可能是静态的

有了这些信息,您应该能够在链接的示例中创建流对象并获取令牌


作为在云函数中存储所有这些配置的替代方案,您可以使用托管OAuth服务,如(我工作的地方),该服务处理授权过程,并允许您仅使用API密钥从任何地方(包括云函数)检索访问令牌。

我最近也遇到了这个问题,正在尝试访问AdSense API。Google的文档非常稀疏,出于一些奇怪的原因使用了Flask,这并没有什么帮助,意味着您必须检索
authorization\u响应
,而不是实际的授权
code
,并且引用了不同的Python示例,这些示例似乎是早在不推荐使用的Python 1.4之后编写的

然而,根据他们的例子,以及一些实现了一些最新修复的博客文章(但在我尝试它们时仍然失败),我成功地拼凑了一些工作代码

我的文件
utils.py
中定义了
initialize\u服务
以初始化与AdSense API的连接:

"""
Auxiliary file for AdSense Management API code samples.
Handles various tasks to do with logging, authentication and initialization.
"""

import os

from apiclient.discovery import build

from oauth2client.client import OAuth2Credentials
from oauth2client.file import Storage
from googleapiclient.http import build_http

import google_auth_oauthlib.flow

MY_DOMAIN = '<your domain here>'

def initialize_service():
    """Builds instance of service from discovery data and does auth."""

    client_secrets = os.path.join(os.path.dirname(__file__), 'client_secrets.json')

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        client_secrets, scopes=['https://www.googleapis.com/auth/adsense.readonly'])
    flow.redirect_uri = f'https://{MY_DOMAIN}/oauth2callback'

    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # Credentials will get written back to a file.
    storage = Storage('adsense.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:

        auth_url, _ = flow.authorization_url(prompt='consent')
        print('Log into the Google Account you use to access your AdWords account ' \
         'and go to the following URL: \n%s\n' % auth_url)
        print('After approving the token enter the verification code (if specified).')
        code = input('Code:').strip()

        flow.fetch_token(code=code)
        print('Access token: %s' % flow.credentials.token)
        print('Refresh token: %s' % flow.credentials.refresh_token)

        # Flow creates a google.oauth2.credentials.Credentials instance but storage
        # can only save and load a oauth2client.client.Credentials
        # instance, so we have to convert it.
        old_creds = flow.credentials
        good_creds = OAuth2Credentials(
            access_token=old_creds.token,
            client_id=old_creds.client_id,
            client_secret=old_creds.client_secret,
            refresh_token=old_creds.refresh_token,
            token_expiry=old_creds.expiry,
            token_uri=old_creds.token_uri,
            user_agent='my-agent',
            id_token=old_creds.id_token,
            scopes=old_creds.scopes,
        )
        storage.put(good_creds)
        credentials = storage.get()

    http = credentials.authorize(http=build_http())

    service = build("adsense", "v1.4", http=http)

    return service

我最近在尝试访问AdSenseAPI时遇到了这个问题。Google的文档非常稀疏,出于一些奇怪的原因使用了Flask,这并没有什么帮助,意味着您必须检索
authorization\u响应
,而不是实际的授权
code
,并且引用了不同的Python示例,这些示例似乎是早在不推荐使用的Python 1.4之后编写的

然而,根据他们的例子,以及一些实现了一些最新修复的博客文章(但在我尝试它们时仍然失败),我成功地拼凑了一些工作代码

我的文件
utils.py
中定义了
initialize\u服务
以初始化与AdSense API的连接:

"""
Auxiliary file for AdSense Management API code samples.
Handles various tasks to do with logging, authentication and initialization.
"""

import os

from apiclient.discovery import build

from oauth2client.client import OAuth2Credentials
from oauth2client.file import Storage
from googleapiclient.http import build_http

import google_auth_oauthlib.flow

MY_DOMAIN = '<your domain here>'

def initialize_service():
    """Builds instance of service from discovery data and does auth."""

    client_secrets = os.path.join(os.path.dirname(__file__), 'client_secrets.json')

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        client_secrets, scopes=['https://www.googleapis.com/auth/adsense.readonly'])
    flow.redirect_uri = f'https://{MY_DOMAIN}/oauth2callback'

    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # Credentials will get written back to a file.
    storage = Storage('adsense.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:

        auth_url, _ = flow.authorization_url(prompt='consent')
        print('Log into the Google Account you use to access your AdWords account ' \
         'and go to the following URL: \n%s\n' % auth_url)
        print('After approving the token enter the verification code (if specified).')
        code = input('Code:').strip()

        flow.fetch_token(code=code)
        print('Access token: %s' % flow.credentials.token)
        print('Refresh token: %s' % flow.credentials.refresh_token)

        # Flow creates a google.oauth2.credentials.Credentials instance but storage
        # can only save and load a oauth2client.client.Credentials
        # instance, so we have to convert it.
        old_creds = flow.credentials
        good_creds = OAuth2Credentials(
            access_token=old_creds.token,
            client_id=old_creds.client_id,
            client_secret=old_creds.client_secret,
            refresh_token=old_creds.refresh_token,
            token_expiry=old_creds.expiry,
            token_uri=old_creds.token_uri,
            user_agent='my-agent',
            id_token=old_creds.id_token,
            scopes=old_creds.scopes,
        )
        storage.put(good_creds)
        credentials = storage.get()

    http = credentials.authorize(http=build_http())

    service = build("adsense", "v1.4", http=http)

    return service

谢谢崔,这很有道理。我可以使用客户端机密(我有)创建一个流对象,但是将外部生成的身份验证代码传递到fetch_token中。有没有一种方法不使用flask就能做到这一点?@Kiran关于这一点(除了Google库)的任何内容都不是python特有的。谷歌发布了一系列不同语言的库,所有这些库都遵循相同的流程。也基本上支持每种语言。@TreyGriffith,它不回答这个问题。Kiran正在Python中寻找一种方法来获取不使用Flask的令牌。基本上回答“是的,可能很多语言都使用API”是没有帮助的。谷歌的文档非常模糊,写得很糟糕,而且确实没有明确说明如何实际获取令牌。@Cerin它字面上回答了Kiran的问题(答案是“是”)。链接文档中的示例特别包括Python(Kiran没有指定他们想要的,只是“不使用flask”)。如果Kiran有一个更详细的问题,一个StackOverflow问题(而不是对另一个答案的评论)将是最好的地方。谢谢Trey,这很有意义。我可以使用客户机机密(我有)创建流对象,但要传递外部生成的auth-cod