我使用jwt-rest-framework进行用户身份验证,我想使用令牌返回user_id
。有一些关于如何使用Django-rest-framework
的例子,所以根据这个例子,我试图覆盖ObtainJSONWenToken
jwt视图并做同样的事情
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework_jwt.views import ObtainJSONWebToken
# Create your views here.
class CustomObtainJSONWebToken(ObtainJSONWebToken):
"""
Return user id with token
"""
def post(self, request, *args, **kwargs):
response = super(CustomObtainJSONWebToken, self).post(request, *args, **kwargs)
token = Token.objects.get(key=response.data['token'])
return Response({'token': token.key, 'id': token.user_id})
但Traceback指出token
它自己:
Traceback:
File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
42. response = get_response(request)
File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.5/contextlib.py" in inner
30. return func(*args, **kwds)
File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
489. response = self.handle_exception(exc)
File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/rest_framework/views.py" in handle_exception
449. self.raise_uncaught_exception(exc)
File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
486. response = handler(request, *args, **kwargs)
File "/home/copser/Documents/iToucan-BackHand/iToucan/itoucan/rest_auth/views.py" in post
15. token = Token.objects.get(key=response.data['token'])
问题是使用令牌返回user_id
的正确方法是什么,如何覆盖此视图以便实现此目的?
答案 0 :(得分:3)
您可以为jwt有效负载响应添加自定义函数:
def jwt_response_payload_handler(token, user=None, request=None):
return {
'token': token,
'user': user.id
}
在你的django设置中添加:
JWT_AUTH = {
...
'JWT_RESPONSE_PAYLOAD_HANDLER': 'your_path_to.jwt_response_payload_handler',
...
}