Django JWT 获取用户信息

ccl*_*oyd 5 django jwt django-rest-framework

我在 Django Rest Framework 中使用 Django JWT 身份验证。
检索令牌后,如何获取已登录用户的用户信息?

Asi*_*med 7

只需检查您的应用程序设置文件,无论您是否指定了 jwt 身份验证后端。如果它在那里提到并且您使用的是用户模型(换句话说,django.contrib.auth.models.User)request.user将起作用

如果您使用自己的自定义 User 模型

from django.conf import settings
from rest_framework import authentication
from rest_framework import exceptions
from rest_framework.authentication import get_authorization_header
import CustomUser # just import your model here
import jwt

class JWTAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request): # it will return user object
        try:
            token = get_authorization_header(request).decode('utf-8')
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            print(token)
            decoded = jwt.decode(token, settings.SECRET_KEY)
            username = decoded['username']
            user_obj = CustomUser.objects.get(username=username)
        except jwt.ExpiredSignature :
            raise exceptions.AuthenticationFailed('Token Expired, Please Login')
        except jwt.DecodeError :
            raise exceptions.AuthenticationFailed('Token Modified by thirdparty')
        except jwt.InvalidTokenError:
            raise exceptions.AuthenticationFailed('Invalid Token')
        except Exception as e:
            raise exceptions.AuthenticationFailed(e)
        return (user_obj, None)

    def get_user(self, userid):
        try:
            return CustomUser.objects.get(pk=userid)
        except Exception as e:
            return None
Run Code Online (Sandbox Code Playgroud)

并在您的应用中添加以下设置

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'path_to_custom_authentication_backend',
        ....
    )
}
Run Code Online (Sandbox Code Playgroud)

现在在每个视图/视图集中,您可以访问用户对象 request.user


Joh*_*fis 3

通过阅读有关DRF 身份验证的文档以及 @neverwalkaloner 在他的评论中提到的,我们发现我们可以django.contrib.auth.User使用该属性在视图中访问登录用户的实例request.user

阅读 DRF 推荐的 JWT 模块的文档:

我没有发现任何证据表明他们更改/覆盖访问登录用户实例信息的方法。