You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django REST Framework卖家注册接口401未授权问题排查

问题描述

在使用Django REST Framework的Serializer和APIView实现卖家注册功能时,调用注册接口(path('sregister/',SellerRegistrationView.as_view(),name='sregister'))返回401状态码及提示“Authentication credentials were not provided.”。即使在视图中添加permission_classes = [AllowAny]仍无效,仅移除settings.py中DEFAULT_PERMISSION_CLASSES的IsAuthenticated配置后问题消失,但需保留全局认证权限以支持后续登录、商品添加等功能。


错误排查与解决方案

核心问题是视图类的权限配置位置错误,同时存在其他语法/拼写问题,导致AllowAny权限未生效。

1. 权限类定义位置错误

DRF要求permission_classes必须作为视图类的类属性定义,才能覆盖全局默认权限。你之前把permission_classes = [AllowAny]写在了post方法内部,这种写法完全无效,框架无法识别该配置。

2. 其他代码问题

  • SellerRegistrationView中返回响应时存在拼写错误:serilizer.data → 应为serializer.data
  • SellerLoginView的post方法定义有语法错误:方法声明后多了冒号,且权限配置位置错误
  • SellerLoginView中调用认证方法时,authenticate_seller.authenticate写法错误,应使用Django内置的authenticate方法(需提前导入)

修正后的代码

views.py 修正版

from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.permissions import AllowAny
from rest_framework import status
from django.http import JsonResponse
from django.contrib.auth import authenticate  # 导入内置认证方法

def get_tokens_for_user(user):
    refresh = RefreshToken.for_user(user)
    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    }

class SellerRegistrationView(APIView):
    # 正确定义为类属性,覆盖全局权限
    permission_classes = [AllowAny]

    def post(self, request, format=None):
        serializer = SellerRegistrationSerializer(data=request.data) 
        if serializer.is_valid(raise_exception=True):
            seller = serializer.save()
            token = get_tokens_for_user(seller)
            # 修正拼写错误
            return JsonResponse(serializer.data, status=status.HTTP_201_CREATED)
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class SellerLoginView(APIView):
    # 正确定义为类属性
    permission_classes = [AllowAny]

    def post(self, request, format=None):
        serializer = SellerLoginSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            email = serializer.data.get('email')
            password = serializer.data.get('password')
            # 修正认证调用方式
            seller = authenticate(request, email=email, password=password)
            if seller is not None:
                token = get_tokens_for_user(seller)
                return JsonResponse({'token': token}, status=status.HTTP_200_OK)
            else:
                return JsonResponse(
                    {'errors': {'non_field_errors': ['Email or password is not valid']}}, 
                    status=status.HTTP_404_NOT_FOUND
                )
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

验证说明

修正后,SellerRegistrationView和SellerLoginView的permission_classes = [AllowAny]会正确覆盖全局的IsAuthenticated权限,注册和登录接口无需认证即可访问,同时其他接口仍受全局权限控制,满足业务需求。

内容的提问来源于stack exchange,提问作者Pramit Khatri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 17:55:55