Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
969 views
in Technique[技术] by (71.8m points)

google oauth - How can I get an oauth2 access_token using Python

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

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

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.

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('
', '')

    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 code parameter

I really hope someone can help me out here.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...