赞
踩
Python 3.6.5
Django 1.11
Django REST Framework 3.8
pip install djangorestframework-jwt
注意:这里,我们安装的是djangorestframework-jwt 1.11;
例如,获取当前用户已下架的主题接口:
from rest_framework_jwt.authentication import JSONWebTokenAuthentication # jwt用户认证 from rest_framework.authentication import SessionAuthentication # session用户认证 class MyRepealTopicViewset(mixins.ListModelMixin, viewsets.GenericViewSet): """ list: 获取当前用户已下架的主题 """ # 权限判断:IsAuthenticated表示是否已经登录 permission_classes = (IsAuthenticated,) # 用户认证:方式一:JSONWebTokenAuthentication;方式二:SessionAuthentication authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication) serializer_class = MyRepealTopicSerializer def get_queryset(self): """返回当前用户已下架的主题""" return Topic.objects.filter(publisher=self.request.user, delete_flag=False, topic_status="已下架").order_by("-add_time")
在setting.py中,将JSONWebTokenAuthentication 添加到DEFAULT_AUTHENTICATION_CLASSES中。
# 配置系统认证的方式
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication', # username和password形式认证
'rest_framework.authentication.SessionAuthentication',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # 全局jwt
),
}
注意:一般使用局部JWT;
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
url(r'^login/$', obtain_jwt_token), # jwt的认证接口
]
# 设置jwt的过期时间
import datetime
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7), # token过期时间是7天
'JWT_AUTH_HEADER_PREFIX': 'JWT',
}
参考资料:
REST framework JWT Auth
源码:https://github.com/GetBlimp/django-rest-framework-jwt
官网文档:http://getblimp.github.io/django-rest-framework-jwt/
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。