如何使用Python获取oauth2 access_token

时间:2016-04-19 13:13:47

标签: python google-oauth2

对于某个项目,有人向我提供了我在Postman中用于测试目的的数据:

在Postman中,这很有效。

验证网址:https://api.example.com/oauth/access_token
访问令牌网址:https://api.example.com/access_token
客户ID:abcde
客户秘密:12345
令牌名称:access_token
授予类型:客户端凭据

我只需要取回访问令牌。

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

我已经尝试了几个Python包和一些自定义代码,但不知怎的,这个看似简单的任务开始引起真正的麻烦。

我试过一个例子:

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"]

然后我有了这个:

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"]

如果这样做,我应该将什么放入code参数

我真的希望有人可以帮助我。

提前致谢。

2 个答案:

答案 0 :(得分:8)

我终于能够完成它

这是我使用的代码:

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

答案 1 :(得分:2)

简单(在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"]

或者您可以使用rauth library

docs中,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/')

并在开会后:

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

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