django使用jwt对FBV接口登陆验证

前言:

背景是在基于原有的DRF框架的小程序项目迭代,习惯于使用原生django接口模式,使用FBV来写视图函数,但是原来的DRF接口权限和认证用的jwt,也就是在VIEWsSet中使用permission_classes来限制权限。所以想了很久,要么把已经写好的代码改成DRF的CBV形式,要么重写一个登录验证,要么想办法接入以前的登录验证用于我现在的接口(要么删库跑人)。

不多说DRF的权限和登陆验证了,直接大概记录一下在新写的接口加入jwt验证。

1. 首先来到一波操作猛如虎,写一个装饰器验证是否登录
def require_login(func):
    def wrapper(request, *args, **kwargs):
        if not request.user.is_authenticated:
            return HttpResponse(status=401)
        return func(request, *args, **kwargs)
    return wrapper

这个是最简单的对model里面的user进行验证,发现request里面根本没有user,怎么调用都是匿名用户AnonymousUser,因为在drf写的登陆验证只有在调用相关的接口才会进行验证,原生的django接口又不能使用permission_classes。所以需要手动接入token拿过来解析得到user在传给request.user.

2.然后想办法搞懂jwt验证的流程和相关源码,通过打断点慢慢跑1万次项目debug 终于看清楚了流程。

两个类:JSONWebTokenAuthentication以及它的父类BaseJSONWebTokenAuthentication

class JSONWebTokenAuthentication(BaseJSONWebTokenAuthentication):
    """
    Clients should authenticate by passing the token key in the "Authorization"
    HTTP header, prepended with the string specified in the setting
    `JWT_AUTH_HEADER_PREFIX`. For example:

        Authorization: JWT eyJhbGciOiAiSFMyNTYiLCAidHlwIj
    """
    www_authenticate_realm = 'api'

    def get_jwt_value(self, request):
        auth = get_authorization_header(request).split()
        auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower()


        if not auth:
            if api_settings.JWT_AUTH_COOKIE:
                return request.COOKIES.get(api_settings.JWT_AUTH_COOKIE)
            return None

        if smart_text(auth[0].lower()) != auth_header_prefix:
            return None

        if len(auth) == 1:
            msg = _('Invalid Authorization header. No credentials provided.')
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid Authorization header. Credentials string '
                    'should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)

        return auth[1]

    def authenticate_header(self, request):
        """
        Return a string to be used as the value of the `WWW-Authenticate`
        header in a `401 Unauthenticated` response, or `None` if the
        authentication scheme should return `403 Permission Denied` responses.
        """
        return '{0} realm="{1}"'.format(api_settings.JWT_AUTH_HEADER_PREFIX, self.www_authenticate_realm)

主要是下面这个类的两个类方法,authenticate(self, request)把request请求里面的请求头"Authorization"也就是token字符串拿出来解析成user。

class BaseJSONWebTokenAuthentication(BaseAuthentication):
    """
    Token based authentication using the JSON Web Token standard.
    """

    def authenticate(self, request):
        """
        Returns a two-tuple of `User` and token if a valid signature has been
        supplied using JWT-based authentication.  Otherwise returns `None`.
        """

        jwt_value = self.get_jwt_value(request)
        if jwt_value is None:
            return None

        try:
            payload = jwt_decode_handler(jwt_value)
        except jwt.ExpiredSignature:
            msg = _('Signature has expired.')
            raise exceptions.AuthenticationFailed(msg)
        except jwt.DecodeError:
            msg = _('Error decoding signature.')
            raise exceptions.AuthenticationFailed(msg)
        except jwt.InvalidTokenError:
            raise exceptions.AuthenticationFailed()

        user = self.authenticate_credentials(payload)

        return (user, jwt_value)

    def authenticate_credentials(self, payload):
        """
        Returns an active user that matches the payload's user id and email.
        """
        User = get_user_model()
        username = jwt_get_username_from_payload(payload)

        if not username:
            msg = _('Invalid payload.')
            raise exceptions.AuthenticationFailed(msg)

        try:
            user = User.objects.get_by_natural_key(username)
        except User.DoesNotExist:
            msg = _('Invalid signature.')
            raise exceptions.AuthenticationFailed(msg)

        if not user.is_active:
            msg = _('User account is disabled.')
            raise exceptions.AuthenticationFailed(msg)

        return user

如果想用我们自己的user模型就需要重写这个类BaseJSONWebTokenAuthentication里面的authenticate_credentials方法,如下:

class JWTAuthentication(JSONWebTokenAuthentication):
    def authenticate_credentials(self, payload):
        id = payload.get('id')
        try:
            user = User.objects.get(id=id)
        except User.DoesNotExist:
            raise exceptions.AuthenticationFailed('用户不存在')
        return user
3.跑流程开始:
3.1先重写authenticate_credentials方法,如上面的代码,然后在装饰器里面实例化:如下面写好的登陆验证装饰器。
def require_login(func):
    def wrapper(request, *args, **kwargs):
        # request.META['HTTP_AUTHORIZATION'] = 'JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6OTgsInd4X3VpZCI6ImNoZW5yb25nMDAxIiwibmFtZSI6Ilx1OTY0OFx1ODRjOSIsImlzX3N0YWZmIjpmYWxzZSwib3JpZ19pYXQiOjE2MDYxMTE1MTZ9.ncpQ5uZv2n2uGyc4q86D9AYgQlfLjd___7D33E0jEdY'
        jwt = JWTAuthentication()
        if jwt.authenticate(request):
            user, jwt_value = jwt.authenticate(request)
            # django的原来的user,不是用户model的user
            # 利用重写的authenticate_credentials方法来获取model的user
            request.user = user
        if not request.user.is_authenticated:
            return HttpResponse(status=401)
        return func(request, *args, **kwargs)
    return wrapper
3.2 把装饰器装在某个接口函数上面,调用接口,request请求进入装饰器内部,通过调用的authenticate(request)方法,代码走到这:
image.png
3.3 然后通过调用get_jwt_value(request)方法:也就是JSONWebTokenAuthentication里面的get_jwt_value(self, request):
image.png
3.3 到了这里,request就开始解析请求头,get_jwt_value(self, request)函数中的auth变量就是token字符串分割好的列表:比如:

auth=["JWT","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6OTgsInd4X3VpZCI6ImNoZW5yb25nMDAxIiwibmFtZSI6Ilx1OTY0OFx1ODRjOSIsImlzX3N0YWZmIjpmYWxzZSwib3JpZ19pYXQiOjE2MDYxMTE1MTZ9.ncpQ5uZv2n2uGyc4q86D9AYgQlfLjd___7D33E0jEdY"]
auth_header_prefix变量就是‘jwt’字符串,是设置好了的标识符(我自己取的名字),这个方法主要是验证是否传了token,并且验证是否是有‘jwt’标志。是的话返回token字符串(这里只是纯字符串,没有jwt三个字符了)。

3.4 流程回到了authenticate(self, request):方法这里,里面的jwt_value已经获得了,就是3.2中手的token字符串,把它拿去解析jwt_decode_handler(jwt_value)得到payload,payload其实是存用户信息的一个字典。比如:
{
        'id': user.id,
        'image': user.image,
        'name': user.name,
        'uid': user.wx_uid,
        'token': token,
        'is_staff': user.is_staff
    }
3.5 得到payload之后,authenticate(self, request)方法会调用authenticate_credentials方法得到user,
user = self.authenticate_credentials(payload)

然后把user放进request.user,就可以进行用户验证了。request.user = user.

你可能感兴趣的:(django使用jwt对FBV接口登陆验证)