Implementation Of Social Authentication By Using Firebase With Django Rest Framework

Social Authentication, widely known as social sign-in, uses social networking platforms’ information to facilitate our applications’ logins. This process is designed in a way to simplify login and registration experiences. It provides a better and convenient alternative to create a mandatory account creation.

Social authentication is a smooth process to accessing sites and apps for users, one that doesn’t require various credentials and a lengthy registration process.

It is a very attractive feature for developers that can help streamline user verification and provide reliable user data for personalization.

Here I will discuss how to use the Firebase authentication system as your REST API’s identity provider using the Django Rest Framework.

Prerequisites:

  • To continue with this blog, we are considering that you are familiar with any front-end frameworks to configure Firebase authentication and send id token to the backend.
  • When configuring with frontend frameworks, make sure that one account per email address is enabled.

How Does Firebase Authentication Work With A Backend?

  • Firebase provides Firebase Admin SDK, which allows you to integrate it with your backend.
  • After getting the id token from the frontend, it verifies whether it’s valid or not.
  • Then it collects the user data from the id token and stores it in the database by creating a user by itself.
  • If the user data already exists in the database, then it successfully login the user.

Preface:

This blog will cover how to set up Firebase admin SDK into the Django rest framework and use it. The steps are as follows-

  • Generate secret key from Firebase.
  • Configure Firebase with Django.
  • Connect with Firebase app
  • Function to verify the id token and collect the data from Firebase.

Generate secret key from Firebase:

  • Go to your Firebase app console and click on the setting icon.

  • Click on the project setting.

  • Go to the service accounts tab.

  • Choose python as your backend language.

  • Click on the Generate new private keys.

  • A file in JSON format will be downloaded to your computer with all the required credentials.
  • Copy the credentials and put them into your environment variables.

Configure Firebase With Django:

  • Install Firebase-admin SDK to your virtual environment.
pip install Firebase-admin
  • Create the credential certificate.
import Firebase_admin

from Firebase_admin import credentials

from Firebase_admin import auth


cred = credentials.Certificate({
 "type": "service_account",
 "project_id": os.getenv('FIREBASE_PROJECT_ID'),
 "private_key_id": os.environ.get('FIREBASE_PRIVATE_KEY_ID'),
 "private_key": os.environ.get('FIREBASE_PRIVATE_KEY'),
 "client_email": os.environ.get('FIREBASE_CLIENT_EMAIL'),
 "client_id": os.environ.get('FIREBASE_CLIENT_ID'),
 "auth_uri": "https://accounts.google.com/o/oauth2/auth",
 "token_uri": "https://accounts.google.com/o/oauth2/token",
 "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
 "client_x509_cert_url": os.environ.get('FIREBASE_CLIENT_CERT_URL')
})
  • Connect to the Firebase app.
default_app = Firebase_admin.initialize_app(cred)
  • Create a function to verify the id token and get the user details from it.
def Firebase_validation(id_token):
   """
   This function receives id token sent by Firebase and
   validate the id token then check if the user exist on
   Firebase or not if exist it returns True else False
   """
   try:
       decoded_token = auth.verify_id_token(id_token)
       uid = decoded_token['uid']
       provider = decoded_token['firebase']['sign_in_provider']
       image = None
       name = None
       if "name" in decoded_token:
           name = decoded_token['name']
       if "picture" in decoded_token:
           image = decoded_token['picture']
       try:
           user = auth.get_user(uid)
           email = user.email
           if user:
               return {
                   "status": True,
                   "uid": uid,
                   "email": email,
                   "name": name,
                   "provider": provider,
                   "image": image
               }
           else:
               return False
       except UserNotFoundError:
           print("user not exist")
   except ExpiredIdTokenError:
       print("invalid token")
  • Creating a class-based view to signing up and log in in through id token.
class SocialSignupAPIView(GenericAPIView):
   """
   api for creating user from social logins
   """
   def post(self, request):
       auth_header = request.META.get('HTTP_AUTHORIZATION')

       if auth_header:
           id_token = auth_header.split(" ").pop()

           validate = Firebase_validation(id_token)

           if validate:
               user = CustomUser.objects.filter(uid = validate["uid"]).first()

               if user:
                   
                   data = {
                       "id": user.id,
                       "email": user.email,
                       "name": user.name,
                       "image": user.image,
                       "type": "existing_user",
                       "provider": validate['provider']
                   }

                   return Response({“data”: data,

                                    “message”: “Login Successful” })

               else:

                   user = CustomUser(email = validate['email'],
                                     name = validate['name'],

                                     uid = validate['uid'],

                                     image = validate['image']

                                     )

                   user.save()

                      data = {
                       "id": user.id,
                       "email": obj.email,
                       "name": obj.name,
                       "image": obj.image,
                       "type": "new_user",
                       "provider": validate['provider']
                   }

                   return Response({“data”: data,

                                    “message”: “User Created Successfully” })

else:
               return Response({“message”: “invalid token”})
       else:
               return Response({“message”: “token not provided”})
  • Creating an endpoint for the class-based view.
from Django.urls import path
from .views import SocialSignupAPIView

urlpatterns = [
    path('socialSignup', SocialSignupAPIView.as_view(), name= social-signup),
]

Conclusion

That’s it!! All set to apply your Firebase authentication with your Django rest framework. Now you can signup and log in your users through social platform accounts with the help of Firebase.

Nihar

Tech Expert

Nihar is a full stack developer with around 1 year of experience. He is an expert in building python Integrated web applications, creating REST API’s with well designed, testable and efficient code. He is always eager to learn new programming languages and technologies and looking for new ways to optimize the development process.

The founder's survey report on "What Matters For Startup" is released - Get your copy and learn the trends of successful companies :)

Download Free eBook Now!

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

"Mindbowser was very helpful with explaining the development process and started quickly on the project."

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

"The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs."

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

"They're very tech-savvy, yet humble."

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

"Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier"

author
Katie Taylor
Founder, Child Life On Call
coma

“As a founder of a budding start up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity."

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give