我在具有React Native前端的Django-Rest应用程序上遇到令牌身份验证问题。我一直使用会话身份验证,这是我第一次建立具有这些要求的项目。
我已安装点子-
djangorestframework_simplejwt
我知道当我碰到端点api/token
我能够在前端检索它们。当我尝试在后端访问列表路由时出现我的问题,并且返回的错误如下。
{
"detail": "Authentication credentials were not provided."
}
我认为这可能是cors问题,或者是我的axios请求出现问题,但我可以肯定它们设置正确。另一个问题是我的视图集中的身份验证和权限类,这是我的直觉告诉我这个问题的来源。
相关settings.py信息-
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
)
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
视图集/序列化器/网址
class WorkoutViewSet(ModelViewSet):
model = apps.get_model('backend', 'Workout')
queryset = model.objects.all()
serializer_class = serializers.WorkoutSerializer
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
class WorkoutSerializer(serializers.ModelSerializer):
class Meta:
model = apps.get_model('backend', 'Workout')
fields = ('name', 'is_complete', 'allow_copy', 'workout_goal', 'user')
router.register(r'workouts', views.WorkoutViewSet, base_name='workouts')
Axios请求
export const workouts = (token) => {
return axios({
method: 'get',
url: 'http://localhost:8000/workouts',
headers: { 'authorization': `Bearer ${token}`}
})
}
感谢任何帮助/指导。
答案 0 :(得分:2)
在您的视图集中,您指定了用于设置 TokenAuthentication 的authentication_classes。
这意味着,对于您的 WorkoutViewSet ,您指定仅使用TokenAuthentication-在标头中使用Token前缀,因此会得到“ 未提供凭据”
如果要使用JWT令牌身份验证-您应在此处明确设置它或将其删除,然后让默认选择的类处理身份验证