How to set password authentication for Api Root / DefaultRouter in Django REST

This post is in continuation of “Developing first REST API using Django Rest Framework ( DRF )” , once you have followed this post and started the server, and opened url http://127.0.0.1:8000/ which opens the Api Root where you can see all the API’s we developed.

This Api Root access is open to all and anyone can see the contents of this page, as displayed below,

The first step to this is to add the login mechanism to this API root page, which can be done by modifying as,

$ vim helloproject/helloapp/urls.py 
urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

Now if you start the server again and visit API root, you will see “Login” text added at the top right corner as,

and when you click on this “Login” , you will be redirected to login URL “http://127.0.0.1:8000/api-auth/login/?next=/” … Notice, “api-auth” in this url as we added in your app’s url.py i.e. in this example helloproject/helloapp/urls.py

But, although you can see “Login” got added, still this page is not password protected and we can still see API details, hence for security reasons when we go for production development, we need to add authentication so only restricted users will have access to what those API’s are.

This authentication can be added by modifying settings.py and add following code as,

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

If you restart the server, you will see that access to Api Root is restricted as below with a message “Authentication credentials were not provided.”

Follow below steps to create a login user …

We’ll now create an initial user named “admin" with a password of “password123". We’ll authenticate as that user later in this example.

$ python manage.py createsuperuser --email social@lynxbee.com --username admin 
Password: 
Password (again): 
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

here, we used “password123” which is too weak, and it showed with a message as “This password is too common” , so you can choose to set any strong password to avoid this message.

Once you have username, password and server is running you can login to Api Root from Top Right corner by clicking on “Login” and you should be able to see the API’s now.

Leave a Comment