OAuth Authentication with Flask Connect to Google, Twitter, and Facebook (original) (raw)

In this article, we are going to build a flask application that will use the OAuth protocol to get user information. First, we need to understand the OAuth protocol and its procedure.

What is OAuth?

OAuth stands for Open Authorization and was implemented to achieve a connection between online services. The OAuth Community Site defines it as “**An open protocol to allow secure authorization in a simple and standard method from web, mobile and desktop applications.**”. A popular example of OAuth would be the Sign in with Google button present on various websites. Here the website service connects with the google service to provide you with an easy option to authorize your resource to the desired service. There are two versions of OAuth OAuth1.0 and OAuth2.0 now.

Terminologies in OAuth

Steps involved to setup OAuth

Step 1: Register your application as a client on the provider website. You will receive the client credentials which include the client ID and client secret.

Step 2: The client application sends an authorization request to the provider’s authorization URL.

Step 3: The user authenticates themselves on the provider’s site and allows resources to be used by the client service.

Step 4: The provider sents the authorization code to the client

Step 5: The client sends the authorization code to the provider’s authorization server.

Step 6: The provider sends the client tokens which can be used for accessing user resources.

Now that the concept of OAuth is clear we can start building our application. There are various libraries available to us that can be used to achieve OAuth. The library we will be using is AuthLib which supports OAuth 1.0 and OAuth 2.0.

Installing required dependencies

To install the required dependencies type the below command in the terminal.

pip install -U Flask Authlib requests

Note: It is recommended to create a virtual environment before installing these dependencies.

Retrieve the client credentials from the providers

The client credentials can be used directly in the program but in actual production, these credentials are to be stored in environment variables.

Create the UI

Create a folder called templates and inside create an index.html file. Paste the following code inside the index.html file. It is a simple code that creates buttons for every provider.

HTML `

Authlib Connect

Google
Twitter
Facebook

`

Creating the Flask app

Initialize the flask application

Let's create a simple flask application that will do nothing and will simply render the above-created HTML file onto the home page.

Python3 `

from flask import Flask, render_template

app = Flask(name)

app.secret_key = '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<
!\xd5\xa2\xa0\x9fR"\xa1\xa8'

''' Set SERVER_NAME to localhost as twitter callback url does not accept 127.0.0.1 Tip : set callback origin(site) for facebook and twitter as http://domain.com/ (or use your domain name) as this provider don't accept 127.0.0.1 / localhost '''

app.config['SERVER_NAME'] = 'localhost:5000'

@app.route('/') def index(): return render_template('index.html')

if name == "main": app.run(debug=True)

`

Run the server using the following command to make sure that the application is running successfully and the index.html page is displayed.

After creating the apps let's see how to add the Oauth for google, Twitter, and Facebook. But at first let's initialize the OAuth.

Initialize OAuth

Python3 `

from flask import Flask, render_template from authlib.integrations.flask_client import OAuth

app = Flask(name)

app.secret_key = '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!/ \xd5\xa2\xa0\x9fR"\xa1\xa8' ''' Set SERVER_NAME to localhost as twitter callback url does not accept 127.0.0.1 Tip : set callback origin(site) for facebook and twitter as http://domain.com/ (or use your domain name) as this provider don't accept 127.0.0.1 / localhost '''

app.config['SERVER_NAME'] = 'localhost:5000' oauth = OAuth(app)

@app.route('/') def index(): return render_template('index.html')

if name == "main": app.run(debug=True)

`

Here we have initialized the OAuth using the OAuth(app) class and we have changed our server name to localhost:5000. Now let's see how to create the OAuth for different Platforms.

Create OAuth for Google

