1. 程式人生 > 實用技巧 >django使用jwt對DRF介面登陸驗證

django使用jwt對DRF介面登陸驗證

前言:

背景是在基於原有的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.