Django Simple JWT:如何在视图层获取登录用户ID?
问题描述
首次使用Simple JWT实现网站授权功能,登录流程正常,但在视图中通过request.user.id无法获取登录用户ID(返回null)。相关代码如下:
后端视图代码
@api_view(['GET']) def test(request): if request.method == 'GET': return Response({'id':request.user.id})
前端登录代码
export default function Login(){ const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [loggedIn, setLoggedIn] = useState(localStorage.access_token ? true : false); const submit = async e => { e.preventDefault(); const user = { email: username, password: password }; const response = await fetch("http://localhost:8000/token/", { method: "POST", headers: { "Content-Type":"application/json", }, body: JSON.stringify(user), }) const data = await response.json(); localStorage.clear(); localStorage.setItem('access_token', data.access); localStorage.setItem('refresh_token', data.refresh); setLoggedIn(true); } return( ... some form ... ) }
URL配置
from rest_framework_simplejwt import views as jwt_views urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('accounts.urls')), path('api/', include('posts.urls')), path('token/', jwt_views.TokenObtainPairView.as_view(), name ='token_obtain_pair'), path('token/refresh/', jwt_views.TokenRefreshView.as_view(), name ='token_refresh'), ]
解决方案
1. 后端配置JWT认证机制
当前视图未配置认证逻辑,DRF无法识别JWT令牌并关联到request.user,需添加认证和权限类:
局部视图配置(仅当前test视图生效)
修改后端视图代码:
from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework.permissions import IsAuthenticated @api_view(['GET']) @authentication_classes([JWTAuthentication]) @permission_classes([IsAuthenticated]) def test(request): if request.method == 'GET': return Response({'id': request.user.id})
全局配置(所有API视图生效)
在项目settings.py中添加DRF全局配置:
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) }
2. 前端请求携带JWT令牌
登录成功后,调用test接口时需在请求头中携带access_token,否则后端无法识别用户身份。示例请求代码:
async function fetchUserInfo() { const token = localStorage.getItem('access_token'); const response = await fetch("http://localhost:8000/api/test/", { // 替换为你的test接口实际URL method: "GET", headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json" } }); const data = await response.json(); console.log(data); }
内容的提问来源于stack exchange,提问作者KermitHQ
相关产品推荐
相关产品推荐

