Authentication is an essential aspect of any web application, and it is crucial to ensure user data security. Django, a popular web framework comes with built-in authentication capabilities and allows developers to implement custom authentication methods. In this blog post, we will explore how to implement Firebase email/password authentication in Django custom authentication.
Firebase is a mobile and web application development platform that offers a wide range of features, including authentication, databases, storage, and more. Firebase’s authentication service ensures both security and user-friendliness. It offers a range of authentication methods, among them the straightforward email/password combination. By integrating Firebase authentication into Django, developers, often referred to as Firebase developers, can leverage Firebase’s benefits while still using Django’s powerful web development features.
This integration allows Firebase developers to combine the authentication simplicity of Firebase with Django’s robust capabilities, creating a seamless user experience while maintaining the flexibility to implement complex functionalities. With Firebase’s real-time updates and Django’s versatile framework, Firebase developers can craft applications that are both dynamic and feature-rich, catering to the modern demands of users in today’s fast-paced digital landscape.
Firebase authentication is one of Firebase’s many services. It provides secure and easy-to-use authentication services, allowing developers to authenticate users using various methods, such as email/password, phone number, social media, and more. Firebase authentication provides a simple API that can be used in any client-side or server-side environment.
Firebase email/password authentication is a straightforward and secure method of authenticating users using their email addresses and passwords. It is an ideal method for apps that don’t require additional identity providers or social media integrations. Firebase email/password authentication provides features such as email verification, password reset, and account deletion, making it a robust authentication solution for web and mobile applications.
Related read: What is Firebase: The Good and the Bad of Firebase Backend Services
Before you embark on integrating Firebase Admin with Django, there are certain prerequisites that developers should ensure are in place.
➡️ Firebase Account: Developers need to create a Firebase account and create a project in the Firebase Console. This project will configure Firebase authentication and other Firebase services used in the Django application.
➡️ Python and Django: Developers should understand Python and the Django web framework. Django is a popular Python web framework, used to build web applications, including Firebase ones.
➡️ Firebase Admin SDK: Developers need to install and configure the Firebase Admin SDK for Python. The Firebase Admin SDK provides APIs for Firebase services that can be used on the server side of the application.
➡️ Firebase Authentication: Developers need to enable Firebase authentication for their project in the Firebase Console. This will allow them to authenticate users in their Django application using Firebase’s authentication service.
➡️ Django Rest Framework: If building a RESTful API, developers should understand Django Rest Framework. This framework allows developers to build APIs quickly and easily using Django.
By having these prerequisites in place, developers can integrate Firebase Admin and Django easily, ensuring a robust and secure authentication solution for their web applications.
Step 1: The first step is to install Django and DRF. You can do this using pip, Python’s package manager.
Open your command prompt or terminal and type the following command:
pip install django djangorestframework firebase-admin
This will install the latest version of Django and DRF on your system.
Step 2: Create a Django project: After installing Django and DRF, the next step is to create a Django project. Django projects are collections of settings and configurations for a specific website or web application.
To create your Django project, navigate to the directory where you want to create your project and type the following command:
django-admin startproject firebase_auth_django
This will create an entire directory called firebase_auth_django, which contains all the necessary files and directories for your Django project.
Step 3: Create a Django app: A Django app is a component of a Django project that performs specific functionality. You can create multiple apps within a Django project.
To create an app, navigate to the root directory of your project and type the following command:
python manage.py startapp users
This will create a newly created directory called users, which contains the necessary files for your Django app.
Step 4: Set up Firebase in the Django project: We need to create a Firebase project in the Firebase Console and obtain the Firebase Admin SDK credentials, which include the service account key. Once we have the service account key, we can set up Firebase in the Django project using the following code:
import os import json import requests import firebase_admin import firebase_admin.auth as auth from firebase_admin import credentials from rest_framework import authentication cred = credentials.Certificate("static/fir-auth-with-django-firebase-adminsdk-1zepn-3023fd129c.json") firebase_admin.initialize_app(cred) FIREBASE_WEB_API_KEY = os.environ.get("FIREBASE_WEB_API_KEY") rest_api_url = f"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword" def create_user(email, password): """ Function for creating firebase user. """ created_user = auth.create_user(email=email, password=password) return created_user.uid def change_firebase_user_password(new_password, uid): """ Function for changing password of firebase user. """ auth.update_user(uid, password=new_password) def change_firebase_user_email(uid, new_email): """ Function for change email of firebase user. """ auth.update_user(uid, email=new_email) def delete_firebase_user(uid): """ Function for deleting firebase user. """ auth.delete_user(uid) def login_firebase_user(email, password): """ Function for login firebase user. """ payload = json.dumps({ "email": email, "password": password, "returnSecureToken": True }) r = requests.post(rest_api_url, params={"key": FIREBASE_WEB_API_KEY}, data=payload) return r.json() def logout_firebase_user(uid): auth.revoke_refresh_tokens(uid) class FirebaseAuthentication(authentication.BaseAuthentication): def authenticate(self, request): from users.models import CustomUser token = request.headers.get('Authorization') if not token: return None try: token = token.split(" ")[1] decoded_token = auth.verify_id_token(token, check_revoked=True) uid = decoded_token["uid"] except: return None try: user = CustomUser.objects.get(uid=uid) return user, None except CustomUser.DoesNotExist: return None def get_user(self, user_id): from users.models import CustomUser try: return CustomUser.objects.get(id=user_id) except CustomUser.DoesNotExist: return None
Step 5: Configure Django settings according to the Firebase and Rest Framework:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'users' ]
REST_FRAMEWORK = { 'DEFAULT_AUTHENTIACTION_CLASSES': ( 'utilities.firebase.FirebaseAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'TEST_REQUEST_DEFAULT_FORMAT': 'json', 'EXCEPTION_HANDLER': 'utilities.utils.custom_exception_handler', }
Step 6: Implement login and logout: We need to create views in Django to handle user login and logout. These views will use Firebase authentication APIs to authenticate and manage user accounts. Here’s an example of a view for user registration:
from rest_framework import status from rest_framework.response import Response from rest_framework.generics import ( CreateAPIView, RetrieveAPIView, ) from rest_framework.permissions import IsAuthenticated from .models import CustomUser from utilities import messages from .serializers import LoginSerializer from utilities.utils import ResponseInfo from utilities.firebase import ( login_firebase_user, logout_firebase_user, FirebaseAuthentication, ) class LoginAPIView(CreateAPIView): """ Class for creating api for login user. """ permission_classes = () authentication_classes = () serializer_class = LoginSerializer def __init__(self, **kwargs): """ Constructor function for formatting the web response to return. """ self.response_format = ResponseInfo().response super(LoginAPIView, self).__init__(**kwargs) def post(self, request, *args, **kwargs): """ POST Method for login users. """ try: CustomUser.objects.get(email=request.data["email"]) serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): user = login_firebase_user(serializer.validated_data.pop("email"), serializer.validated_data.pop('password')) if not user.get("error"): self.response_format["data"] = user self.response_format["message"] = [messages.SUCCESS] else: self.response_format["status_code"] = status.HTTP_400_BAD_REQUEST self.response_format["error"] = "login_error" self.response_format["message"] = [messages.INVALID_CREDENTIALS] except CustomUser.DoesNotExist: self.response_format["data"] = None self.response_format["error"] = "user" self.response_format["status_code"] = status.HTTP_404_NOT_FOUND self.response_format["message"] = [messages.UNAUTHORIZED_ACCOUNT] return Response(self.response_format) class LogoutAPIView(CreateAPIView): """ Class for creating api for logout user. """ permission_classes = (IsAuthenticated,) authentication_classes = (FirebaseAuthentication,) serializer_class = LoginSerializer def __init__(self, **kwargs): """ Constructor function for formatting the web response to return. """ self.response_format = ResponseInfo().response super(LogoutAPIView, self).__init__(**kwargs) def post(self, request, *args, **kwargs): """ POST Method for logout users. """ uid = request.user.uid logout_firebase_user(uid) self.response_format["data"] = None self.response_format["error"] = None self.response_format["status_code"] = status.HTTP_200_OK self.response_format["message"] = [messages.LOGOUT_SUCCESS] return Response(self.response_format)
Step 7: Now we are at the final stage of this blog, we will create an API that allows only authenticated users to access it.
class GetDataAPIView(RetrieveAPIView): """ Class for creating api for getting authenticated data. """ permission_classes = (IsAuthenticated,) authentication_classes = (FirebaseAuthentication,) serializer_class = LoginSerializer def __init__(self, **kwargs): """ Constructor function for formatting the web response to return. """ self.response_format = ResponseInfo().response super(GetDataAPIView, self).__init__(**kwargs) def get(self, request, *args, **kwargs): """ GET Method for getting authenticated data. """ self.response_format["data"] = request.user.email return Response(self.response_format)
By following these steps, we can easily implement Firebase email/password authentication in Django and ensure a robust and secure authentication solution for our web applications.
Related read: Firebase Authentication & Email Verification In Android
In conclusion, implementing Firebase email/password authentication in Django through Django Rest Framework is a powerful way to secure your application and simplify user authentication. By using Firebase’s authentication service, we can benefit from advanced security features and user management tools.
In addition, we can retain full control over our Django application. This blog post covers the prerequisites for Firebase Admin and Django. It also covers the step-by-step process of implementing Firebase email/password authentication in Django through the Django Rest Framework. By following these steps, we can create a robust and secure authentication system for our Django application. This will allow us to focus on building our core features.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowMindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
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.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
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.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork