简体   繁体   English

使用Django Rest框架进行JWT令牌认证

[英]JWT Token Authentication with Django Rest Framework

I am having some issues with token authentication on my Django-Rest application with a react native frontend. 我在具有React Native前端的Django-Rest应用程序上遇到令牌身份验证的一些问题。 I have always used Session Authentication, and this is my first time setting up a project with these requirements. 我一直使用会话身份验证,这是我第一次建立具有这些要求的项目。

I pip installed - 我点安装-

djangorestframework_simplejwt

I know the tokens are being generated when I hit the endpoint api/token 我知道当我点击端点api/token时正在生成api/token

I am able to retrieve them on the front end. 我可以在前端检索它们。 My problem occurs when I try to hit a list route in the backend and the error I get back is as follows. 当我尝试在后端访问列表路由时出现我的问题,并且返回的错误如下。

{
    "detail": "Authentication credentials were not provided."
}

I thought this could be a cors issue, or an issue with my axios request, but I am fairly certain they are setup correctly. 我以为这可能是cors问题,或者是我的axios请求存在问题,但我可以肯定它们设置正确。 The other issue is the authentication and permissions classes in my viewset which is where my intuition is telling me this problem is coming from. 另一个问题是我的视图集中的身份验证和权限类,这是我的直觉告诉我这个问题的来源。

Relevant settings.py info -- 相关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',
    )
}

Viewset/Serializer/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 Request Axios请求

export const workouts = (token) => {
  return axios({
    method: 'get',
    url: 'http://localhost:8000/workouts',
      headers: { 'authorization': `Bearer ${token}`}
  })
} 

Thanks for any help/direction. 感谢您的帮助/指导。

in your viewset, you have specified authentication_classes where you set TokenAuthentication . 在您的视图集中,您已经指定了设置AuthenticationAuthentication的authentication_classes

That means, for your WorkoutViewSet you specified to use only TokenAuthentication - which uses Token prefix in the header, hence you get ' Credentials not provided ' 这意味着,对于您的WorkoutViewSet,您指定仅使用TokenAuthentication-在标头中使用Token前缀,因此您将获得“ 未提供凭据

If you want to use the JWT token authentication - you should either set it explicitly here or remove it and let the default chosen classes handle the authentication 如果要使用JWT令牌身份验证-您应该在此处明确设置它或将其删除,然后让默认选择的类处理身份验证

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM