简体   繁体   English

django rest 框架中未提供错误身份验证凭据

[英]getting error Authentication credentials were not provided in django rest framework

Hi Everyone i am creating login api in DRF and getting response also as i expected but i test token to other api then got error Authentication credentials were not provided, i don't know where i am going wrong please help me out.also custom user model can't possible to use because that model i have already used大家好,我在 DRF 中创建登录 api 并得到响应,但我测试到其他 api 的令牌然后得到错误未提供身份验证凭据,我不知道我哪里出错了,请帮助我。还有自定义用户无法使用模型,因为我已经使用过该模型

setting.py- this is setting file setting.py-这是设置文件

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'api.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework_simplejwt.authentication.JWTAuthentication'
    ),
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
        'rest_framework_datatables.renderers.DatatablesRenderer',
    ),
    'DEFAULT_FILTER_BACKENDS': (
        'rest_framework_datatables.filters.DatatablesFilterBackend',
    ),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework_datatables.pagination.DatatablesPageNumberPagination',
    'PAGE_SIZE': 100,
}

models.py模型.py

class GmsUser(GmsBaseModel):
    first_name=models.CharField(max_length=255,null=True, blank=True)
    middle_name=models.CharField(max_length=255,null=True, blank=True)
    last_name=models.CharField(max_length=255,null=True, blank=True)
    user_name=models.CharField(max_length=255,null=True, blank=True, unique=True)
    password=models.CharField(max_length=255,null=True, blank=True)
    token = models.CharField(max_length=255, null=True)

    class Meta:
        db_table = "gms_users"
    def __str__(self):
        return self.user_name

views.py视图.py

@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
def gms_user_login(request):
    user_name = request.data.get("user_name")
    password = request.data.get("password")
    users=GmsUser.objects.filter(user_name=user_name).values_list('id',flat=True)
    role=GmsRole.objects.filter(id=GmsUserRole.objects.filter(user=users[0]).values_list('role',flat=True)[0]).values_list('role',flat=True)[0]
    # city=GmsUserProfile.objects.filter(user=users[0]).values_list('city',flat=True)[0]
    try:
        query=GmsUserRole.objects.filter(user=users[0]).exists()
    except Exception as e:
        return Response({"message":"User not found","error":True,"code":400,"results":str(e)},status=HTTP_400_BAD_REQUEST)
    if user_name is None or password is None:
        return Response({'detail': 'Please provide both username and password'})
    else:
        try:
            if query:
                user = GmsUser.objects.get(user_name=user_name)
        except GmsUser.DoesNotExist:
            return Response({'detail': 'Invalid UserName'})
        if user.password.lower() != password.lower():
            return Response({'detail': 'Invalid Password'})
    user.token=get_random_string(length=50)
    user.save()
    response_data=GmsUserSignupSerializer(user).data
    response_data1=GmsRoleSerializer(GmsRole.objects.get(role=role)).data
    response_data2=GmsUserProfileSerializer(GmsUserProfile.objects.get(user=users[0])).data
    response_data['roles']=response_data1
    response_data['user_profile']=response_data2
    try:
        return JsonResponse({"message": "login","error":False,"code":200,"results":{'token':user.token,'user':response_data}},status=HTTP_200_OK)
    except Exception as e:
        return JsonResponse({"message": "login","error":True,"code":500,"results":str(e)},status=HTTP_200_OK)

Login api Response登录 api 响应

{
    "message": "login",
    "error": false,
    "code": 200,
    "results": {
        "token": "7R1EAR6qQdTyM6ZvD7kHfwdCHoj33tsp1QXUCIXSqU8929uMOq",
        "user": {
            "id": 4,
            "user_name": "edwin",
            "password": "1234"
            "roles": {
                "id": 1
            },
            "user_profile": {
                "id": 2
                "city": 1
            }
        }
    }
}

I think you need to set the right authentication class to be used in settings.py.我认为您需要设置要在 settings.py 中使用的正确authentication类。 Now there are 4 classes defined.现在定义了 4 个类。 But I think you have to set one class.但我认为你必须设置一个类。

If you select the rest_framework.authentication.TokenAuthentication , you don't need to create token with random string.如果选择rest_framework.authentication.TokenAuthentication ,则不需要使用随机字符串创建令牌。 The rest_framework.authtoken app will create Token model and you can just use that. rest_framework.authtoken应用程序将创建Token模型,您可以使用它。

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # 'api.authentication.TokenAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
        # 'rest_framework_simplejwt.authentication.JWTAuthentication'
    ),
    ...
}

暂无
暂无

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

相关问题 Django Rest 框架 - 未提供身份验证凭据 - Django Rest Framework - Authentication credentials were not provided Django Rest Framework JWT“未提供身份验证凭据。”} - Django Rest Framework JWT “Authentication credentials were not provided.”} Django Rest Framework {“detail”:“未提供身份验证凭据。”} - Django Rest Framework {“detail”:“Authentication credentials were not provided.”} Python 请求与 Django Rest 框架 - “详细信息”:“未提供身份验证凭据” - Python Requests with Django Rest Framework - 'detail': 'Authentication credentials were not provided' 如何在 Django rest 框架中自定义 [Authentication credentials were not provided] 错误消息 - How to customize [Authentication credentials were not provided] error message in Django rest framework Django-rest-framework {“详细信息”:“未提供身份验证凭据。” } 使用 django-rest-knox - Django-rest-framework {“detail”: “Authentication credentials were not provided.” } using django-rest-knox 自定义Django休息框架身份验证响应{“详细信息”:“未提供身份验证凭据。”} - Customize Django rest framework authentication response {“detail”: “Authentication credentials were not provided.”} Django:未提供身份验证凭据 - Django: Authentication credentials were not provided Django OAuth Toolkit为我提供了“未提供身份验证凭据”错误 - Django OAuth Toolkit giving me “Authentication credentials were not provided” error Django:“详细信息”:“未提供身份验证凭据。” - Django : “detail”: “Authentication credentials were not provided.”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM