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

Posted

技术标签:

【中文标题】"detail": "未提供身份验证凭据。"创建新用户时【英文标题】:"detail": "Authentication credentials were not provided." When Creating a new user 【发布时间】:2020-04-02 03:05:46 【问题描述】:

当他们注册我的应用程序时,我正在尝试在我的平台中创建一个新用户。我希望他们输入他们的详细信息并将其发送到服务器以创建帐户,以便他们可以登录然后接收令牌。每当我使用邮递员发送凭据时,我都会收到此错误:

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

这是我目前所拥有的:

Settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'buddysapp',
    'oauth2_provider',
    'social_django',
    'rest_framework_social_oauth2',
    'bootstrap3',
    'multiselectfield',
    'openinghours',
    'whitenoise.runserver_nostatic',
    'import_export',
    'phone_field',
    'django_s3_storage',
    'rest_framework',
    'rest_auth',
    'rest_framework.authtoken',

]


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

    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
        'rest_framework_social_oauth2.authentication.SocialAuthentication',
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',



    ),

REST_USE_JWT = True



def jwt_get_username_from_payload_handler(user):

    return 
        'username': user.username,
        'email': user.email
    


SIMPLE_JWT = 
    'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=30),
    'REFRESH_TOKEN_LIFETIME': datetime.timedelta(hours=1),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': True,

    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',

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

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

Views.py

@api_view(['POST',])
def createApp_user(request):

    if request.method == 'POST':
        serializer = AppSignUpSerializer(data=request.data)
        data = 
        if serializer.is_valid():
            user=serializer.save()
            data['response']= 'Successfully registered new user.'
            data['email'] = user.email
            data['username'] = user.username
        # else:
            # data = serializer.errors
        return Response(data)

Serializers.py

class AppSignUpSerializer(serializers.ModelSerializer):

    class Meta:
        model = User

        extra_kwargs = 'password': 'password': True
        fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name')

    email = serializers.EmailField(
            required=True,
            validators=[UniqueValidator(queryset=User.objects.all())]
            )
    username = serializers.CharField(
            max_length=32,
            validators=[UniqueValidator(queryset=User.objects.all())]
            )
    password = serializers.CharField(min_length=6, max_length=100,
            write_only=True)

    def save(self):
        user = User(
        first_name=self.validated_data['first_name'],
        last_name=self.validated_data['last_name'],
        email=self.validated_data['email'],
        username=self.validated_data['username']

        )
        password = self.validated_data['password']

        user.set_password(password)
        user.save()
        return user

【问题讨论】:

【参考方案1】:

这是因为您的全局 DRF 设置也应用于 createApp_user 视图。 您需要做的是,通过相应的装饰器为您的视图提供空的permission_classesauthentication_classes 设置,如下所示

from rest_framework.decorators import api_view, authentication_classes, permission_classes


@api_view(['POST', ])
@authentication_classes(())
@permission_classes(())
def createApp_user(request):
    ...
    # your rest of the code

【讨论】:

以上是关于"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 时出现此错误