This is a sample Django app to authenticate with GitHub as a third-party OAuth2 provider.
This app is deployed on AWS running SSL here. This app contains a secret page whose secret content can only be viewed after authenticating with GitHub.
Before authentication, the secret page looks like this:
After authentication:
This app uses the following Python packages
- python-dotenv, to store sensitive information
- oauthlib, to integrate with third-party OAuth2 providers, such as GitHub
- requests, to send HTTP GET and POST requests
Other requirements include:
- a GitHub account to login
- a GitHub OAuth developer account to generic credentials such as
client id
andclient secret
. - an SSL connection to implement a client callback with a URL endpoint that receives communication back from GitHub's OAuth service.
- I wanted to understand and learn how to integrate with a third-party OAuth2 provider by writing some code myself, instead of plugging in a third-party Django app
- With oauthlib, I am able to write a client service that completes the OAuth2 flow between the client and provider, which requires these steps:
- request authorization from GitHub at an authorized GitHub URL with
client id
andstate
information and expecting acode
back - receive a
code
back from GitHub with the priorstate
information at the client's callback URL - fetch a token from GitHub's token URL passing
client secret
andcode
as arguments - retrieve the authorized user profile data from GitHub as
JSON
data - create a Django
User
account or reuse an existing authorizedUser
account - login to Django with
User
account - proceed with Django app logic based on
User
privileges
- request authorization from GitHub at an authorized GitHub URL with
To learn more about GitHub's OAuth2 flow, refer to this doc.
I wrote a supporting article for this project here. If you found any bugs, or would like me to improve this article, please don't hesitate to contact me. Thanks.