Django JWT 获取用户信息

标签 django django-rest-framework jwt

我正在使用 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/

相关文章:

django - 导入 asgi_redis : ImportError: No module named _compat

asp.net - Sql Server数据->MySql + Django迁移

python - Django Rest Framework - 自动注释查询集

python - 如何向 django 查询添加静态用户字段

c# - 在 Hangfire 中设置 JWT Bearer Token 授权/认证

django - 将 django RawQueryset 中字段的值转换为不同的 django 字段类型

python - 多个子域的 Django 多 session cookie 域

python - Django REST API 相关字段查询

Django Rest JWT 使用用户名或电子邮件登录?

c# - 具有 jwt token 和身份的 asp core 2 中基于角色的授权