Python3 `

The user details get print in the console.

so you can do whatever you want to do instead

of printing it

from flask import Flask, render_template, url_for, redirect from authlib.integrations.flask_client import OAuth import os

app = Flask(name) app.secret_key = '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!/ xd5\xa2\xa0\x9fR"\xa1\xa8'

''' Set SERVER_NAME to localhost as twitter callback url does not accept 127.0.0.1 Tip : set callback origin(site) for facebook and twitter as http://domain.com/ (or use your domain name) as this provider don't accept 127.0.0.1 / localhost '''

app.config['SERVER_NAME'] = 'localhost:5000' oauth = OAuth(app)

@app.route('/') def index(): return render_template('index.html')

@app.route('/google/') def google():

# Google Oauth Config
# Get client_id and client_secret from environment variables
# For developement purpose you can directly put it 
# here inside double quotes
GOOGLE_CLIENT_ID = os.environ.get('GOOGLE_CLIENT_ID')
GOOGLE_CLIENT_SECRET = os.environ.get('GOOGLE_CLIENT_SECRET')

CONF_URL = 'https://accounts.google.com/.well-known/openid-configuration'
oauth.register(
    name='google',
    client_id=GOOGLE_CLIENT_ID,
    client_secret=GOOGLE_CLIENT_SECRET,
    server_metadata_url=CONF_URL,
    client_kwargs={
        'scope': 'openid email profile'
    }
)

# Redirect to google_auth function
redirect_uri = url_for('google_auth', _external=True)
return oauth.google.authorize_redirect(redirect_uri)

@app.route('/google/auth/') def google_auth(): token = oauth.google.authorize_access_token() user = oauth.google.parse_id_token(token) print(" Google User ", user) return redirect('/')

if name == "main": app.run(debug=True)

`

Create OAuth for Twitter

Python3 `

The user details get print in the console.

so you can do whatever you want to do instead

of printing it

from flask import Flask, render_template, url_for, redirect from authlib.integrations.flask_client import OAuth import os

app = Flask(name) app.secret_key = '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O/ <!\xd5\xa2\xa0\x9fR"\xa1\xa8'

''' Set SERVER_NAME to localhost as twitter callback url does not accept 127.0.0.1 Tip : set callback origin(site) for facebook and twitter as http://domain.com/ (or use your domain name) as this provider don't accept 127.0.0.1 / localhost '''

app.config['SERVER_NAME'] = 'localhost:5000' oauth = OAuth(app)

@app.route('/') def index(): return render_template('index.html')

@app.route('/google/') def google():

# Google Oauth Config
# Get client_id and client_secret from environment variables
# For developement purpose you can directly put it here inside double quotes
GOOGLE_CLIENT_ID = os.environ.get('GOOGLE_CLIENT_ID')
GOOGLE_CLIENT_SECRET = os.environ.get('GOOGLE_CLIENT_SECRET')
CONF_URL = 'https://accounts.google.com/.well-known/openid-configuration'
oauth.register(
    name='google',
    client_id=GOOGLE_CLIENT_ID,
    client_secret=GOOGLE_CLIENT_SECRET,
    server_metadata_url=CONF_URL,
    client_kwargs={
        'scope': 'openid email profile'
    }
)

# Redirect to google_auth function
redirect_uri = url_for('google_auth', _external=True)
return oauth.google.authorize_redirect(redirect_uri)

@app.route('/google/auth/') def google_auth(): token = oauth.google.authorize_access_token() user = oauth.google.parse_id_token(token) print(" Google User ", user) return redirect('/')

@app.route('/twitter/') def twitter():

# Twitter Oauth Config
TWITTER_CLIENT_ID = os.environ.get('TWITTER_CLIENT_ID')
TWITTER_CLIENT_SECRET = os.environ.get('TWITTER_CLIENT_SECRET')
oauth.register(
    name='twitter',
    client_id=TWITTER_CLIENT_ID,
    client_secret=TWITTER_CLIENT_SECRET,
    request_token_url='https://api.twitter.com/oauth/request_token',
    request_token_params=None,
    access_token_url='https://api.twitter.com/oauth/access_token',
    access_token_params=None,
    authorize_url='https://api.twitter.com/oauth/authenticate',
    authorize_params=None,
    api_base_url='https://api.twitter.com/1.1/',
    client_kwargs=None,
)
redirect_uri = url_for('twitter_auth', _external=True)
return oauth.twitter.authorize_redirect(redirect_uri)

@app.route('/twitter/auth/') def twitter_auth(): token = oauth.twitter.authorize_access_token() resp = oauth.twitter.get('account/verify_credentials.json') profile = resp.json() print(" Twitter User", profile) return redirect('/')

if name == "main": app.run(debug=True)

`

Create OAuth for Facebook

