首页 > 其他 > 详细

jwt

时间:2019-09-09 13:08:33      阅读:120      评论:0      收藏:0      [点我收藏+]

pip install djangorestframework-jwt

# 此路由可以直接生成token,可以用postman测试

from django.urls import path
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
    path(login/, obtain_jwt_token),
]

"""
postman发生post请求

接口:http://api.luffy.cn:8000/user/login/

数据:
{
    "username":"admin",
    "password":"admin"
}
"""

 

在settings文件中加入jwt配置

 

import datetime
JWT_AUTH = {
    # 过期时间
    JWT_EXPIRATION_DELTA: datetime.timedelta(days=1),
    # 自定义认证结果:见下方序列化user和自定义response
    JWT_RESPONSE_PAYLOAD_HANDLER: user.utils.jwt_response_payload_handler,  
}

 

自定义返回结果方式如下:

from .serializers import UserModelSerializers
def jwt_response_payload_handler(token, user=None, request=None):
    return {
        status: 0,
        msg: ok,
        data: {
            token: token,
            user: UserModelSerializers(user).data
        }
    }

自定义jwt认证类

 

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)  # 获取请求头中的token {‘Authorization‘:‘jwt token‘}

        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

 

jwt的启用

 

 

全局启用

在settings文件中配置

 

REST_FRAMEWORK = {
    # 认证模块
    DEFAULT_AUTHENTICATION_CLASSES: (
        user.authentications.JSONWebTokenAuthentication,
    ),
}

 

局部禁用与启用

cbv类,需要继承APIViews

# 局部禁用
authentication_classes = []

# 局部启用
from user.authentications import JSONWebTokenAuthentication
authentication_classes = [JSONWebTokenAuthentication]

多方式登录

user/utils.py

import re
from .models import User
from django.contrib.auth.backends import ModelBackend
class JWTModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            if re.match(r^1[3-9]\d{9}$, username):
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except User.DoesNotExist:
            return None
        if user.check_password(password) and self.user_can_authenticate(user):
            return user

settings配置

AUTHENTICATION_BACKENDS = [user.utils.JWTModelBackend]

手动签发jwt

from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

‘‘‘
另外一种导入
from rest_framework_jwt.serializers import jwt_payload_handler
from rest_framework_jwt.serializers import jwt_encode_handler
‘‘‘

payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)

 

jwt

原文:https://www.cnblogs.com/zhouze/p/11490897.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!