Django實(shí)現(xiàn)接口token檢測(cè)的完整實(shí)現(xiàn)方案
一、Token認(rèn)證的實(shí)現(xiàn)思路
- 用戶(hù)登錄后生成Token:用戶(hù)登錄成功后,服務(wù)器生成一個(gè)Token,并返回給客戶(hù)端。
- 客戶(hù)端請(qǐng)求時(shí)攜帶Token:客戶(hù)端在每次請(qǐng)求時(shí),將Token放入HTTP請(qǐng)求頭(Headers)中。
- 服務(wù)器端驗(yàn)證Token:Django后端解析請(qǐng)求中的Token,并驗(yàn)證其合法性。
- Token校驗(yàn)通過(guò),允許訪問(wèn)接口;否則,返回未授權(quán)的錯(cuò)誤信息。

二、環(huán)境準(zhǔn)備
在Django項(xiàng)目中,我們可以使用rest_framework.authtoken或者自定義Token認(rèn)證邏輯。這里介紹兩種方式:
- 基于 Django REST framework(DRF) 的 Token 認(rèn)證
- 自定義 Token 認(rèn)證
三、基于 Django REST Framework(DRF)的 Token 認(rèn)證
Django REST Framework 提供了現(xiàn)成的 Token 認(rèn)證機(jī)制,下面是實(shí)現(xiàn)步驟。
1. 安裝 Django REST framework
如果還未安裝 Django REST framework,請(qǐng)使用 pip 安裝:
pip install djangorestframework pip install djangorestframework.authtoken

