欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Django?REST?Framework?(DRF)?項(xiàng)目中實(shí)現(xiàn)JWT的示例代碼

 更新時(shí)間:2025年02月07日 10:22:43   作者:春天的菠菜  
本文主要介紹了Django?REST?Framework?(DRF)?項(xiàng)目中實(shí)現(xiàn)JWT的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

前言:JSON Web Tokens (JWT) 是一種開放標(biāo)準(zhǔn) (RFC 7519),用于在各方之間安全地傳輸信息。在現(xiàn)代 Web 應(yīng)用中,JWT 認(rèn)證是一種常見的身份驗(yàn)證機(jī)制,它提供了無(wú)狀態(tài)、輕量級(jí)的身份驗(yàn)證方式。本文將詳細(xì)介紹如何在 Django REST Framework (DRF) 項(xiàng)目中實(shí)現(xiàn) JWT 認(rèn)證,并配置 token 黑名單以增強(qiáng)安全性。

1、安裝依賴

需要安裝 djangorestframework 和 djangorestframework-simplejwt 包。你可以使用 pip 來(lái)安裝它們

pip install djangorestframework
pip install djangorestframework-simplejwt

2、配置項(xiàng)目

編輯 settings.py 文件,添加 rest_framework 和 rest_framework_simplejwt 到 INSTALLED_APPS: 

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

3、配置JWT

3.1 配置默認(rèn)認(rèn)證類和權(quán)限類

在 settings.py 中配置默認(rèn)的認(rèn)證類和權(quán)限類: 

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

3.2 配置JWT設(shè)置

在 settings.py 中配置 JWT 的一些選項(xiàng),例如 token 的過期時(shí)間、簽名算法等:

from datetime import timedelta

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': True,
    'BLACKLIST_AFTER_ROTATION': True,
    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUTH_HEADER_TYPES': ('Bearer',),
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',
}

4、創(chuàng)建視圖和序列化器

4.1 創(chuàng)建自定義 Token 視圖

創(chuàng)建一個(gè)視圖來(lái)處理登錄請(qǐng)求,返回 JWT token。

# views.py
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenBlacklistView
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from django.contrib.auth.models import User
from .serializers import RegisterSerializer

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        # Add custom claims
        token['username'] = user.username
        return token

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

class RegisterView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = RegisterSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            return Response({
                "user": UserSerializer(user, context=self.get_serializer_context()).data,
                "message": "User Created Successfully.  Now perform Login to get your token",
            })
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

# serializers.py
from rest_framework import serializers
from django.contrib.auth.models import User

class RegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'password', 'email')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user = User.objects.create_user(
            username=validated_data['username'],
            email=validated_data['email'],
            password=validated_data['password']
        )
        return user

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email')

4.2 配置URL

在 urls.py 中配置 URL 路由,以便訪問登錄、注冊(cè)、刷新和注銷視圖:

# urls.py
from django.urls import path
from .views import MyTokenObtainPairView, RegisterView