Python3 `

The user details get print in the console.

so you can do whatever you want to do instead

of printing it

from flask import Flask, render_template, url_for, redirect from authlib.integrations.flask_client import OAuth import os

app = Flask(name) app.secret_key = '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O/ <!\xd5\xa2\xa0\x9fR"\xa1\xa8'

''' Set SERVER_NAME to localhost as twitter callback url does not accept 127.0.0.1 Tip : set callback origin(site) for facebook and twitter as http://domain.com/ (or use your domain name) as this provider don't accept 127.0.0.1 / localhost '''

app.config['SERVER_NAME'] = 'localhost:5000' oauth = OAuth(app)

@app.route('/') def index(): return render_template('index.html')

@app.route('/google/') def google():

# Google Oauth Config
# Get client_id and client_secret from environment variables
# For developement purpose you can directly put it here inside double quotes
GOOGLE_CLIENT_ID = os.environ.get('GOOGLE_CLIENT_ID')
GOOGLE_CLIENT_SECRET = os.environ.get('GOOGLE_CLIENT_SECRET')
CONF_URL = 'https://accounts.google.com/.well-known/openid-configuration'
oauth.register(
    name='google',
    client_id=GOOGLE_CLIENT_ID,
    client_secret=GOOGLE_CLIENT_SECRET,
    server_metadata_url=CONF_URL,
    client_kwargs={
        'scope': 'openid email profile'
    }
)

# Redirect to google_auth function
redirect_uri = url_for('google_auth', _external=True)
return oauth.google.authorize_redirect(redirect_uri)

@app.route('/google/auth/') def google_auth(): token = oauth.google.authorize_access_token() user = oauth.google.parse_id_token(token) print(" Google User ", user) return redirect('/')

@app.route('/twitter/') def twitter():

# Twitter Oauth Config
TWITTER_CLIENT_ID = os.environ.get('TWITTER_CLIENT_ID')
TWITTER_CLIENT_SECRET = os.environ.get('TWITTER_CLIENT_SECRET')
oauth.register(
    name='twitter',
    client_id=TWITTER_CLIENT_ID,
    client_secret=TWITTER_CLIENT_SECRET,
    request_token_url='https://api.twitter.com/oauth/request_token',
    request_token_params=None,
    access_token_url='https://api.twitter.com/oauth/access_token',
    access_token_params=None,
    authorize_url='https://api.twitter.com/oauth/authenticate',
    authorize_params=None,
    api_base_url='https://api.twitter.com/1.1/',
    client_kwargs=None,
)
redirect_uri = url_for('twitter_auth', _external=True)
return oauth.twitter.authorize_redirect(redirect_uri)

@app.route('/twitter/auth/') def twitter_auth(): token = oauth.twitter.authorize_access_token() resp = oauth.twitter.get('account/verify_credentials.json') profile = resp.json() print(" Twitter User", profile) return redirect('/')

@app.route('/facebook/') def facebook():

# Facebook Oauth Config
FACEBOOK_CLIENT_ID = os.environ.get('FACEBOOK_CLIENT_ID')
FACEBOOK_CLIENT_SECRET = os.environ.get('FACEBOOK_CLIENT_SECRET')
oauth.register(
    name='facebook',
    client_id=FACEBOOK_CLIENT_ID,
    client_secret=FACEBOOK_CLIENT_SECRET,
    access_token_url='https://graph.facebook.com/oauth/access_token',
    access_token_params=None,
    authorize_url='https://www.facebook.com/dialog/oauth',
    authorize_params=None,
    api_base_url='https://graph.facebook.com/',
    client_kwargs={'scope': 'email'},
)
redirect_uri = url_for('facebook_auth', _external=True)
return oauth.facebook.authorize_redirect(redirect_uri)

@app.route('/facebook/auth/') def facebook_auth(): token = oauth.facebook.authorize_access_token() resp = oauth.facebook.get( 'https://graph.facebook.com/me?fields=id,name,email,picture%7Burl%7D') profile = resp.json() print("Facebook User ", profile) return redirect('/')

if name == "main": app.run(debug=True)

`

Run the app

Start server with:

python app.py

Then visit:

http://localhost:5000/

Note: The OAuth configuration for every provider is different and depends on the version of OAuth. Every provider has its own documentation on implementing the protocol so make sure to check it out.