我的django rest应用程序在使用react本机前端时遇到了令牌身份验证问题。我一直使用会话身份验证,这是我第一次设置具有这些要求的项目。
I PIP已安装-
djangorestframework_simplejwt
我知道当我到达端点时,令牌正在生成
api/token
我能在前端找到它们。我的问题发生在我尝试在后端访问列表路由时,返回的错误如下所示。
{
"detail": "Authentication credentials were not provided."
}
我认为这可能是一个CORS问题,或者是我的AXIOS请求的一个问题,但是我确信它们是正确设置的。另一个问题是viewset中的authentication和permissions类,我的直觉告诉我这个问题是从这里来的。
相关设置.py info--
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',
)
}
视图集/序列化程序/url
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}`}
})
}
谢谢你的帮助/指导。