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

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

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

Simply (in case of Facebook Authentication):

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.

In the docs there is an interesting example with facebook oAuth2 authentication:

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

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

Before using it, you need to pip install requests

import requests


def get_access_token(url, client_id, client_secret):
    response = requests.post(
        url,
        data={grant_type: client_credentials},
        auth=(client_id, client_secret),
    )
    return response.json()[access_token]


get_access_token(https://api.example.com/access_token, abcde, 12345)

Leave a Reply

Your email address will not be published. Required fields are marked *