django rest framework-JWT

JWT Introduction

Reference https://lion1ou.win/2017/01/18/ introduction.

session with JSON Web Token difference

Sessionid generated in save to redis userid: sessionid. Sessionid then returned to the user, for the user after the tape sessionid, userid needed to verify the identity of the operator, the rear end of the sessionid verify whether the same redis sessionid.
Token session and in fact for authentication, session we need to be stored for future comparison, and Token not.
Token way is to use the algorithm to verify, you do not need to be saved to the database.

drf comes with JSON Web Token Token difference

drf comes token Token is a new table, which kept the correspondence between the user and a random value of Token, and three project database store sessionid no difference, but drf the token to put in a request header, common interface sessionid get or post on request.

使用 django-rest-framework-jwt

django have an existing JWT wheels django-rest-framework-jwt, can be used to use.

Download and install
pip install djangorestframework-jwt
Set permissions Certification

Set PERMISSION_CLASSES and AUTHENTICATION_CLASSES
global settings certification authority, in settings.pythe

REST_FRAMEWORK = {
    # 权限认证
    'DEFAULT_PERMISSION_CLASSES': (
        # 使用django标准的 'django.contrib.auth'权限,未认证的用户只读权限
        #'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
        'rest_framework.permissions.IsAuthenticated',
    ),
    # 身份验证
    'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
            'rest_framework.authentication.SessionAuthentication',
            'rest_framework.authentication.BasicAuthentication',
        ),
}

import datetime
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), # 指明token的有效期
}
url configuration
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
    url(r'^api-token-auth/', obtain_jwt_token),
]

Local authentication setting permissions, you can also set permissions in the specified ViewSet, such as information on the article do certification authority, the need to log in to gain information.

class ArticleViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet):
    queryset = Article.objects.all()  # 查询结果集
    serializer_class = ArticleSerializer # 序列化类
    pagination_class = ArticlePagination   # 自定义分页会覆盖settings全局配置的
    # 过滤器 过滤,搜索,排序
    filter_backends = (DjangoFilterBackend,filters.SearchFilter,filters.OrderingFilter)
    # 如果要允许对某些字段进行过滤,可以使用filter_fields属性。
    #filter_fields = ('title', 'category')
    # 使用自定义过滤器
    filter_class = AriticleFilter
    # 搜索
    search_fields = ('title', 'description', 'content')
    # 排序
    ordering_fields = ('id', 'read_num')

    # Token认证
    from rest_framework.permissions import IsAuthenticated
    permission_classes = (IsAuthenticated,)
test

At this time, direct access http://www.qmpython.com:8000/api/articles/ return

{
  "detail": "身份认证信息未提供。"
}
Get JWT token

In linux

curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"1q2w3e4r"}' http://www.qmpython.com:8000/api/api-token-auth/

return

{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZW1haWwiOiIxMzI4QHFxLmNvbSIsImV4cCI6MTU1OTUyODIxOCwidXNlcl9pZCI6MX0.FXh6MiTlEhx0XMkx7ofcENh0ldFdh2nqWvBLOkCcLOY"}
Url required to access rights

url token acquired above, need access privileges

curl -H "Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZW1haWwiOiIxMzI4QHFxLmNvbSIsImV4cCI6MTU1OTUyODIxOCwidXNlcl9pZCI6MX0.FXh6MiTlEhx0XMkx7ofcENh0ldFdh2nqWvBLOkCcLOY" http://www.qmpython.com:8000/api/articles/
9286065-1b7a4b63ee127344.png
image.png

Reproduced in: https: //www.jianshu.com/p/24de69d8f495

Guess you like

Origin blog.csdn.net/weixin_33785108/article/details/91315519