OAuth2: Authenticating users made secure
For anyone who has ever been curious about building an application that embeds other services inside would probably have come across this term: OAuth2 (Open Authentication 2). For instance, if you were creating an app and want to allow your users to log in through Google, Facebook, or even maybe Twitter, you will need to use each of these companies' respective OAuth2 systems to "authenticate" your users.
What is OAuth2
OAuth2 is a set of rules that allow users to authenticate to third-party apps (in this case your app is the app they are using and perhaps Google is the third-party app) without exposing their credentials or identity to you. This is how it works:
- You first have to receive a set of credentials to use a third-party app's OAuth2 system commonly called:
client id
andclient secret
- When creating this, you will need to fill out your app's information such as name, company name, website, address and etc. One of which would likely be a
callback URL
. This is the endpoint you must set in your app to allow the third-party app to redirect your user upon logging in
Typically, after authentication, you should be able to request a token, normally called access_token
that is used in every request to retrieve data for the user.
For example, a typical OAuth2 Session will go as follows:
Every app will implement it ever so slightly different from one another. Keep an eye on the documentation to see what they need!
Let's try one
Let us try to implement Google's OAuth2 authentication as an example. Go ahead and create an app on google's developer console:
On the left, go to "OAuth Consent Screen" and fill out the details there. As for testing, we can leave basically everything blank except for the email and app name.
In the scopes section, you can select as many scopes as you want (these are essentially permissions that you will request from your users). For now, we will use profile
one for testing:
Next, add your own email address as a testing user and finish the setup!
After completing the OAuth Screen setup, you can create an (OAuth2 Client) app on the project in the Credentials Tab:
For now, we will use a local host server at port 8088 for the callback URL
(they call it to redirect URI here).
This will create a set of keys:
Save this somewhere so that no one can see it!
Now that the app is set up, we can use it to authenticate a new Google user into our app. For this, we will be programming in python for simplicity using Flask.
We can create a simple web server with Flask at port 8088 running on a local host using the following script to be our "app".
First, we must redirect the user to Google for authentication. This can be done by generating an authentication url according to OAuth2 specifications. We can easily do this using a library in python:
This function would return an authentication URL that would look similar to this: https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=138037670983-5l4jg8utussuo13tvq1im8cn2v0c99rs.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8088&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&state=Xduz6uV1SwvzJ4jxsosn7MkrNlojAJ&prompt=consent&access_type=offline
Going to this URL will prompt the user to log in and accept permissions. After logging in, Google will automatically redirect the user to the flask server at http://localhost:8088
(our redirect URL) with a few query parameters, namely:
state=Xduz6uV1SwvzJ4jxsosn7MkrNlojAJ
(This will be the same "state" as the one generated fromgenerate_auth_url
. You can now match it to whoever it was that wanted to login)code=4%2F0AVHEtk4CYs-IInn7tAJog9H8P5rWKm5FJnOxWO4I1WDaikOyO-eu_G95dJJYhUVt8hKnig
scope=profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile
These are all the information you need to retrieve what is called an access token from Google for the user. To get the token, we will need to make a request to Google according to their docs:
The response object will look like this:
{
"access_token": "ya29.a0Ael9sCP9uHr_k6QpdKeezmBi--gT8AuEdD3F8zqi8EgzpCwD0HU0bCepxyde0fpud5ev4pnx5fchVoa1bo1CjUli7jlky_p5iHPcgmCMMXS51FueSPv_PTmvrP5udP89n3n3Kb1flfIHSfY18Fp2X40xYSnxaCgYKAVISARESFQF4udJhjKerSxzFbDOgqnd-MA5Oog0163",
"expires_in": 3599,
"refresh_token": "1//03zBC4HVy3AgjCgYIARAAGAMSNwF-L9IrPoBvLSJC_-nyVvcOD7hnRgZM5Xu79ATdgFkGCSv_DaPMYqfeJoy9iDzQ9m1TT1p18yY",
"scope": "https://www.googleapis.com/auth/userinfo.profile",
"token_type": "Bearer",
"id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjFhYWU4ZDdjOTIwNThiNWVlYTQ1Njg5NWJmODkwODQ1NzFlMzA2ZjMiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhenAiOiIxMzgwMzc2NzA5ODMtNWw0amc4dXR1c3N1bzEzdHZxMWltOGNuMnYwYzk5cnMuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiIxMzgwMzc2NzA5ODMtNWw0amc4dXR1c3N1bzEzdHZxMWltOGNuMnYwYzk5cnMuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMDQ2MzYxOTAwODU0MjY4MTE5NjYiLCJhdF9oYXNoIjoiZU0zVUxGeGhfcXc3ZE9FejNRQzdndyIsIm5hbWUiOiJFbGxpb3R0IFl1IiwicGljdHVyZSI6Imh0dHBzOi8vbGgzLmdvb2dsZXVzZXJjb250ZW50LmNvbS9hL0FHTm15eFpzaWFjZHZJWFdUSlBNbWgyQlQ5NTZiZDZKbXZGY3hZakVpYnR6bmc9czk2LWMiLCJnaXZlbl9uYW1lIjoiRWxsaW90dCIsImZhbWlseV9uYW1lIjoiWXUiLCJsb2NhbGUiOiJlbiIsImlhdCI6MTY4MDAwNTAyNiwiZXhwIjoxNjgwMDA4NjI2fQ.B-BzE-5V8IDJDSN30vNUKJ4AD2L0X0bHAJc1CxvogBqCyN3i2pZdLCcLqa98pgcUzpm6g6EaIys4I-GfVEkaj4nFoxzpeQMvyqmtbgPxMXoeQqb3b7hUwl2xMVFqKgL0J7dSw0m4FQdy14hfLUkuWCxua9dYkhWchIJkXpncmMfNEZINEPQDbrp1TUrU70hMH4650a4IK4Z1soK5JW7d1deD5XIHjSk55B_AD2IH6pd57cI_4qVB4j6FCxBFBviZPu3_RHsHfHsTVDp58oKIwZ28kCEwCX1O8HXLfka-yYhXx-Rg0xh7WJgv68tEcZo3jgjIfkR7XAeO_-Giz8BkBg"
}
That's it! It would be best if you now stored this payload somewhere (ideally in a database) and you can now access this user's "profile" data.
Other things to note
The example above shows how to specifically authenticate users through Google for your app. Each app would do something slightly different (for example, they might require you to post a JSON data object to request the access token rather than doing it in the query parameters. However, generally speaking, the flows are always the same as the OAuth2 protocol is an international standard, and if you follow the general steps above, you should be able to implement any OAuth2 systems into your app!