Django JWT认证报错:未提供认证信息问题求助
排查DRF+SimpleJWT认证失败:"Authentication details were not provided"问题
以下是可能的原因及对应的解决方法:
1. 未配置DRF的JWT认证类
DRF默认不会自动启用SimpleJWT的认证机制,必须在settings.py中明确配置认证类:
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), }
如果缺少这个配置,DRF无法识别请求头中的Bearer token,会直接返回认证缺失的错误。
2. URL路径格式错误
你的urls.py中路径开头带了斜杠:
path("/users/profile/", uv.getUserProfile, name="get-user-profile")
Django的path()函数不需要开头的斜杠,修正为:
path("users/profile/", uv.getUserProfile, name="get-user-profile")
虽然路径不匹配不一定直接导致认证错误,但可能引发路由匹配异常,间接导致请求未被正确的视图处理。
3. 请求头格式不正确
确认Postman中的Authorization请求头严格遵循格式:
- 键:
Authorization - 值:
Bearer <你的access_token>
注意Bearer和token之间必须有一个空格,且token不能包含多余的空格、换行或引号。
4. 使用了无效/过期的Token
- 确保使用的是access token,而非refresh token:refresh token仅用于获取新的access token,无法直接访问需要认证的接口。
- 检查token是否过期:可以通过SimpleJWT的默认配置或自定义配置(如
ACCESS_TOKEN_LIFETIME)确认过期时间,过期则重新获取新的access token。
5. 视图未指定认证类(可选)
如果全局配置未生效,可在视图上单独指定认证类:
from rest_framework_simplejwt.authentication import JWTAuthentication @api_view(['GET']) @authentication_classes([JWTAuthentication]) # 添加这一行 @permission_classes([IsAuthenticated]) def getUserProfile(request): user = request.user serializer = UserSerializer(user, many=False) return Response(serializer.data)
优先推荐全局配置,避免重复代码。
内容的提问来源于stack exchange,提问作者Zoclhas
相关产品推荐
相关产品推荐