urlpatterns = [
    path('login/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('login/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('logout/', TokenBlacklistView.as_view(), name='token_blacklist'),
    path('register/', RegisterView.as_view(), name='auth_register'),
]

5、測(cè)試API

使用 Postman 或其他 HTTP 客戶端來(lái)測(cè)試你的 API。以下是一些示例請(qǐng)求:

5.1 注冊(cè)新用戶

URL: /register/
Method: POST
Body:

{
  "username": "testuser",
  "email": "testuser@example.com",
  "password": "testpassword"
}

5.2 登錄并獲取JWT token

URL: /login/
Method: POST
Body:

{
  "username": "testuser",
  "password": "testpassword"
}

5.3 刷新JWT token

URL: /login/refresh/
Method: POST
Body:

{
  "refresh": "your_refresh_token"
}

5.4 注銷(將token加入黑名單)

URL: /logout/
Method: POST
Body:

{
  "refresh": "your_refresh_token"
}

6、總結(jié)

通過以上步驟,我們成功地在 Django REST Framework 項(xiàng)目中實(shí)現(xiàn)了 JWT 認(rèn)證,并配置了 token 黑名單以增強(qiáng)安全性。JWT 認(rèn)證提供了一種無(wú)狀態(tài)、輕量級(jí)的身份驗(yàn)證方式,而 token 黑名單則確保了已注銷的 token 不會(huì)被再次使用,從而提高了應(yīng)用的安全性。

到此這篇關(guān)于Django REST Framework (DRF) 項(xiàng)目中實(shí)現(xiàn)JWT的示例代碼的文章就介紹到這了,更多相關(guān)Django REST Framework JWT內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python face_recognition實(shí)現(xiàn)AI識(shí)別圖片中的人物

    Python face_recognition實(shí)現(xiàn)AI識(shí)別圖片中的人物

    最近碰到了照片識(shí)別的場(chǎng)景,正好使用了face_recognition項(xiàng)目,給大家分享分享。face_recognition項(xiàng)目能做的很多,人臉檢測(cè)功能也是有的,是一個(gè)比較成熟的項(xiàng)目。感興趣的可以了解一下
    2022-01-01
  • 基于Python編寫一個(gè)有趣的年會(huì)抽獎(jiǎng)系統(tǒng)

    基于Python編寫一個(gè)有趣的年會(huì)抽獎(jiǎng)系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了如何使用Python編寫一個(gè)簡(jiǎn)易的抽獎(jiǎng)系統(tǒng),順便幫助大家鞏固一下對(duì)Python語(yǔ)法和框架的理解,感興趣的小伙伴可以了解下
    2023-12-12
  • Python實(shí)現(xiàn)葵花8號(hào)衛(wèi)星數(shù)據(jù)自動(dòng)下載實(shí)例

    Python實(shí)現(xiàn)葵花8號(hào)衛(wèi)星數(shù)據(jù)自動(dòng)下載實(shí)例

    這篇文章主要為大家介紹了Python實(shí)現(xiàn)葵花8號(hào)衛(wèi)星數(shù)據(jù)自動(dòng)下載實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-10-10
  • python中int與str互轉(zhuǎn)方法

    python中int與str互轉(zhuǎn)方法

    最近學(xué)習(xí)python中的數(shù)據(jù)類型時(shí),難免聯(lián)想到j(luò)ava中的基本型數(shù)據(jù)類型與引用型數(shù)據(jù)類型。接下來(lái)通過本文給大家介紹python中int與str互轉(zhuǎn),需要的朋友可以參考下
    2018-07-07
  • python高級(jí)特性和高階函數(shù)及使用詳解

    python高級(jí)特性和高階函數(shù)及使用詳解

    Python很棒,它有很多高級(jí)用法值得細(xì)細(xì)思索,學(xué)習(xí)使用。這篇文章主要介紹了python高級(jí)特性和高階函數(shù)及使用詳解,需要的朋友可以參考下
    2018-10-10
  • python通過移動(dòng)端訪問查看電腦界面

    python通過移動(dòng)端訪問查看電腦界面

    這篇文章主要介紹了python通過移動(dòng)端訪問查看電腦界面,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-01-01
  • Python操作Redis數(shù)據(jù)庫(kù)的詳細(xì)教程與應(yīng)用實(shí)戰(zhàn)

    Python操作Redis數(shù)據(jù)庫(kù)的詳細(xì)教程與應(yīng)用實(shí)戰(zhàn)

    Redis是一個(gè)高性能的鍵值存儲(chǔ)數(shù)據(jù)庫(kù),支持多種類型的數(shù)據(jù)結(jié)構(gòu),如字符串、哈希表、列表、集合和有序集合等,在Python中,通過redis-py庫(kù)可以方便地操作Redis數(shù)據(jù)庫(kù),本文將詳細(xì)介紹如何在Python代碼中操作Redis,需要的朋友可以參考下
    2024-08-08
  • 關(guān)于pandas-profiling的降級(jí)之旅

    關(guān)于pandas-profiling的降級(jí)之旅

    這篇文章主要介紹了關(guān)于pandas-profiling的降級(jí)之旅,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • Python的Flask框架中web表單的教程

    Python的Flask框架中web表單的教程

    這篇文章主要介紹了Python的Flask框架中web表單的教程,表單是學(xué)習(xí)各個(gè)web框架中的基礎(chǔ)知識(shí),需要的朋友可以參考下
    2015-04-04
  • pandas數(shù)據(jù)清洗(缺失值和重復(fù)值的處理)

    pandas數(shù)據(jù)清洗(缺失值和重復(fù)值的處理)

    這篇文章主要介紹了pandas數(shù)據(jù)清洗(缺失值和重復(fù)值的處理),pandas對(duì)大數(shù)據(jù)有很多便捷的清洗用法,尤其針對(duì)缺失值和重復(fù)值,詳細(xì)介紹感興趣的小伙伴可以參考下面文章內(nèi)容
    2022-08-08

最新評(píng)論