---
# System prepended metadata

title: JWT in django rest framewrok
tags: [django, python, backend]

---

# JWT in django rest framewrok
###### tags: `python` `django` `backend`

install 

generate token in /authentication/models.py
```
#
@property
    def token(self):
        token = jwt.encode(
            {'username': self.username, 'email': self.email, 'exp': datetime.utcnow() + timedelta(hours=48)},
            settings.SECRET_KEY,
            algorithm='HS256')
        # exp:expity time (how long the token can exist)
        return token
```

create url in /authentication/urls.py
```
urlpatterns = [
    #
    path('user', views.AuthUserAPIView.as_view(), name='user')

]
```

make authentcation view /authentication/views.py
```
class AuthUserAPIView(GenericAPIView):

    permission_classes = (permissions.IsAuthenticated, )
    
    def get(self, request):
        user = request.user
        serializer = RegisterSerializer(user)
        return response.Response({'user': serializer.data})
```

get token and decode 
create /authentication/jwt.py
```
from rest_framework.authentication import BaseAuthentication
from rest_framework import  exceptions
from authentication.models import User
import jwt
from django.conf import settings

class JWTAuthentication(BaseAuthentication):

    def authenticate(self, request):

        auth_header = request.headers.get('Authorization')
        auth_token = auth_header.split(' ')
        # auth_token: ["Bearar","$token"]

        # the request format not correct
        if len(auth_token) != 2:
            raise exceptions.AuthenticationFailed("Token is invalid")

        token = auth_token[1]

        try:
            payload = jwt.decode(
                token,settings.SECRET_KEY, algorithms="HS256"
            )
            username = payload['username']

            user = User.objects.get(username=username)

            return user, token

        except jwt.ExpiredSignatureError as ex:
            raise exceptions.AuthenticationFailed("Token is expired,please log in again.")

        except jwt.DecodeError as ex:
            raise exceptions.AuthenticationFailed("Token is invalid")

        except User.DoesNotExist as no_user:
            raise exceptions.AuthenticationFailed("User is not found")
```

change settings to make jwt default authentication (origenal default use OAuth2)
```
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'authentication.jwt.JWTAuthentication',    #'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ]
}
```

add /authentication/views.py
```
class LoginAPIView(GenericAPIView):
    authentication_classes = []
    #not using the jwt authentication
    #
```

