Make OAuth2 token communication behind the scenes in python

325 views Asked by At

I am trying to build a most basic python app that uses OAuth2 to log into GitHub and fetch from there my username - using requests-oauthlib (this one: https://requests-oauthlib.readthedocs.io/en/latest/examples/github.html).

Here is the code from there:

from requests_oauthlib import OAuth2Session
from flask.json import jsonify

client_id = <my GitHub id>
client_secret = <my GitHub secret>
authorization_base_url = 'https://github.com/login/oauth/authorize'
token_url = 'https://github.com/login/oauth/access_token'
github = OAuth2Session(client_id)

authorization_url, state = github.authorization_url(authorization_base_url)
print('Please go here and authorize,', authorization_url)

redirect_response = input('Paste the full redirect URL here:')

github.fetch_token(token_url, client_secret=client_secret,
    authorization_response=redirect_response)

r = github.get('https://api.github.com/user')
print(r.content)

If I add the generated link to the browser, press enter, the url will change like a charm into a localhost:8080 (the callback url I provided in GitHub) with a code and state param. If I input it in my python code, I am able to fetch the GitHub data. My question is, is there any way to automatize this? Like, skipping the user interaction and simply ask for the credentials in GitHub then print my data in the console? Thanks

1

There are 1 answers

0
Adrian Muntean On BEST ANSWER

You are using the web application flow. For your purpose, it would be better to use the Device Flow.

Basically, the user needs to add a code that you will provide on a GitHub page input. And since you are using this as a simple app you could do that in a lower level and use the simple GET and POSTS requests together with requests