drf-jwt如何在登录之后返回用户对象

前言

在登录验证之后,本想返回一个user对象到前端,可是在drf发送response的时候user对象就消失了,查看源码和文档之后才了解,drf默认只会返回token

验证对象返回User
class CustomBackend(ModelBackend):
    """
    自定义用户验证
    """
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username)|Q(mobile=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

跟踪debug 会走到 jwt_response_payload_handler 方法返回一个token

drf 源码

def jwt_response_payload_handler(token, user=None, request=None):
    """
    Returns the response data for both the login and refresh views.
    Override to return a custom response such as including the
    serialized representation of the User.

    Example:

    def jwt_response_payload_handler(token, user=None, request=None):
        return {
            'token': token,
            'user': UserSerializer(user, context={'request': request}).data
        }

    """
    return {
        'token': token,
        # 'user': UserDetailSerializer(user, context={'request': request}).data
    }

我们自己可以覆盖这个方法

1. 首先在Setting配置这个方法
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
    'JWT_AUTH_HEADER_PREFIX': 'JWT',
    'JWT_RESPONSE_PAYLOAD_HANDLER':'users.views.jwt_response_payload_handler'
}
2. users.views里创建此方法
def jwt_response_payload_handler(token, user=None, request=None):
    """
    设置jwt登录之后返回token和user信息
    """
    return {
        'token': token,
        'user': UserDetailSerializer(user, context={'request': request}).data
    }

你可能感兴趣的:(drf-jwt如何在登录之后返回用户对象)