"detail": "未提供身份验证凭据。"一般视图

Posted

技术标签:

【中文标题】"detail": "未提供身份验证凭据。"一般视图【英文标题】:"detail": "Authentication credentials were not provided." for general views 【发布时间】:2021-10-04 19:38:34 【问题描述】:

我创建了一个自定义用户模型并应用了 Djoser 身份验证和 jwt。但是在此之后,当我尝试获取产品视图请求时,出现此错误:

"detail": "未提供身份验证凭据。"

截图如下:

这是product_views.py:


from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.response import Response
from base.serializers import ProductSerializer ,ProductCategorySerializer 
from base.models import Product, ProductCatogory, Review
from rest_framework import status


@api_view(['GET'])
def getProducts(request):
    query = request.query_params.get('keyword')
    if query is None:
        query = ''

    products = Product.objects.filter(
        name__icontains=query)
    serializer = ProductSerializer(products, many=True)
    return Response(serializer.data)


@api_view(['POST'])
@permission_classes([IsAdminUser])
def createCategory(request):
    new_category =  ProductCatogory.objects.create()
    new_category.save()

    return Response('new category created successfully')


@api_view(['PUT'])
@permission_classes([IsAdminUser])
def editCategory(request, pk):
    data = request.data
    category = ProductCatogory.objects.get(id=pk)
    category.product_category = data['product_category']
    category.save()
    serializer = ProductCategorySerializer(category, many=False)

    return Response(serializer.data)

@api_view(['DELETE'])
@permission_classes([IsAdminUser])
def deleteCategory(request, pk):
    product_Catogory = ProductCatogory.objects.get(id=pk)
    product_Catogory.delete()
    return Response('Category is deleted successfully')

@api_view(['GET'])
def getCategorys(request):
    product_category = ProductCatogory.objects.all()
    serializer = ProductCategorySerializer(product_category, many=True)
    return Response(serializer.data)


@api_view(['GET'])
def productsByCategory(request,pk):
    category = ProductCatogory.objects.get(id=pk)
    products = category.product_set.all()
    serializer = ProductSerializer(products, many=True)
    return Response(serializer.data)
@api_view(['PUT'])
def updateProductCategory(request,pk):
    data = request.data

    product_id = data['product_id']
    product = Product.objects.get(_id=product_id)
    category = ProductCatogory.objects.get(id=pk)
    product.category = category

    product.save()

    return Response('category added successfully')
  




@api_view(['GET'])
def getTopProducts(request):

    products = Product.objects.filter(
        rating__gte=4).order_by('-rating')[0:5]
    serializer = ProductSerializer(products, many=True)
    return Response(serializer.data)


@api_view(['GET'])
def getProduct(request, pk):
    product = Product.objects.get(_id=pk)
    serializer = ProductSerializer(product, many=False)
    return Response(serializer.data)


@api_view(['POST'])
@permission_classes([IsAdminUser])
def createProduct(request):
    user = request.user

    product = Product.objects.create(
        user=user,
        name='Sample Name',
        price=0,
        brand='Sample Brand',
        countInStock=0,
        
        description=''
    )

    serializer = ProductSerializer(product, many=False)
    return Response(serializer.data)


@api_view(['DELETE'])
@permission_classes([IsAdminUser])
def deleteProduct(request, pk):
    product = Product.objects.get(_id=pk)
    product.delete()
    return Response('Product is deleted successfully')


@api_view(['PUT'])
@permission_classes([IsAdminUser])
def updateProduct(request, pk):
    data = request.data
    product = Product.objects.get(_id=pk)

    product.name = data['name']
    product.price = data['price']
    product.brand = data['brand']
    product.countInStock = data['countInStock']
    product.description = data['description']

    product.save()

    serializer = ProductSerializer(product, many=False)
    return Response(serializer.data)


@api_view(['POST'])
def uploadImage(request):
    data = request.data

    product_id = data['product_id']
    product = Product.objects.get(_id=product_id)

    product.image = request.FILES.get('image')
    product.save()

    return Response('Image was uploaded')


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def createProductReview(request, pk):
    user = request.user
    product = Product.objects.get(_id=pk)
    data = request.data

    # 1 - Review already exists
    alreadyExists = product.review_set.filter(user=user).exists()
    if alreadyExists:
        content = 'detail': 'Product already reviewed'
        return Response(content, status=status.HTTP_400_BAD_REQUEST)

    # 2 - No Rating or 0
    elif data['rating'] == 0:
        content = 'detail': 'Please select a rating'
        return Response(content, status=status.HTTP_400_BAD_REQUEST)

    # 3 - Create review
    else:
        review = Review.objects.create(
            user=user,
            product=product,
            name=user.first_name,
            rating=data['rating'],
            comment=data['comment'],
        )

        reviews = product.review_set.all()
        product.numReviews = len(reviews)
# if review = product and product = category 
        total = 0
        for i in reviews:
            total += i.rating

        product.rating = total / len(reviews)
        product.save()

        return Response('Review Added')

