article

Wednesday, June 17, 2020

How to Implement Token Authentication using Django REST Framework


How to Implement Token Authentication using Django REST Framework

In this tutorial you are going to learn how to implement Token-based authentication using Django REST Framework (DRF).

Install Django REST Framework DRF:


pip install djangorestframework


settings.py
 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    'rest_framework', #pip install djangorestframework
    'rest_framework.authtoken',
    'myapp',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',  
    ],
}
migrate the database python manage.py migrate
views.py
 
#views.py
from django.shortcuts import render, redirect

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated

class HelloView(APIView):
    permission_classes = (IsAuthenticated,) #Generated token c4fe47947247e684dd0e065ea674e1645525d891 for user ednalan23

    def get(self, request):
        content = {'message': 'Hello, World!'}
        return Response(content)
urls.py
 
#urls.py
from django.contrib import admin  
from django.urls import path
from myapp import views  
from django.conf.urls import url
from django.urls import include, path
from rest_framework.authtoken.views import obtain_auth_token

urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/', views.HelloView.as_view(), name='hello'),
    path('api-token-auth/', obtain_auth_token, name='api_token_auth'),
]

I use HTTPie https://httpie.org/ Python command line tool:

http http://127.0.0.1:8000/hello/

http post http://127.0.0.1:8000/api-token-auth/ username=ednalan23 password=ednalan23

http GET http://127.0.0.1:8000/hello/ "Authorization: Token c4fe47947247e684dd0e065ea674e1645525d891"

Related Post