Django Authentication for APIs
Tags: django, restframework, restapi, jwt
Published: 2023-09-03 14:37:49

## 1. Use rest_framework

Used for the response "instead of regular json response"
### Installation
> Install package `pip install djangorestframework`

Then add in settings
```python
INSTALLED_APPS = [
    ...
    'rest_framework',
]
```
---

## 2. Use simple jwt
To deal with authentication with access and refresh token
### Installation
> install pacakge `pip install djangorestframework-simplejwt
`

Then add in settings:

```python
REST_FRAMEWORK = {
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        ...
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
    ...
}
```

### Steps:

- Use these endpoints to get the access and refresh tokens

```python
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair')
```

> 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 


```python
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh')
```

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

- Customize jwt

```python
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
  ....
}
```

```python
SIMPLE_JWT = {
  ....
"ROTATE_REFRESH_TOKENS": True,
...
}
```

> - 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
    
 
```python
SIMPLE_JWT = {
  ....
 "BLACKLIST_AFTER_ROTATION": True
  ...
}
```
> - 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)

```python
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
```

---

## 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:
```python
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 

```