Django REST framework JWT 和登錄功能實(shí)現(xiàn)
前后分離token的方式做登錄身份校驗(yàn)预鬓,jwt校驗(yàn)方式更加簡單便捷化乌妒,無需通過redis緩存箱残,而是直接根據(jù)token取出保存的用戶信息志笼,以及對token可用性校驗(yàn)韭脊,單點(diǎn)登錄更為簡單。
配置環(huán)境:
python 3.7
Django==2.1.11
djangorestframework-jwt==1.10.0
一、安裝
pip install djangorestframework-jwt
二拦赠、配置
1.打開項(xiàng)目中settings配置
import datetime
# drf框架的配置信息
REST_FRAMEWORK = {
# 設(shè)置所有接口都需要被驗(yàn)證
'DEFAULT_PERMISSION_CLASSES': (
#’rest_framework.permissions.IsAuthenticatedOrReadOnly’,
),
# 用戶登陸認(rèn)證方式
'DEFAULT_AUTHENTICATION_CLASSES': (
‘rest_framework_jwt.authentication.JSONWebTokenAuthentication’,
#’rest_framework.authentication.SessionAuthentication’,
#’rest_framework.authentication.BasicAuthentication’,
),
}
# jwt載荷中的有效期設(shè)置
JWT_AUTH = {
#token 有效期
'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=8),
'JWT_ALLOW_REFRESH': True,
#續(xù)期有效期(該設(shè)置可在24小時(shí)內(nèi)帶未失效的token 進(jìn)行續(xù)期)
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(hours=24),
# 自定義返回格式巍沙,需要手工創(chuàng)建
'JWT_RESPONSE_PAYLOAD_HANDLER': ‘Users.utils.jwt_response_payload_handler’,
}
2.創(chuàng)建自定義返回?cái)?shù)據(jù)格式
# 創(chuàng)建用戶應(yīng)用
python manage.py startapp Users
在Users應(yīng)用目錄下新建utils.py 并配置文件
“””
自定義jwt認(rèn)證成功返回?cái)?shù)據(jù)
:token 返回的jwt
:user 當(dāng)前登錄的用戶信息[對象]
:request 當(dāng)前本次客戶端提交過來的數(shù)據(jù)
:role 角色
“””
def jwt_response_payload_handler(token, user=None, request=None, role=None):
if user.first_name:
name = user.first_name
else:
name = user.username
return {
"authenticated": ‘true’,
'id': user.id,
"role": role,
'name': name,
'username': user.username,
'email': user.email,
'token': token,
}
三、使用
- 申請token
1.打開項(xiàng)目中urls.py 配置路由
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('Users.urls’)),
]
2.在Users應(yīng)用目錄下創(chuàng)建并打開urls.py
# jwt內(nèi)部實(shí)現(xiàn)的登陸視圖
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token
from django.urls import path
urlpatterns = [
path(r"login", obtain_jwt_token),
]
3.打開postman
Postman 申請token
- token 續(xù)期
在Users應(yīng)用目錄下打開urls.py
# jwt內(nèi)部實(shí)現(xiàn)的登陸視圖
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token
from django.urls import path
urlpatterns = [
path(r"login", obtain_jwt_token),
path(r"refresh", refresh_jwt_token),
]
Postman token續(xù)期
四荷鼠、驗(yàn)證
驗(yàn)證的時(shí)候句携,我們使用的是rest_framework 框架,該框架使用將在其他文檔詳細(xì)敘述。
permission是權(quán)限驗(yàn)證 IsAuthenticated必須登錄用戶 IsOwnerOrReadOnly必須是當(dāng)前登錄的用戶
from rest_framework.permissions import IsAuthenticated,IsAuthenticatedOrReadOnly
# 分頁配置
class LargeResultsSetPagination(PageNumberPagination):
page_size = 10
page_size_query_param = 'page_size'
max_page_size = 10000
# 域名列表
class DomainManageList(viewsets.ReadOnlyModelViewSet):
# authentication是用戶認(rèn)證
authentication_classes = (JSONWebTokenAuthentication,)
# permission是權(quán)限驗(yàn)證 IsAuthenticated必須登錄用戶 IsOwnerOrReadOnly必須是當(dāng)前登錄的用戶
# permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
#判斷是否登陸
permission_classes = (IsAuthenticated, )
#查詢所有信息
queryset = Domain_Manage.objects.all()
#序列化
serializer_class = DomainManageListSerializers
pagination_class = LargeResultsSetPagination