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.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?