Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Sử dụng Djoser trong Django để xác thực token không cần view


Djoser là thư viện xác thực đơn giản cho Django REST Framework. Nó cung cấp các endpoint tạo token từ username, email, password chỉ qua POST request.

Cài đặt & Cấu hình

  1. Cài gói: pip install djoser djangorestframework

  2. Thêm vào INSTALLED_APPS trong settings.py:

    'myapp', 'rest_framework', 'rest_framework.authtoken', 'djoser'
  3. Cấu hình REST_FRAMEWORK và DJOSER:

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.TokenAuthentication',
        ),
        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.IsAuthenticated',
        ]
    }
    DJOSER = {"USER_ID_FIELD": "username"}
  4. Trong urls.py dự án:

    path('api/v1/', include('djoser.urls')),
    path('api/v1/token/login', include('djoser.urls.authtoken'))
  5. Chạy migration và server.

Kiểm tra

  • POST /api/v1/users/ – tạo user mới.

  • POST /api/v1/token/login – lấy token bằng username/password.