为什么我在这里展示它,因为我想表明需要经过身份验证才能获得产品。

这里是 settings.py:

"""
Django settings for backend project.

Generated by 'django-admin startproject' using Django 3.2.5.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from datetime import timedelta
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-jyhhr)v0kyrb+^ifdlio=p3mo&l=$(^an7xb&fow--z^rxd7^r'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework_simplejwt',
    'djoser',
    'base.apps.BaseConfig',
    'accounts.apps.AccountsConfig',
    'corsheaders',
]

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',

]

ROOT_URLCONF = 'backend.urls'

TEMPLATES = [
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': 
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        ,
    ,
]

WSGI_APPLICATION = 'backend.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = 
    'default': 
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    



EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'SOMEEMAIL@gmail.com'
EMAIL_HOST_PASSWORD = 'FOOO'
EMAIL_USE_TLS = True


DJOSER = 
    'LOGIN_FIELD': 'email',
    'USER_CREATE_PASSWORD_RETYPE': True,
    'USERNAME_CHANGED_EMAIL_CONFIRMATION': True,
    'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True,
    'SEND_CONFIRMATION_EMAIL': True,
    'SET_USERNAME_RETYPE': True,
    'SET_PASSWORD_RETYPE': True,
    'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/uid/token',
    'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/uid/token',
    'ACTIVATION_URL': 'activate/uid/token',
    'SEND_ACTIVATION_EMAIL': True,
    'SERIALIZERS': 
        'user_create': 'accounts.serializers.UserCreateSerializer',
        'user': 'accounts.serializers.UserCreateSerializer',
        'user_delete': 'djoser.serializers.UserDeleteSerializer',
    

REST_FRAMEWORK = 
       'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAdminUser','rest_framework.permissions.IsAuthenticated', ),

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',

        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )




...

SIMPLE_JWT = 
    'ACCESS_TOKEN_LIFETIME': timedelta(days=30),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': True,
    'UPDATE_LAST_LOGIN': False,

    'ALGORITHM': 'HS256',
    # 'SIGNING_KEY': settings.SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': None,
  
    'AUTH_HEADER_TYPES': ('JWT',),
    'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
    'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',

    'JTI_CLAIM': 'jti',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),

# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    ,
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, javascript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'
MEDIA_URL = '/images/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


CORS_ALLOW_ALL_ORIGINS = True
MEDIA_ROOT = "static/images"

STATICFILES_DIRS = [
    BASE_DIR / "static"
]

AUTH_USER_MODEL = 'accounts.UserAccount'

我已经搜索过,但他们说要更改 REST_FRAMEWORK 的 AUTHENTICATION PERMISSIONS,正如您所看到的,我已经这样做了,但无济于事。

【问题讨论】:

您是否在请求的标头中添加了令牌? 不,我认为它不需要任何令牌...... 您必须从客户端添加令牌 您是否希望在没有令牌的情况下访问此 API?这意味着即使未经身份验证的用户也可以访问?如果没有,那么您需要令牌来验证用户。否则api如何知道哪个用户正在尝试访问 是的,我想让未经身份验证的用户可以访问。它解决了我的问题你知道怎么做吗? 【参考方案1】:

要对非认证用户开放API,需要在authentication_classes上给它一个空列表:

from rest_framework.decorators import api_view, authentication_classes, permission_classes


@api_view(['GET'])
@authentication_classes([]) # Add this
@permission_classes([]) # Maybe add this too
def getProducts(request):
    query = request.query_params.get('keyword')
    if query is None:
        query = ''

    products = Product.objects.filter(
        name__icontains=query)
    serializer = ProductSerializer(products, many=True)
    return Response(serializer.data)

【讨论】:

成功了。非常非常感谢你 。上帝保佑你???。但是我需要在每个视图上都这样做吗 在您希望任何人都可以访问的每个视图上(安全性为零)。请注意,您不会在request.user中获得任何用户 感谢您的告知,因为它导致了另一个问题。现在请提供解决方案 request.user 需要authentication_classes。你需要考虑你的设计。没有身份验证意味着没有用户。【参考方案2】:

您是否在标题中添加了标记?如果您已添加,则访问令牌必须已过期,以便您可以从刷新令牌中获取新的访问令牌

在不记名令牌等标头中添加令牌。

【讨论】:

它解决了我的问题。谢谢,但我希望任何人都可以访问产品视图,即使是未经授权的用户也是如此。你能告诉我怎么做吗?

以上是关于"detail": "未提供身份验证凭据。"一般视图的主要内容,如果未能解决你的问题,请参考以下文章

"detail": "Method \"GET\" not allowed. 在 django 中调用端点

"errors":"errors":["detail":"您无权执行此操作。","code":&qu

"detail": "未提供身份验证凭据。"创建新用户时

模型 \"Trains\ 的路径 \"setno\" 处的值 \" details: '233' \" 转换为字符串失败

为啥响应总是 "detail":"Unsupported media type \"text/plain\" in request." 在

"detail": "未提供身份验证凭据。"设置 uid 和 token 时出现此错误