我有一个代理用户模型:
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))
应该可以通过覆盖^{} 身份验证类并将代理用户模型设置为
user_model
来使用代理模型,如下所示:假设您在
myapp/authentication.py
上添加此类,则可以将此自定义身份验证类作为REST_FRAMEWORK
设置中的默认身份验证类之一应用:或者仅将其应用于所需的某些视图:
这应该反过来为您提供一个
request.user
,它是一个TheDude
实例相关问题 更多 >
编程相关推荐