zoukankan      html  css  js  c++  java
  • django中token的签发

    1.下载JWT

    pip install djangorestframework-jwt

    2.签发token

    #导入jwt
    from
    rest_framework_jwt.serializers import jwt_payload_handler from rest_framework_jwt.serializers import jwt_encode_handler
    #导入jwt默认的登录模块
    from django.contrib import auth class LoginAPIView(APIView): def post(self, request, *args, **kwargs): username = request.data.get('username') password = request.data.get('password') if not (username and password): return Response({ 'error': 'username与password为必须字段' }) user_obj = auth.authenticate(username=username, is_active=True, password=password) if user_obj: # 签发token payload = jwt_payload_handler(user_obj) token = jwt_encode_handler(payload) return Response({ 'status': 0, 'msg': 'ok', 'token': token }) else: return Response({ 'status': 1, 'msg': 'username与password有误' })

    3.全局配置jwt和局部配置

    # 全局认证组件
     REST_FRAMEWORK={
         'DEFAULT_AUTHENTICATION_CLASSES':[
             'app01.cache_jwt.JwtToken',
        ]
     }
    #设置token过期时间
    import datetime
    JWT_AUTH = {
        # 过期时间
        'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
    }


    #局部使用jwt
    authentication_classes = [JwtToken]
    #局部禁用jwt
    authentication_classes = []

    4.jwt的验证

    from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
    from rest_framework_jwt.authentication import jwt_decode_handler
    from rest_framework import exceptions
    
    class JwtToken(BaseJSONWebTokenAuthentication):
        def authenticate(self, request):
    
            jwt_value = request.META.get('HTTP_TOKEN')
            if not jwt_value:
                raise exceptions.AuthenticationFailed('token 字段是必须的')
            try:
                payload = jwt_decode_handler(jwt_value)
            except jwt.ExpiredSignature:
                raise exceptions.AuthenticationFailed('token已过期')
            except jwt.InvalidTokenError:
                raise exceptions.AuthenticationFailed('token非法')
    
            user = self.authenticate_credentials(payload)
    
            return (user, jwt_value)

     注释:严格的token验证是要在签发的时候存进数据库或者缓存中,然后在前端向后端发送数据的时候从数据库中或者缓存中取出来进行校验

  • 相关阅读:
    Google开源框架盒子模型之Android---<FlexboxLayout>(认知篇)
    Android Studio配置中AndroidAnnotations
    Android Studio分包引发的血案(App启动一直黑屏问题)
    Android Studio打包APK过大问题的研究
    Android WebView JS互调案例
    Eclipse版本android 65535解决方案(原理等同android studio现在的分包方式)
    Android MVP + 泛型,实现了友好VP交互及Activity潜在的内存泄露的优化
    mysql数据监控(db.odbc.select[])
    zabbix 默认消息
    zabbix 利用脚本发邮件(mail)
  • 原文地址:https://www.cnblogs.com/xzcvblogs/p/12345110.html
Copyright © 2011-2022 走看看