Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Django REST Framework JWT Authentication


หากเคยทำงานกับ Django REST Framework คงรู้จัก JWT Authentication ใช้สำหรับ Token Authentication เป็นวิธียอดนิยมใน Django JWT ย่อมาจาก JSON Web Token

ตัวอย่าง

ติดตั้งแพ็กเกจ:

pip install djangorestframework-simplejwt
pip install djangorestframework

ไม่ต้องการแอปเพิ่ม แค่ตั้งค่า Django REST Framework frontend และ authentication backend

ใน settings.py:

INSTALLED_APPS = [
    ...
    'rest_framework_simplejwt',
    'rest_framework'
    ...
]
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
}

เพิ่ม rest_framework และ JWT auth framework เป็นแอป ตั้งค่า authentication backend ใช้ JWT

ใน urls.py ของโปรเจกต์:

from django.urls import path
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'),
]

เพิ่ม 2 URLs: สร้าง token ด้วย username/password และ refresh token ด้วย token ที่สร้าง

เอาต์พุต

Django REST Framework JWT Authentication