drf-jwt
官网
http://getblimp.github.io/django-rest-framework-jwt/
安装子:虚拟环境
pip install djangorestframework-jwt
使用:user/urls.py
from django.urls import path from rest_framework_jwt.views import obtain_jwt_token urlpatterns = [ path('login/', obtain_jwt_token), ]
测试接口:post请求
""" postman发生post请求 接口:http://api.luffy.cn:8000/user/login/ 数据: { "username":"admin", "password":"admin" } """
自定义jwt登录(手动签发jwt)
1、View.py中定义一个类
from rest_framework.views import APIView from rest_framework_jwt.serializers import jwt_payload_handler from rest_framework_jwt.serializers import jwt_encode_handler from django.contrib import auth class LoginAPIView(APIView): def post(self,request,*args,**kwargs): username = request.data.get('username') password = request.data.get('password') if not (username and password): return Response({ 'error':'用户名或密码不能为空' }) user_obj = auth.authenticate(username=username,password=password,is_active=True) if user_obj: payload = jwt_payload_handler(user_obj) token = jwt_encode_handler(payload) return Response({ 'status':0, 'msg':'ok', 'token':token }) else: return Response({ 'status':1, 'msg':'用户名或密码错误' })
2、serializers.py中定义基于auth_user的序列化与反序列化的类
class LoginModelSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ('username', 'password') extra_kwargs = { 'password':{ 'write_only':True } }
3、url中设置指向路由
from api import views url(r'^login/$', views.LoginAPIView.as_view()),
jwt过期时间
在setting中配置
import datetime
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
}
authentication_classes和permission_classes
两者配合使用可省略session
必须完成jwt校验才能得到登陆状态
# authentication_classes = [JSONWebTokenAuthentication] authentication_classes = [JWTAuthentication] # 登陆后才能查看 permission_classes = [IsAuthenticated]
基于drf-jwt的全局认证:user/authentications.py(自己创建)
import jwt from rest_framework.exceptions import AuthenticationFailed from rest_framework_jwt.authentication import jwt_decode_handler from rest_framework_jwt.authentication import get_authorization_header from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication class JSONWebTokenAuthentication(BaseJSONWebTokenAuthentication): def authenticate(self, request): jwt_value = get_authorization_header(request) if not jwt_value: raise AuthenticationFailed('Authorization 字段是必须的') try: payload = jwt_decode_handler(jwt_value) except jwt.ExpiredSignature: raise AuthenticationFailed('签名过期') except jwt.InvalidTokenError: raise AuthenticationFailed('非法用户') user = self.authenticate_credentials(payload) return user, jwt_value
全局启用:settings/dev.py
REST_FRAMEWORK = { # 认证模块 'DEFAULT_AUTHENTICATION_CLASSES': ( 'user.authentications.JSONWebTokenAuthentication', ), }
局部启用禁用:任何一个cbv类首行
# 局部禁用 authentication_classes = [] # 局部启用 from user.authentications import JSONWebTokenAuthentication authentication_classes = [JSONWebTokenAuthentication]