DEV Community

Rana Wael
Rana Wael

Posted on

Django Authentication for APIs

1. Use rest_framework

Used for the response "instead of regular json response"

Installation

Install package pip install djangorestframework

Then add in settings

INSTALLED_APPS = [
    ...
    'rest_framework',
]
Enter fullscreen mode Exit fullscreen mode

2. Use simple jwt

To deal with authentication with access and refresh token

Installation

install pacakge pip install djangorestframework-simplejwt

Then add in settings:

REST_FRAMEWORK = {
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        ...
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
    ...
}
Enter fullscreen mode Exit fullscreen mode

Steps:

  • Use these endpoints to get the access and refresh tokens
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair')
Enter fullscreen mode Exit fullscreen mode

This api is post method to login with user then gives us the access and refresh tokens

Access token store info. about the user that is encoded

path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh')
Enter fullscreen mode Exit fullscreen mode

This api is post method to give it the refresh token then generates and gives us the new access token

  • Customize jwt
SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5),
 #Custom the lifetime of access token
    "REFRESH_TOKEN_LIFETIME": timedelta(days=1),
# Custom the lifetime of refresh token
  ....
}
Enter fullscreen mode Exit fullscreen mode
SIMPLE_JWT = {
  ....
"ROTATE_REFRESH_TOKENS": True,
...
}
Enter fullscreen mode Exit fullscreen mode
  • Use it when we need the user stay logged in even if the refresh token is expired (stay logged in if the user still opened the browser)
  • Generate new refresh token every time using refresh token api (to generate new access token)
  • Create rolling window and generate new refresh token
  • When making this boolean value (True), the endpoint of refresh token will give response new access and refresh tokens instead of new access token only
SIMPLE_JWT = {
  ....
 "BLACKLIST_AFTER_ROTATION": True
  ...
}
Enter fullscreen mode Exit fullscreen mode
  • Use it when using ”ROTATE_REFRESH_TOKENS” to block the old refresh tokens when generate new refresh token (to use the new refresh token only and block the old ones)
  • You need to add 'rest_framework_simplejwt.token_blacklist', to your INSTALLED_APPS in the settings file to use this setting
  • Customize Token Claims

Used to customize the decoded token returned to the user (more information about him)

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView


class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
  token = super().get_token(user)
  # custom claims
  token['username'] = user.username

return token

class MyTokenObtainPairView(TokenObtainPairView):
  serializer_class = MyTokenObtainPairSerializer
Enter fullscreen mode Exit fullscreen mode

3. Use CORS

  • Adds cross origin resource sharing(cors) headers to responses
  • It allows our resources to be accessed on other domains

Installation

Install pacakge python -m pip install django-cors-headers

Then add to settings:

INSTALLED_APPS = [
    ...,
    "corsheaders",
    ...,
]
...
MIDDLEWARE = [
    ...,
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...,
]
CORS_ALLOW_ALL_ORIGINS= True # To make any domain can access our project
## or
CORS_ALLOWED_ORIGINS = [allowed_urls, ...] # List of urls that we want to allow to our api 

Enter fullscreen mode Exit fullscreen mode

Top comments (0)