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

在Django API中通过Access Token获取自定义用户详情

Django JWT 获取用户详情实现指南

核心原理

HTTP是无状态协议,后端无法直接识别请求归属的用户,必须由前端存储并主动携带Access Token。完整流程:

  1. 用户登录成功后,后端返回Access Token和Refresh Token
  2. 前端将Access Token存储在本地(如localStorage/sessionStorage)
  3. 前端发起用户详情请求时,在请求头中携带Authorization: Bearer <你的Access Token>
  4. 后端通过JWT认证中间件解析Token,验证有效性后自动将用户信息绑定到request.user
  5. 后端视图直接从request.user中提取所需字段返回给前端

后端APIView无法主动获取Token,必须依赖前端携带的请求头——这是JWT认证的核心逻辑,也是HTTP无状态特性的必然要求。

后端实现代码

1. 确认JWT认证配置(settings.py)

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}

# 可选:配置Token有效期
from datetime import timedelta
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
}

2. 编写用户详情视图

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import status

class UserProfileView(APIView):
    # 仅允许已登录用户访问
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # request.user即为当前通过Token认证的用户实例
        user = request.user
        # 返回指定字段,避免泄露敏感信息(如密码哈希)
        profile_data = {
            'username': user.username,
            'email': user.email,
            'phone': user.phone if hasattr(user, 'phone') else '未设置'
            # 可根据你的User模型添加其他字段
        }
        return Response(profile_data, status=status.HTTP_200_OK)

3. 配置URL路由

from django.urls import path
from .views import UserProfileView

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

前端实现代码(原生JS示例)

1. 登录成功后存储Token

// 登录请求示例
async function handleLogin(username, password) {
    const res = await fetch('/api/token/', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({username, password})
    });
    const data = await res.json();
    // 将Access Token存入localStorage
    localStorage.setItem('access_token', data.access);
}

2. 点击按钮获取用户详情

// 绑定按钮点击事件
document.getElementById('get-profile-btn').addEventListener('click', async () => {
    const accessToken = localStorage.getItem('access_token');
    if (!accessToken) {
        alert('请先登录');
        return;
    }

    try {
        const res = await fetch('/api/user/profile/', {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${accessToken}`,
                'Content-Type': 'application/json'
            }
        });

        if (res.status === 401) {
            // Token过期或无效,可在此处理刷新Token逻辑
            alert('登录已过期,请重新登录');
            localStorage.removeItem('access_token');
            return;
        }

        const profile = await res.json();
        // 渲染用户信息到页面
        document.getElementById('username-display').textContent = profile.username;
        document.getElementById('email-display').textContent = profile.email;
        document.getElementById('phone-display').textContent = profile.phone;
    } catch (err) {
        console.error('获取用户信息失败:', err);
    }
});

常见问题排查

  • 401 Unauthorized错误:检查Token是否正确/过期;请求头格式是否为Bearer + 空格 + Token;后端是否配置了JWT认证类。
  • 用户字段返回null:确认User模型存在对应字段;若为自定义User模型,需确保数据库已同步迁移。
  • 视图无法获取request.user:检查视图是否添加了permission_classes = [IsAuthenticated]——只有登录用户才能触发用户信息绑定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 09:52:55