如何使用 Python 获取 oauth2 access_token

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36719540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:15:18  来源:igfitidea点击:

How can I get an oauth2 access_token using Python

pythongoogle-oauth2

提问by Johan Vergeer

For a project someone gave me this data that I have used in Postman for testing purposes:

对于一个项目,有人给了我这个我在 Postman 中用于测试目的的数据:

In Postman this works perfectly.

在邮递员中,这非常有效。

Auth URL: https://api.example.com/oauth/access_token
Access Token URL: https://api.example.com/access_token
client ID: abcde
client secret: 12345
Token name: access_token
Grant type: Client Credentials

身份验证 URL:https://api.example.com/oauth/access_token
访问令牌 URL:https
://api.example.com/access_token
客户端 ID:abcde客户端密钥:12345
令牌名称:access_token
授权类型:客户端凭据

All I need is to get back the access token.

我所需要的只是取回访问令牌。

Once, I got the access token I can continue.

有一次,我获得了可以继续的访问令牌。

I have already tried several Python packages and some custom code, but somehow this seemingly simple task starts to create a real headache.

我已经尝试了几个 Python 包和一些自定义代码,但不知何故,这个看似简单的任务开始让人头疼。

One exemple I tried:

我试过的一个例子:

import httplib
import base64
import urllib
import json

def getAuthToken():
    CLIENT_ID = "abcde"
    CLIENT_SECRET = "12345"
    TOKEN_URL = "https://api.example.com/oauth/access_token"

    conn = httplib.HTTPSConnection("api.example.com")

    url = "/oauth/access_token"

    params = {
        "grant_type": "client_credentials"
    }

    client = CLIENT_ID
    client_secret = CLIENT_SECRET

    authString = base64.encodestring('%s:%s' % (client, client_secret)).replace('\n', '')

    requestUrl = url + "?" + urllib.urlencode(params)

    headersMap = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": "Basic " + authString
    }

    conn.request("POST", requestUrl, headers=headersMap)

    response = conn.getresponse()

    if response.status == 200:
        data = response.read()
        result = json.loads(data)

        return result["access_token"]

Then I have got this one:

然后我得到了这个:

import requests
import requests.auth

CLIENT_ID = "abcde"
CLIENT_SECRET = "12345"
TOKEN_URL = "https://api.example.com/oauth/access_token"
REDIRECT_URI = "https://www.getpostman.com/oauth2/callback"

def get_token(code):
    client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
    post_data = {"grant_type": "client_credentials",
                 "code": code,
                 "redirect_uri": REDIRECT_URI}
    response = requests.post(TOKEN_URL,
                             auth=client_auth,
                             data=post_data)
    token_json = response.json()
    return token_json["access_token"]

If this would work, what should I put into the codeparameter

如果这行得通,我应该在code参数中输入什么

I really hope someone can help me out here.

我真的希望有人能在这里帮助我。

Thanks in advance.

提前致谢。

回答by Johan Vergeer

I was finally able to get it done

我终于能够完成它

This is the code I used:

这是我使用的代码:

class ExampleOAuth2Client:
    def __init__(self, client_id, client_secret):
        self.access_token = None

        self.service = OAuth2Service(
            name="foo",
            client_id=client_id,
            client_secret=client_secret,
            access_token_url="http://api.example.com/oauth/access_token",
            authorize_url="http://api.example.com/oauth/access_token",
            base_url="http://api.example.com/",
        )

        self.get_access_token()

    def get_access_token(self):
        data = {'code': 'bar',
                'grant_type': 'client_credentials',
                'redirect_uri': 'http://example.com/'}

        session = self.service.get_auth_session(data=data, decoder=json.loads)

        self.access_token = session.access_token

回答by CarloV

Simply (in case of Facebook Authentication):

简单(在 Facebook 身份验证的情况下):

import requests, json

access_token = requests.get("https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=your_client_id&client_secret=your_client_secret").json()["access_token"]

Or you can use rauth library.

或者您可以使用rauth 库

In the docsthere is an interesting example with facebook oAuth2 authentication:

文档中有一个有趣的示例,其中包含 facebook oAuth2 身份验证:

from rauth import OAuth2Service

facebook = OAuth2Service(
client_id='your_client_id',
client_secret='your_client_secret',
name='facebook',
authorize_url='https://graph.facebook.com/oauth/authorize',
access_token_url='https://graph.facebook.com/oauth/access_token',
base_url='https://graph.facebook.com/')

and after open a session:

打开会话后:

session = facebook.get_auth_session(data={'code': 'foo','redirect_uri': redirect_uri})

in the session json there is your access token

在会话 json 中有您的访问令牌