DEV Community

Cover image for Google/Apple token verification with Django
Damian D. Morejon
Damian D. Morejon

Posted on • Edited on

Google/Apple token verification with Django

Overview

Over the past few weeks, I have been working on a project where one of the main requirements is to enable token verification and authenticate or register & authenticate a user with Django.

What we’re going to do

We are going to use google-api-python-client to handle Google token verification and requests to handle token verification with Apple-ID servers.

Step 1: Setup

Install all packages we are going to use:

If you want to separate multiple python versions you can use a virtual environment by running python3 -m venv , this will create venv folder, activate it with source /bin/activate. Check the docs for more details

Next, we will set global variables in our settings.py with the keys and secrets, necessary to verify our tokens.

Make sure to check how to enable Apple Sign-In and Google Sign-in with Firebase if it’s not done yet.

Step 2: Create views

Here we will create two views, one for manage verification for Google tokens and another one for Apple tokens.

Let’s create first a simple serializer for our User model:

Then the Google view:

Here we are using the token that comes from a request to be verified using google-api-python-client, then we use the email, given name, and family name to register a user in our server if is not registered yet, save the profile image, and create a jwt token for user authentication in our server.

The Apple view:

In our Apple view, we are expecting either an access_token or a refresh_token. First, we need to generate a client secret using the algorithm ES256, then use the access token and the client secret to request an authentication token to Apple ID servers, and decode the response to get user information. You have to handle the user’s full name because this is only returned the first time a user signs in. Second, if we receive a refresh token, we use it to verify that the user is still signed in against the Apple ID servers. If we got no errors, proceed to authenticate or register/authenticate a user.

Configure some routes:

And that’s it!! We rock! Now you have all set to verify tokens from both Google and Apple and manage your users…

Top comments (0)