使用REST framework JWT时更改默认用户

2024-09-21 01:15:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代理用户模型:

class TheDude(User):
    class Meta:
        proxy = True

我正在使用Django REST框架JWT在REST API中进行JWT身份验证

我想从请求中获取用户对象,但目前它是一个用户对象。因为它是代理的,所以我不能使用AUTH_USER_MODEL。我尝试过使用中间件组件覆盖请求中的用户,但在那个阶段没有设置。我也尝试过使用JWT_RESPONSE_PAYLOAD_HANDLER,但是我的函数没有被调用,所以我也不能在那里设置它

如果我希望在调用视图中的request.user而不是User时能够获取TheDude对象,那么在使用REST框架JWT Auth库进行身份验证时,我将如何做到这一点

编辑

我补充说

REST_FRAMEWORK = {
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        ...
        'myapp.authentication.MyCustomJWTAuthentication',
    )
    ...
}

到my settings.py和my

class MyCustomJWTAuthentication(JWTAuthentication):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.user_model = TheDude

但是,当我从serialiser中的请求获取用户时,它仍然是User类型,而不是TheDude类型

class TestSerializer(serializers.ModelSerializer):

    user_test = serializers.SerializerMethodField('get_user_test')

    def get_user_test(self, obj):
        print(type(self.context['request'].user))

Tags: 对象用户testself框架身份验证rest代理
1条回答
网友
1楼 · 发布于 2024-09-21 01:15:41

应该可以通过覆盖^{}身份验证类并将代理用户模型设置为user_model来使用代理模型,如下所示:

from rest_framework_simplejwt.authentication import JWTAuthentication


class MyCustomJWTAuthentication(JWTAuthentication):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.user_model = TheDude

假设您在myapp/authentication.py上添加此类,则可以将此自定义身份验证类作为REST_FRAMEWORK设置中的默认身份验证类之一应用:

REST_FRAMEWORK = {
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'myapp.authentication.MyCustomJWTAuthentication',
        ...
        
    )
    ...
}

或者仅将其应用于所需的某些视图:

from myapp.authentication import MyCustomJWTAuthentication


class CertainAPIViewThatNeedsTheDude(APIView):
    authentication_classes = (MyCustomJWTAuthentication, )

这应该反过来为您提供一个request.user,它是一个TheDude实例

相关问题 更多 >

    热门问题