• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Django 实现JWT登录认证

武飞扬头像
哥的心、禁止访问
帮助1

依赖:

Django版本:2.2.5

djangorestframework:3.12.1

djangorestframework-jwt:1.11.0

废话不说直接上代码:

主urls.py文件(ratelimt用于登录频繁限制)

  1.  
    from django.contrib import admin
  2.  
    from django.urls import path,include,re_path
  3.  
    from rest_framework_jwt.views import obtain_jwt_token
  4.  
    from ratelimit.decorators import ratelimit
  5.  
     
  6.  
     
  7.  
    urlpatterns = [
  8.  
    # jwt的认证接口
  9.  
    re_path('api/(?P<version>[v1|v2] )/login/$', ratelimit(key='ip', method='POST', rate='1/6s',block=True)(obtain_jwt_token)),
  10.  
    ]

settings配置:

  1.  
    #有效期限
  2.  
    JWT_AUTH = {
  3.  
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), #也可以设置seconds=?
  4.  
    'JWT_AUTH_HEADER_PREFIX': 'JWT', #JWT跟前端保持一致,比如“token”这里设置成JWT
  5.  
    'JWT_RESPONSE_PAYLOAD_HANDLER': 'app.utils.jwt_reponse_revised.jwt_response_payload_handler', # response中token的payload部分处理函数
  6.  
    }

JWT_RESPONSE_PAYLOAD_HANDLER为当前项目指定文件夹下的函数名

由于源码中会调取此函数作为登录接口的Response

drf源码如下:

  1.  
    jwt_response_payload_handler = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER
  2.  
     
  3.  
     
  4.  
     
  5.  
    class JSONWebTokenAPIView(APIView):
  6.  
    """
  7.  
    Base API View that various JWT interactions inherit from.
  8.  
    """
  9.  
    permission_classes = ()
  10.  
    authentication_classes = ()
  11.  
     
  12.  
    def get_serializer_context(self):
  13.  
    """
  14.  
    Extra context provided to the serializer class.
  15.  
    """
  16.  
    return {
  17.  
    'request': self.request,
  18.  
    'view': self,
  19.  
    }
  20.  
     
  21.  
    def get_serializer_class(self):
  22.  
    """
  23.  
    Return the class to use for the serializer.
  24.  
    Defaults to using `self.serializer_class`.
  25.  
    You may want to override this if you need to provide different
  26.  
    serializations depending on the incoming request.
  27.  
    (Eg. admins get full serialization, others get basic serialization)
  28.  
    """
  29.  
    assert self.serializer_class is not None, (
  30.  
    "'%s' should either include a `serializer_class` attribute, "
  31.  
    "or override the `get_serializer_class()` method."
  32.  
    % self.__class__.__name__)
  33.  
    return self.serializer_class
  34.  
     
  35.  
    def get_serializer(self, *args, **kwargs):
  36.  
    """
  37.  
    Return the serializer instance that should be used for validating and
  38.  
    deserializing input, and for serializing output.
  39.  
    """
  40.  
    serializer_class = self.get_serializer_class()
  41.  
    kwargs['context'] = self.get_serializer_context()
  42.  
    return serializer_class(*args, **kwargs)
  43.  
     
  44.  
    def post(self, request, *args, **kwargs):
  45.  
    serializer = self.get_serializer(data=request.data)
  46.  
    if serializer.is_valid():
  47.  
    user = serializer.object.get('user') or request.user
  48.  
    token = serializer.object.get('token')
  49.  
    response_data = jwt_response_payload_handler(token, user, request)
  50.  
    response = Response(response_data)
  51.  
    if api_settings.JWT_AUTH_COOKIE:
  52.  
    expiration = (datetime.utcnow()
  53.  
    api_settings.JWT_EXPIRATION_DELTA)
  54.  
    response.set_cookie(api_settings.JWT_AUTH_COOKIE,
  55.  
    token,
  56.  
    expires=expiration,
  57.  
    httponly=True)
  58.  
    return response
  59.  
     
  60.  
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
学新通

jwt_response_payload_handler函数内容:

  1.  
    def jwt_response_payload_handler(token,user=None,request=None):
  2.  
    """为返回的结果添加用户相关信息"""
  3.  
    return {
  4.  
    'result' : {
  5.  
    'token':"JWT " token,#与配置保持一致
  6.  
    'username':user.loginName,
  7.  
    'userid':user.userId
  8.  
    }
  9.  
    }

实例:

学新通

使用:

前端需将Token添加到headers中Authorization

后端验证方式:

  1.  
    from rest_framework_jwt.authentication import JSONWebTokenAuthentication
  2.  
    class SampleView(mixins.ListModelMixin):
  3.  
    queryset = Sample_info.objects.all()
  4.  
    serializer_class = SampleSerializers
  5.  
    module_name = 'sample'
  6.  
    filter_backends = (filters.DjangoFilterBackend, Order,)
  7.  
    filter_class = SampleInfoFilter
  8.  
    pagination_class = SamplePagination
  9.  
    ordering_fields = ('receipt_date',)
  10.  
    permission_classes = [IsAuthenticated, ]
  11.  
    authentication_classes = [JSONWebTokenAuthentication]#<--------token验证
  12.  
    def get(self, request, *args, **kwargs):
  13.  
    return self.list(request, *args, **kwargs)

JSONWebTokenAuthentication源码:

  1.  
     
  2.  
    class JSONWebTokenAuthentication(BaseJSONWebTokenAuthentication):
  3.  
    """
  4.  
    Clients should authenticate by passing the token key in the "Authorization"
  5.  
    HTTP header, prepended with the string specified in the setting
  6.  
    `JWT_AUTH_HEADER_PREFIX`. For example:
  7.  
     
  8.  
    Authorization: JWT eyJhbGciOiAiSFMyNTYiLCAidHlwIj
  9.  
    """
  10.  
    www_authenticate_realm = 'api'
  11.  
     
  12.  
    def get_jwt_value(self, request):
  13.  
    auth = get_authorization_header(request).split()
  14.  
    auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower()
  15.  
    if not auth:
  16.  
    if api_settings.JWT_AUTH_COOKIE:
  17.  
    return request.COOKIES.get(api_settings.JWT_AUTH_COOKIE)
  18.  
    return None
  19.  
    if smart_text(auth[0].lower()) != auth_header_prefix:
  20.  
    return None
  21.  
    if len(auth) == 1:
  22.  
    msg = _('Invalid Authorization header. No credentials provided.')
  23.  
    raise exceptions.AuthenticationFailed(msg)
  24.  
    elif len(auth) > 2:
  25.  
    msg = _('Invalid Authorization header. Credentials string '
  26.  
    'should not contain spaces.')
  27.  
    raise exceptions.AuthenticationFailed(msg)
  28.  
    return auth[1]
  29.  
     
  30.  
    def authenticate_header(self, request):
  31.  
    """
  32.  
    Return a string to be used as the value of the `WWW-Authenticate`
  33.  
    header in a `401 Unauthenticated` response, or `None` if the
  34.  
    authentication scheme should return `403 Permission Denied` responses.
  35.  
    """
  36.  
    return '{0} realm="{1}"'.format(api_settings.JWT_AUTH_HEADER_PREFIX, self.www_authenticate_realm)
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhibeijg
系列文章
更多 icon
同类精品
更多 icon
继续加载