zoukankan      html  css  js  c++  java
  • JWT安装配置与使用

    1.JWT安装配置


     

    1.1 安装JWT

    pip install djangorestframework-jwt==1.11.0

     1.2 syl/settings.py 配置jwt载荷中的有效期设置

    # jwt载荷中的有效期设置
    JWT_AUTH = {
        # 1.token前缀:headers中 Authorization 值的前缀
        'JWT_AUTH_HEADER_PREFIX': 'JWT',
        # 2.token有效期:一天有效
        'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
        # 3.刷新token:允许使用旧的token换新token
        'JWT_ALLOW_REFRESH': True,
        # 4.token有效期:token在24小时内过期, 可续期token
        'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(hours=24),
        # 5.自定义JWT载荷信息:自定义返回格式,需要手工创建
        'JWT_RESPONSE_PAYLOAD_HANDLER': 'user.utils.jwt_response_payload_handler',
    }
    jwt载荷中的有效期设置

     1.3 syl/settings.py JWT结合DRF进行认证权限配置

     

    # 在DRF配置文件中开启认证和权限
    REST_FRAMEWORK = {
      ...
      # 用户登陆认证方式
      'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # 在DRF中配置JWT认证
        # 'rest_framework.authentication.SessionAuthentication', # 使用session时的认证器
        # 'rest_framework.authentication.BasicAuthentication' # 提交表单时的认证器
      ],
      # 权限配置, 顺序靠上的严格
      'DEFAULT_PERMISSION_CLASSES': [
      # 'rest_framework.permissions.IsAdminUser', # 管理员可以访问
      'rest_framework.permissions.IsAuthenticated', # 全局配置只有认证用户可以访问接口
      # 'rest_framework.permissions.IsAuthenticatedOrReadOnly', # 认证用户可以访问, 否则只能读取
      # 'rest_framework.permissions.AllowAny', # 所有用户都可以访问
      ],
    ...
    }

    1.4 user/urls.py 增加获取token接口和刷新token接口 

    # -*- coding: utf-8 -*-
    from django.urls import path, include
    from user import views
    from rest_framework.routers import SimpleRouter, DefaultRouter
    from rest_framework.authtoken.views import obtain_auth_token
    from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token
    
    # 自动生成路由方法, 必须使用视图集
    # router = SimpleRouter() # 没有根路由 /user/ 无法识别
    router = DefaultRouter()  # 1. 有根路由
    router.register(r'user', views.UserViewSet)  # 2. 配置路由
    urlpatterns = [
        path('index/', views.index),
        path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),  # 认证地址
    
        path('login/', obtain_jwt_token),  # 获取token,登录视图
        path('refresh/', refresh_jwt_token),  # 刷新token
    
        path('apiview/', views.UserInfoViewSet.as_view()),
    
    ]
    
    urlpatterns += router.urls  # 3. 模块地址
    rest_framework_jwt

    1.5 在user/utils.py中从写jwt_response_payload_handler

    # -*- coding: utf-8 -*-
    def jwt_response_payload_handler(token, user=None, request=None, role=None):
    
        """
      自定义jwt认证成功返回数据
      :token 返回的jwt
      :user 当前登录的用户信息[对象]
      :request 当前本次客户端提交过来的数据
      :role 角色
        """
        if user.first_name:
            name = user.first_name
        else:
            name = user.username
        return {
            'authenticated': 'true',
            'id': user.id,
            "role": role,
            'name': name,
            'username': user.username,
            'email': user.email,
            'token': token,
        }
    jwt_response_payload_handler

     2.postman测试接口

     2.1 测试登录接口,获取token

     

    http://192.168.56.100:8888/user/login/

     

     

    '''自定义认证和权限优先级更高,可以覆盖settings.py中的 '''
    # 自定义权限类
    permission_classes = (MyPermission,)
    # 自定义认证类, 自定义会覆盖全局配置
    authentication_classes = (JSONWebTokenAuthentication,)

     2.2 使用获得的token获取所有用户信息

     

    http://192.168.56.100:8888/user/login/
    

     

     3.源码分析

    class JSONWebTokenAPIView(APIView):
      """
      Base API View that various JWT interactions inherit from.
      """
      permission_classes = ()
      authentication_classes = ()
      
    def get_serializer_context(self):     """     Extra context provided to the serializer class.     """     return {       'request': self.request,       'view': self,     }   def get_serializer_class(self):     """     Return the class to use for the serializer.     Defaults to using `self.serializer_class`.     You may want to override this if you need to provide different     serializations depending on the incoming request.     (Eg. admins get full serialization, others get basic serialization)     """     assert self.serializer_class is not None, (       "'%s' should either include a `serializer_class` attribute, "       "or override the `get_serializer_class()` method."       % self.__class__.__name__)     return self.serializer_class   def get_serializer(self, *args, **kwargs):     """     Return the serializer instance that should be used for validating and     deserializing input, and for serializing output.     """     serializer_class = self.get_serializer_class()     kwargs['context'] = self.get_serializer_context()     return serializer_class(*args, **kwargs)   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 # User表对象       token = serializer.object.get('token') # 获取到生成的token       response_data = jwt_response_payload_handler(token, user, request)       response = Response(response_data)        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    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

     

    1.编写注册接口

    1.1 user/urls.py 中添加路由

    urlpatterns = [
    path('register/', views.RegisterView.as_view()), # 注册视图, /user/register/
    ]

     1.2 user/views.py 中写注册视图函数

    class RegisterView(APIView):
        """
        用户注册, 权限是: 匿名用户可访问
        """
        # 自定义权限类
        permission_classes = (AllowAny,)
    
        def post(self, request):
            """
            接收邮箱和密码, 前端校验两遍一致性, 注册成功后返回成功, 然            
            后用户自行登录获取token
            1. 随机用户名
            2. 生成用户
            3. 设置用户密码
            4. 保存用户
            :param request:
            :return: {'code':0,'msg':'注册成功'}
            """
            email = request.data.get('email')
            passwrod = request.data.get('password')
    
            if all([email, passwrod]):
                pass
            else:
                return Response({'code':9999,'msg':'参数不全'})
            rand_name = self.randomUsername()
            user = User(username=rand_name, email=email)
            user.set_password(passwrod)
            user.save()
    
            return Response({'code': 0, 'msg': '注册成功'})
    
        def randomUsername(self):
            """
            生成随机用户名: 格式: SYL + 年月日时分 + 5位随机数
            :return:
            """
            d = datetime.datetime.now()
            base = 'SYL'
            time_str = '%04d%02d%02d%02d%02d'  %(d.year,d.month, d.day, d.hour,d.minute)
            rand_num = str(random.randint(10000, 99999)   
            return base + time_str + rand_num
                     

     2.重写django认证

    2.1 syl/settings.py 中指定自定义后端认证函数位置

    # 自定义验证后端
    AUTHENTICATION_BACKENDS = ['user.utils.EmailAuthBackend']

    2.2 user/utils.py 中重写认证函数

    # 以前使用username进行用户验证,现在修改成email进行验证
    class EmailAuthBackend:
        def authenticate(self, request, username=None, password=None):
            try:
                user = User.objects.get(username=username)
            except Exception as e:
                print(e)
                user = None
            if not user:
                try:
                    user = User.objects.get(email=username)
                except Exception as e:
                    print(e)
                    user = None
            if user and user.check_password(password):
                return user
            else:
                return None
    
        def get_user(self, user_id):
            try:
                return User.objects.get(pk=user_id)
            except User.DoesNotExist:
                return None
    EmailAuthBackend

    3.注册用户 & 测试登录

    3.1 注册接口测试

    http://192.168.56.100:8888/user/register/

     3.2 登录接口测试

    注: 认证时只能识别username,所以必须要在请求中携带username字段

    http://192.168.56.100:8888/user/login/

     3.3 获取用户列表接口测试

      · 访问接口

    http://192.168.56.100:8888/user/user/5/

      · 测试自定义权限

    # 自定义权限类
    permission_classes = (MyPermission,)
    # 自定义认证类, 自定义会覆盖全局配置
    authentication_classes = (JSONWebTokenAuthentication,)

  • 相关阅读:
    B树,B+树
    中断
    死锁
    无锁队列
    Cookie和Session
    分布式系统一致性
    c++ 标准库迭代器失效
    html5 app图片预加载
    html5 手机APP计算高度问题
    html5 750 REM JS换算方法
  • 原文地址:https://www.cnblogs.com/pythonqwertytre/p/13771740.html
Copyright © 2011-2022 走看看