You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Django JWT及DRF获取已登录用户信息方法咨询

获取已登录用户信息的几种实用方案

嘿,这个场景我太熟了!用DRF+JWT的话,获取登录用户信息其实很直接——JWT认证通过后,DRF会自动把当前用户实例绑定到request.user上,给你几个常用的实现方式:

1. 在任意认证后的视图中直接调用request.user

只要你的视图已经通过JWT认证(比如加了装饰器,或者类视图里配置了认证类),那在视图函数/方法里直接用request.user就能拿到当前登录用户的所有属性,比如request.user.username、request.user.email这些。

举个简单的业务视图例子:

from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.response import Response

@api_view(['GET'])
@authentication_classes([JSONWebTokenAuthentication])
@permission_classes([IsAuthenticated])
def my_profile(request):
    # 直接提取用户信息
    current_user = request.user
    return Response({
        'user_id': current_user.id,
        'username': current_user.username,
        'email': current_user.email,
        'full_name': f"{current_user.first_name} {current_user.last_name}"
    })

2. 专门写一个用户信息API接口

如果需要单独给前端提供拉取用户资料的接口,可以专门封装一个视图:

第一步:创建用户序列化器

先定义序列化器来控制返回字段,避免泄露敏感信息:

from rest_framework import serializers
from django.contrib.auth.models import User

class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'first_name', 'last_name')  # 只返回需要的字段

第二步:编写用户信息视图

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from .serializers import UserInfoSerializer

class UserInfoView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 用序列化器格式化用户数据
        serializer = UserInfoSerializer(request.user)
        return Response(serializer.data)

第三步:配置路由

在urls.py里添加接口路径:

from django.urls import path
from .views import UserInfoView

urlpatterns = [
    # 其他路由...
    path('api/user/info/', UserInfoView.as_view(), name='user-info'),
]

前端只要带着有效JWT token(请求头里加Authorization: Bearer <你的token>)访问这个接口,就能拿到结构化的用户信息了。

3. 全局配置认证(更省心)

如果你的大部分视图都需要JWT认证,可以在settings.py里全局配置,不用每个视图都重复写认证配置:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

这样所有视图默认都会要求JWT认证,直接在视图里用request.user就行;如果有需要开放的视图,再单独设置permission_classes = [AllowAny]。


内容的提问来源于stack exchange,提问作者cclloyd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:22:01