我正在使用 Django JWT 身份验证和 Django Rest Framework。
获取token后如何获取登录用户的用户信息?
最佳答案
只需检查您的应用程序设置文件,无论您是否指定了 jwt 身份验证后端。
如果在那里提到并且您正在使用 User 模型(换句话说 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',
....
)
}
现在,在每个 View / View 集中,您可以使用 request.user
访问用户对象
关于Django JWT 获取用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50405425/