2. 添加到 Django 配置
在 settings.py 中啟用 Django REST framework 和 Token 認(rèn)證:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken',]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}
3. 生成 Token 表
運(yùn)行 Django 遷移命令,創(chuàng)建 Token 認(rèn)證所需的數(shù)據(jù)表:
python manage.py migrate
4. 創(chuàng)建 API 視圖
創(chuàng)建用戶(hù)登錄接口,生成并返回 Token。
from django.contrib.auth import authenticate
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
class LoginView(APIView):
def post(self, request):
username = request.data.get("username")
password = request.data.get("password")
user = authenticate(username=username, password=password)
if user:
token, created = Token.objects.get_or_create(user=user)
return Response({"token": token.key})
return Response({"error": "Invalid Credentials"}, status=status.HTTP_401_UNAUTHORIZED)
5. 保護(hù) API 端點(diǎn)
在 API 視圖中使用 TokenAuthentication 保護(hù) API,僅允許持有有效 Token 的用戶(hù)訪問(wèn):
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
class ProtectedView(APIView):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({"message": "You have access to this protected endpoint."})
6. 測(cè)試 API
獲取 Token:
curl -X POST http://127.0.0.1:8000/api/login/ -H "Content-Type: application/json" -d '{"username": "admin", "password": "password"}'
服務(wù)器返回:
{"token": "abc123xyz456"}
訪問(wèn)受保護(hù)的 API:
curl -X GET http://127.0.0.1:8000/api/protected/ -H "Authorization: Token abc123xyz456"
服務(wù)器返回:
{"message": "You have access to this protected endpoint."}
四、自定義 Token 認(rèn)證方案
如果不使用 DRF 自帶的 TokenAuthentication,我們也可以自定義 Token 認(rèn)證。
1. 自定義 Token 模型
在 models.py 中創(chuàng)建 Token 存儲(chǔ)表:
from django.db import models
from django.contrib.auth.models import User
import uuid
class CustomToken(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
key = models.CharField(max_length=255, unique=True, default=uuid.uuid4)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.key
2. 創(chuàng)建 Token 生成邏輯
在 views.py 中定義登錄邏輯,生成自定義 Token:
from django.contrib.auth import authenticate
from django.http import JsonResponse
from .models import CustomToken
def custom_login(request):
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(username=username, password=password)
if user:
token, created = CustomToken.objects.get_or_create(user=user)
return JsonResponse({"token": token.key})
return JsonResponse({"error": "Invalid credentials"}, status=401)3. 中間件攔截 Token
在 middleware.py 中定義 Token 驗(yàn)證邏輯:
from django.http import JsonResponse
from .models import CustomToken
class TokenMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
token = request.headers.get("Authorization")
if not token:
return JsonResponse({"error": "Token missing"}, status=401)
try:
user_token = CustomToken.objects.get(key=token)
request.user = user_token.user
except CustomToken.DoesNotExist:
return JsonResponse({"error": "Invalid token"}, status=401)
return self.get_response(request)
然后,在 settings.py 中啟用中間件:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.authentication.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'myapp.middleware.TokenMiddleware', # 添加自定義 Token 認(rèn)證中間件
]
4. 受保護(hù)的 API
在 views.py 中定義需要 Token 認(rèn)證的接口:
from django.http import JsonResponse
def protected_view(request):
return JsonResponse({"message": "Welcome, you are authenticated!"})
5. 測(cè)試
獲取 Token:
curl -X POST http://127.0.0.1:8000/custom_login/ -d "username=admin&password=admin"
返回:
{"token": "abc123xyz456"}
訪問(wèn)受保護(hù) API:
curl -X GET http://127.0.0.1:8000/protected_view/ -H "Authorization: abc123xyz456"
返回:
{"message": "Welcome, you are authenticated!"}
五、總結(jié)
本方案介紹了 Django 中實(shí)現(xiàn)接口 Token 認(rèn)證的兩種方法:
- 使用 Django REST framework(DRF)的 Token 認(rèn)證:適用于 REST API,簡(jiǎn)單易用。
- 自定義 Token 認(rèn)證:適用于更靈活的需求,可定制 Token 規(guī)則、過(guò)期策略等。
以上代碼和步驟確保了 API 的安全性,避免未經(jīng)授權(quán)的訪問(wèn),適用于 Django Web 項(xiàng)目的用戶(hù)身份驗(yàn)證。
到此這篇關(guān)于Django實(shí)現(xiàn)接口token檢測(cè)的完整實(shí)現(xiàn)方案的文章就介紹到這了,更多相關(guān)Django接口token檢測(cè)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python提取包含關(guān)鍵字的整行數(shù)據(jù)方法
今天小編就為大家分享一篇python提取包含關(guān)鍵字的整行數(shù)據(jù)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12
一文教你Python如何使用sqlparse玩轉(zhuǎn)SQL解析
sqlparse?是一個(gè)?Python?第三方庫(kù),專(zhuān)門(mén)用于解析和格式化?SQL?語(yǔ)句,它提供了強(qiáng)大的?SQL?解析功能,下面小編就來(lái)為大家詳細(xì)介紹一下它的具體使用吧2025-02-02
基于Python編寫(xiě)一個(gè)有趣的進(jìn)程勾選器(Process?Selector)
本文主要介紹了如何利用Python編寫(xiě)一個(gè)有趣的進(jìn)程勾選器,可以在Checklistbox中列出系統(tǒng)中正在運(yùn)行的進(jìn)程的名稱(chēng)和PID,并允許用戶(hù)選擇進(jìn)程并將其保存到文本文件中,需要的可以參考一下2023-05-05
一步步教你用python的scrapy編寫(xiě)一個(gè)爬蟲(chóng)
這篇文章主要給大家介紹了如何利用python的scrapy編寫(xiě)一個(gè)爬蟲(chóng)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用scrapy具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
Python編程之基于概率論的分類(lèi)方法:樸素貝葉斯
這篇文章主要介紹了Python編程之基于概率論的分類(lèi)方法:樸素貝葉斯,簡(jiǎn)單介紹了其概述,貝葉斯理論和條件概率,以及樸素貝葉斯的原理等相關(guān)內(nèi)容,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11
tensorflow實(shí)現(xiàn)KNN識(shí)別MNIST
這篇文章主要為大家詳細(xì)介紹了tensorflow實(shí)現(xiàn)KNN識(shí)別MNIST,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03
如何在python中實(shí)現(xiàn)ECDSA你知道嗎
這篇文章主要為大家介紹了python中實(shí)現(xiàn)ECDSA,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助,希望能夠給你帶來(lái)幫助2021-11-11
使用Pandas計(jì)算系統(tǒng)客戶(hù)名稱(chēng)的相似度
在日常業(yè)務(wù)處理中,我們經(jīng)常會(huì)面臨將不同系統(tǒng)中的數(shù)據(jù)進(jìn)行匹配和比對(duì)的情況,本文將介紹如何使用Python的Pandas庫(kù)來(lái)處理這個(gè)問(wèn)題,需要的可以參考一下2023-07-07

