【发布时间】:2018-10-28 13:07:55
【问题描述】:
我在 Django Rest Framework 中使用 Django JWT 身份验证。
获取令牌后如何获取登录用户的用户信息?
【问题讨论】:
-
尝试
request.user如果您在请求中提供了令牌,它应该可以工作。
标签: django django-rest-framework jwt
我在 Django Rest Framework 中使用 Django JWT 身份验证。
获取令牌后如何获取登录用户的用户信息?
【问题讨论】:
request.user 如果您在请求中提供了令牌,它应该可以工作。
标签: django django-rest-framework jwt
通过阅读DRF Authentication 上的文档以及@neverwalkaloner 在他的评论中提到的那样,我们看到我们可以通过使用request.user 属性在视图中访问登录用户的django.contrib.auth.User 实例。
阅读 DRF 推荐的两个 JWT 模块的文档:
我没有发现任何证据表明他们更改/覆盖了访问登录用户实例信息的方法。
【讨论】:
只需检查您的应用程序设置文件,您是否指定了 jwt 身份验证后端。
如果它在那里提到并且如果您使用的是用户模型(换句话说 django.contrib.auth.models.User)request.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
并在您的应用中添加以下设置
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'path_to_custom_authentication_backend',
....
)
}
现在在每个视图/视图集中,您可以使用 request.user 访问用户对象
【讨论】:
如果你熟悉 django rest jwt,你可能会在你的 settings.py 中看到这样的配置:
JWT_AUTH = {
.....
'JWT_RESPONSE_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_response_payload_handler',
'JWT_SECRET_KEY': SECRET_KEY,
....
}
您可以像下面这样简单地创建一个方法,例如 my_custom_jwt_response_payload_handler,并将 JWT_RESPONSE_PAYLOAD_HANDLER 寻址到新的处理程序:
def jwt_response_payload_handler(token, user=None, request=None):
return {
'token': token,
'user': {
'username': user.username, 'id': user.id,
...
}
}
您可以在此响应中添加所需的任何数据。然后用你的新处理程序修补 settings.py:
JWT_AUTH = {
.....
'JWT_RESPONSE_PAYLOAD_HANDLER':
'localtion-to-my-own-handler-file.my_custom_jwt_response_payload_handler',
....
}
为了更好地理解,我建议阅读jwt_response_payload_handler in here 的原始源代码和 cmets
【讨论】:
一旦您登录,意味着您已通过 Django 身份验证,现在您可以在代码中的任何位置检索当前用户详细信息。
request.user
请求包含用户通过身份验证后的用户模型的所有详细信息。否则,它将显示 Anonymus 用户。
【讨论】: