Django——Django REST framework JWT

Django REST framework JWT

我们在验证完用户的身份后(检验用户名和密码),需要向用户签发JWT,在需要用到用户身份信息的时候,还需核验用户的JWT。

关于签发和核验JWT,我们可以使用Django REST framework JWT扩展来完成。

文档网站http://getblimp.github.io/django-rest-framework-jwt/

安装配置

安装

pip install djangorestframework-jwt

配置

REST_FRAMEWORK = {
   'DEFAULT_PERMISSION_CLASSES': [
'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # 全局验证
],
} JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), }
  • JWT_EXPIRATION_DELTA 指明token的有效期

 不设置成全局的话:

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")

 

账号登录

1. 业务说明

验证用户名和密码,验证成功后,为用户签发JWT,前端将签发的JWT保存下来。

2. 后端接口设计

请求方式: POST meiduo_admin/authorizations/

请求参数: JSON 或 表单

参数名类型是否必须说明
username str 用户名
password str 密码

返回数据: JSON

{
    "username": "python",
    "user_id": 1,
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo5LCJ1c2VybmFtZSI6InB5dGhvbjgiLCJleHAiOjE1MjgxODI2MzQsImVtYWlsIjoiIn0.ejjVvEWxrBvbp18QIjQbL1TFE0c0ejQgizui_AROlAU"
}
返回值类型是否必须说明
username str 用户名
id int 用户id
token str 身份认证凭据

3. 后端实现

Django REST framework JWT提供了登录签发JWT的视图,可以直接使用

from rest_framework_jwt.views import obtain_jwt_token

urlpatterns = [
    url(r'^authorizations/$', obtain_jwt_token),
]

但是默认的返回值仅有token,我们还需在返回值中增加username和user_id。

通过修改该视图的返回值可以完成我们的需求。

在users/utils.py 中,创建

 

def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'id': user.id,
        'username': user.username
    }

修改配置文件

# JWT配置
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
    'JWT_RESPONSE_PAYLOAD_HANDLER': 'meiduo_admin.utils.jwt_response.jwt_response_payload_handler',
}

 验证:

 

posted @ 2021-02-24 10:51  pywjh  阅读(197)  评论(0编辑  收藏  举报
回到顶部