backend - JWT登录

首先pip安装djangorestframework-jwt

然后在django 工程中引入jwt

INSTALLED_APPS = [
    ....
    'rest_framework.authtoken'
]

REST_FRAMEWORK = {
    ....
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
    'JWT_AUTH_HEADER_PREFIX': 'JWT',
}

然后在urls.py中引用obtain_jwt_token用于验证登录信息并获取jwt token

from rest_framework_jwt.views import obtain_jwt_token
#...

urlpatterns = [
    # ...

    url(r'^api-token-auth/', obtain_jwt_token),
]

调用这个接口,如果登录信息验证通过,会返回一个token,然鹅,我们已经自定义了Json的返回,因此这个token也需要被包装

from rest_framework.exceptions import APIException
from rest_framework_jwt.views import JSONWebTokenAPIView
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from rest_framework_jwt.settings import api_settings
from rest_framework import status
from datetime import datetime

from backend.utils.json_response import JsonResponse


jwt_response_payload_handler = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER


class AuthenticationFailed(APIException):
    status_code = status.HTTP_401_UNAUTHORIZED
    default_detail = ('Incorrect authentication credentials.',)
    default_code = 'authentication_failed'


class ObtainJSONWebToken(JSONWebTokenAPIView):
    serializer_class = JSONWebTokenSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            response = JsonResponse(data=response_data, code=200, msg="Login Success")
            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    token,
                                    expires=expiration,
                                    httponly=True)
            return response
        # from rest_framework.exceptions import AuthenticationFailed, ParseError
        raise AuthenticationFailed

在urls.py中调用这个ObtainJSONWebToken就可以了

from backend.views.login import ObtainJSONWebToken
...
urlpatterns = [
    ...
    path(r'login/', ObtainJSONWebToken.as_view()),
]

你可能感兴趣的:(backend - JWT登录)