Django JWT

YH Lin
Feb 7, 2021

--

JWT代表JSON Web Token,它是客戶端/服務器應用程序使用的身份驗證策略。通過將用戶名+密碼交換為訪問令牌和刷新令牌來獲取JWT

開始之前,先安裝

pip install djangorestframework
pip install djangorestframework-simplejwt

接著在settings.py 中

INSTALLED_APPS = [
...
'rest_framework',
'rest_framework_simplejwt',
]

同樣在settings.py中

REST_FRAMEWORK = {
'DEFAULTRMISSION_CLASSES':('rest_framework.permissions.IsAuthenticated'),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}

SIMPLE_JWT = {
'REFRESH_TOKEN_LIFETIME': timedelta(days=15),
'ROTATE_REFRESH_TOKENS': True,
}

關於setting 中還有一些設定可參考這裡

例如,這是指我的token 可維持的有效期是一天

‘ACCESS_TOKEN_LIFETIME’: timedelta(days=1),

在urls.py 中加入

from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
...
urlpatterns = [
path('admin/', admin.site.urls),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),

]

這樣我們可以利用

https://127.0.0.1:8000/api/token/

在其他的API 想要或得保護時,可以在views.py中加上

class ReadingViewSet(viewsets.ModelViewSet):
authentication_classes = [SessionAuthentication, BasicAuthentication]
permission_classes = [IsAuthenticated]
# permission_classes = (AllowAny,)
queryset = Reading.objects.all()
serializer_class = ReadingSerializers
# http_method_names = ("post", "patch")
authentication_classes = (JWTAuthentication,)

這樣一來,在API 要使用前就會先需要你提供token的資訊

在postman中可在Authentication 中的type 選擇BearerToken

--

--

No responses yet