简体   繁体   English

使用用户名和密码登录时未提供身份验证凭据

[英]Authentication credentials were not provided on login with username and password

I have a such misunderstanding with my django我对我的 django 有这样的误解

I make a login from DJANGO built in view for testing, lofin is successful我从 DJANGO 登录进行测试,lofin 成功

DJANGO 内置视图

But from postman or any other place i get an ERROR Authentication credentials were not provided但是从 postman 或任何其他地方我得到一个错误未提供身份验证凭据

邮递员登录

CAN ANYBODY PLEASE EXPLAIN WHAT IS WRONG!!!任何人都可以解释什么是错的!

If i did not provide full explanation, please inform me, and i will add如果我没有提供完整的解释,请告诉我,我会补充

This is settings.py这是settings.py

    DEBUG = True

ALLOWED_HOSTS = ['127.0.0.1', 'localhost']


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "tsundoku",
    'rest_framework',
    'rest_framework.authtoken',
    '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",
]

CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
]

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.1/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/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.1/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.1/howto/static-files/

STATIC_URL = '/static/'
# MEDIA_URL this is for displaying image in browser ex. http://localhost:8000/images/d14f96e4b0e94973b151ea8097e28c01.jpg
MEDIA_URL = '/images/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)
# MEDIA_ROOT this is the directory where the images will be saved
MEDIA_ROOT = os.path.join(
    BASE_DIR, f'tsundoku/static/images/')
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static/")


REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # 'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
        # 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
    'DEFAUlt_filter_classes': (
        'django_filters.rest_framework.DjangoFilterBackend',
    ),
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework.parsers.JSONParser',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

Ptoject usrl.py ptoject usrl.py

    from django.contrib import admin
from django.conf import settings
from django.urls import path, include
from django.conf.urls.static import static
from rest_framework.routers import DefaultRouter
from rest_framework_simplejwt import views as jwt_views

print('project -> urls.py initialised')

router = DefaultRouter()

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('tsundoku.urls')),
    path('api/token/', jwt_views.TokenObtainPairView.as_view(),
         name='token_obtain_pair'),
    path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(),
         name='token_refresh'),

]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

App urls.py应用程序 urls.py

    from django.urls import include, path, re_path
from rest_framework import routers
from rest_framework.authtoken.views import obtain_auth_token
from . import views
from rest_framework.urlpatterns import format_suffix_patterns
import django

print('tsundoku -> urls.py initialised')


# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    re_path(r'^books/$', views.BooksList.as_view(), name='all-books'),
    re_path(r'^books/?(?P<active>[0-1])/$',
            views.BooksList.as_view(), name='all-active-books'),
    path('book/<int:pk>/',
         views.books_details, name='single-book'),
    path('userbook/', views.userbook_list, name='userbook'),
    path('banner/', views.banners, name='banner'),
    # re_path(
    # r'login/(?P<username>[^[^-\.][\w-\.]+@([\w-]+\.)+[\w-]{2,4}])/(?P<password>[.]{1,})$', views.Login, name='Login'),
    path('register/', views.RegisterView.as_view(), name='register'),
    path('login/', views.LoginView.as_view(), name='login'),

    path('hello/', views.TestAuth.as_view(), name='hello'),
    path('accounts/', include('django.contrib.auth.urls')),
    # To get a token by username and pwd
    path('api-token-auth/', obtain_auth_token, name='api-token-auth'),
]

urlpatterns = format_suffix_patterns(urlpatterns)

Serializer串行器

class LoginSerializer(serializers.Serializer):
    print('serializers.py -> LoginSerializer')

    email = serializers.CharField(max_length=50)
    password = serializers.CharField(max_length=255)

    def printa(self, data):
        print('login')

View看法

class LoginView(APIView):
    print('login_register-view.py -> Login')

    def post(self, request, *args, **kwargs):
        print(request)
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid():
            """
            User may login with mail and username, 
            so first we check it and throw error if not user found in DB
            """
            username = serializer.data['email']
            if '@' in serializer.data['email']:
                try:
                    username = User.objects.get(
                        email__exact=serializer.data['email']).username
                except User.DoesNotExist:
                    username = None
            password = serializer.data['password']
            print('username', username)
            user = authenticate(
                username=username, password=password)
            print('active user: ', user)
            if user is not None:
                if not User.is_active:
                    print('user is not active')
                login(request, user)
                token, created = Token.objects.get_or_create(user=user)
                response = {'result': [{
                    'username': username,
                    'token': token.key}],
                    'success': True
                }
                return Response(response, status=status.HTTP_201_CREATED)
            err_response = {'result':
                            [{'error': 'You see this error because you entered invalid credentials or user with this credentials is not active'}],
                            'success': False
                            }
            return Response(err_response, status=status.HTTP_401_UNAUTHORIZED)
        return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED)

Solved by adding permission classes通过添加权限类解决

class LoginView(APIView):
    print('login_register-view.py -> Login')

    permission_classes = ()

.......

Based on this answer基于这个答案

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

相关问题 详细信息:未提供身份验证凭据 - details:Authentication credentials were not provided 获取:未提供身份验证凭据 - Fetch : authentication credentials were not provided Django:未提供身份验证凭据 - Django: Authentication credentials were not provided DRF:“详细信息”:“未提供身份验证凭据。” - DRF: “detail”: “Authentication credentials were not provided.” Django:“详细信息”:“未提供身份验证凭据。” - Django : “detail”: “Authentication credentials were not provided.” Django Rest 框架 - 未提供身份验证凭据 - Django Rest Framework - Authentication credentials were not provided PlotlyRequestError:未提供身份验证凭据 python - PlotlyRequestError: Authentication credentials were not provided python 为什么我无法使用此 django 登录代码登录,消息显示:“未提供身份验证凭据” - Why I can't log in with this django login code, the message says: "Authentication credentials were not provided" Django OAuth Toolkit为我提供了“未提供身份验证凭据”错误 - Django OAuth Toolkit giving me “Authentication credentials were not provided” error Django OAuth 工具包 - 自省请求:“未提供身份验证凭据。” - Django OAuth Toolkit - Introspection Request: “Authentication credentials were not provided.”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM