早上好
我正在编写我的第一个DRF API,并使用django-rest-framework-jwt(https://getblimp.github.io/django-rest-framework-jwt/)处理JWT身份验证。
我当前正在使用内置视图:
@Test
public void testProcessingResult() throws Exception {
final Box<Object> resultBox = new Box();
snsClient.subscribe(new SubscribeRequest(topicArn,
msg -> resultBox.setValue(extractResult(msg))
));
...
httpClient.post(endpoint, params); // send the request
Thread.sleep(2000); // wait for eventual processing
assertEquals(expected, resultBox.getValue());
}
,但需要将一些用户信息返回给UI(VueJS)。我想将用户ID和名称信息存储到Vuex存储中,以传递到后续的API调用中并呈现给用户(“ Hello Jim!”)。
我发现在讨论为jwt有效负载响应添加自定义函数时发现了这一点: jwt rest framework returning user id with token
我不确定该在哪里做...
感谢您的澄清。
BCBB
答案 0 :(得分:1)
有两种解决方案
1)首先,用户ID是在JWT中编码的,您可以自己在js中对其进行解码。
2)您可以按以下方式覆盖从django-rest-framework-jwt返回的有效负载:
例如,将以下代码放在您的accounts
应用中名为utils.py
def jwt_response_payload_handler(token, user=None, request=None):
return {
'token': token,
'username': user.username,
'user_id' : user.id,
'email' : user.email
}
并在rest-framework-jwt
设置中替换
'JWT_RESPONSE_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_response_payload_handler',
有了这个
'JWT_RESPONSE_PAYLOAD_HANDLER':
'accounts.utils.jwt_response_payload_handler',