session+cookie+md5+jwt原生

1 session和cookie

cookie存储在客户端

session存储在服务端

session依赖于cookie,异步请求没有带上cookieid,session永远用不了

请求头没有cookie,session用不了,因为没有cookie id

2 使用try...expect的好处

try ... except 节省IO操作

3 make_password 万能

  • 不可逆
import hashlib

def make_password(mypass):

	md5 = hashlib.md5()

	#定义加密对象
	sign_str = mypass
	#转码
	sign_utf8 = str(sign_str).encode(encoding="utf-8")
	#加密
	md5.update(sign_utf8)
	#生成密文
	md5_server = md5.hexdigest()

	return md5_server


print(make_password("123"))

4 token用 py_jwt库

  • token可逆
  • token过期,重定向到登录界面
  • token容易被窃取,一定要设置过期时间
import jwt

#加密

encode_jwt = jwt.encode({'uid':'123'},'123',algorithm='HS256')

print(encode_jwt)

#解密

#强转
encode_jwt = str(encode_jwt,'utf-8')

decode_jwt = jwt.decode('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIxMjMifQ.5dsjJNESZl-wHQGCz6b-lmmUVlXmWcyiOI4rIpWM4cs','123',algorithms=['HS256'])

print(decode_jwt)

5 jwt使用

5.1 前端封装

  • http/index.js
axios.interceptors.request.use(
    config => {
        // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了
        const token = localStorage.getItem("token")
            // console.log(token)
        if (token) {
            config.headers.Authorization = 'JWT ' + token
        }
        return config;
    },
    error => {
        return Promise.error(error);
    })

5.2 后端生成+解密

  • 视图中传递要生成token的字典(包含用户信息)
class LoginView(APIView):
    def post(self, request):
        num = request.data.get('num')
        username = request.data.get('username')
        password = request.data.get('password')
        get_key = request.data.get('session_key')
        user = UserModel.objects.filter(username=username).first()
        if check_password(password, user.password):
            session_data = Session.objects.get(pk=get_key).get_decoded()
            num_get = session_data.get('num')
            # 因为前端已经保存cookieid,不需要再次上传这个
            # num_get = request.session.get('num')
            if num == str(num_get):
                user_obj = {
                    'user_id': user.pk,
                    'user_name': user.username,
                    'role_id': user.role_id
                }
                token = create_token(user_obj)
                return Response(
                    {'msg': '登录成功', 'code': 200, 'token': token, 'num':num, 'username': user.username}
                )
        return Response(
            {'msg': '登录失败', 'code': 400}
        )
5.2.1 生成
def create_token(user):
    user['exp'] = datetime.now() + timedelta(minutes=30)
    token = jwt.encode(user, settings.SECRET_KEY, algorithm='HS256')
    return token
5.2.2 解密
from django.conf import settings
from django.http import HttpResponse
from rest_framework_jwt.utils import jwt_decode_handler
import jwt
from jwt import exceptions


def decodeToken(request):
    token = request.META.get('HTTP_AUTHORIZATION')
    print('this is token', token)
    # user_info = jwt_decode_handler(token[4:])
    # return user_info
    try:
        user_info = jwt.decode(token[4:], settings.SECRET_KEY)
        print('this is user_info', user_info)
    except exceptions.ExpiredSignatureError:
        return HttpResponse('token已经失效')
    except jwt.DecodeError:
        return HttpResponse('token认证失败')
    except jwt.InvalidIssuer:
        return HttpResponse('非法的token')
    return user_info
posted @ 2020-12-21 19:00  狐狸大大爱吃糖  阅读(130)  评论(0编辑  收藏  举报