A Django simple Application with Authentication
In this repo the_site is project, having two apps 'auth' and 'home'
Steps how JWT based authentication is implemented
-
pip install djangorestframework_simplejwt
-
Settings.py
INSTALLED_APPS = [
'rest_framework',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
- urls.py
In the_site.auth.urls
path('hello/', views.HelloView.as_view(), name='hello'),
In the_site.urls
path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),
- In auth.views.py
from django.views import View
class HelloView(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request):
content = {'message': 'Hello, World!'}
return Response(content)
- Do below steps:
- python manage.py migrate
- python manage.py createsuperuser
- pip3 install httpie
- Generate Tokens by visiting webpage: http://127.0.0.1:8000/api/token/
OR from cli do
curl -u username http://127.0.0.1:8000/api/token/
- http http://127.0.0.1:8000/auth/hello/ "Authorization: Bearer "
- After 5 minutes, access token will expire. We can get new access token using refresh token http post http://127.0.0.1:8000/api/token/refresh/ refresh=