简体   繁体   English

未在所有呼叫中提供身份验证凭据 Django

[英]Authentication credentials were not provided Django on All calls

I am quite new to django and i am trying to use Djoser for Authentication but i am getting "Authentication credentials were not provided" on every call.我对 django 很陌生,我正在尝试使用 Djoser 进行身份验证,但每次通话时我都会收到“未提供身份验证凭据” Following is my settings file.以下是我的设置文件。

"""
Django settings for django_dir project.

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

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

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

import os
import environ

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

ROOT_DIR = environ.Path(__file__) - 2
APPS_DIR = ROOT_DIR.path('my_apps')
MEDIA_ROOT = str(APPS_DIR('media'))
# https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/'

# APPS_DIR = os.path.join(BASE_DIR, 'my_apps'),
env = environ.Env()

# STATIC FILE CONFIGURATION
# ----------------------------------------------
STATIC_ROOT = str(ROOT_DIR('staticfiles'))

# STATIC_URL = '/static/'

STATICFILES_DIRS = (
    str(APPS_DIR.path('static')),
    #     str(ROOT_DIR.path('frontend')),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

TEMPLATES_DIR = os.path.join(BASE_DIR, 'my_apps/templates')

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'm!nh54$kig!!=in(fqny#grtd!e(_$jjrph-95g0_52xsdw*&c'

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    # django apps
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',  # new
    'allauth',  # new
    'allauth.account',  # new
    'allauth.socialaccount',

    'rest_auth',
    'rest_auth.registration',
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    # local apps
    'my_apps.users.apps.UsersConfig',
]

# CORS conf

CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
    'http://localhost:4200',
    'http://127.0.0.1:4200'
)

# djangorestframework CONFIGURATION
# ------------------------------------------------------------------------------
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 10,
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DATETIME_FORMAT': "%Y-%m-%d %H:%M:%S",
}

# myproject/settings.py
AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
)

SITE_ID = 1

# LOGIN_REDIRECT_URL = '/auth/login/'#'/auth-token/token/create/'


AUTH_USER_MODEL = 'users.User'

SESSION_COOKIE_AGE = 7200

REST_AUTH_SERIALIZERS = {
}

REST_AUTH_REGISTER_SERIALIZERS = {
    'REGISTER_SERIALIZER': 'my_apps.users.serializers.RegisterSerializer',
}

# LOGIN_REDIRECT_URL = 'users:redirect'
LOGIN_URL = 'account_login'

# djoser settings
DJOSER = {
    'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}',
    'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}',
    'ACTIVATION_URL': '#/activate/{uid}/{token}',
    'SEND_ACTIVATION_EMAIL': True,
    'SERIALIZERS': {
        'user_create': 'my_apps.users.serializers.RegisterSerializer',
        'user': 'my_apps.users.serializers.UserSerializer',
        'current_user': 'my_apps.users.serializers.UserSerializer'
    },
}

# Important default settings
ACCOUNT_EMAIL_VERIFICATION = 'none'
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = None

# EMAIL CONFIGURATION
# --------------------
# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'


# Production

DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',
                         default='changethis <info@changethis.org>')
SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)
ACCOUNT_EMAIL_SUBJECT_PREFIX = ''
'''
SERVER_EMAIL = 'mazharabbasazhar72@gmail.com'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'mazharabbasazhar72@gmail.com'   #'mazharabbasazhar72@gmail.com'# os.environ['SENDGRID_USER_NAME']
EMAIL_HOST_PASSWORD = 'change' #os.environ['SENDGRID_PASSWORD']
EMAIL_PORT = 587
EMAIL_USE_TLS = True
'''

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'


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 = 'covid.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'my_apps/templates')],
        'OPTIONS': {
            'loaders': [
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ],
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

AUTH_TEMPLATE_CONSTANTS = {
    'project_name': 'Gateway Platform',
    'support_email': 'support@gatewayplatform.com',
}

WSGI_APPLICATION = 'covid.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {}
# DEPLOYMENT_MODE = env('DEPLOYMENT_MODE')
DEPLOYMENT_MODE = 'local'
if DEPLOYMENT_MODE == 'local':
    DEBUG = True
    DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': 'mydatabase',
        }
    }
elif DEPLOYMENT_MODE == 'staging':
    DEBUG = False


# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)

STATIC_URL = '/static/'

That's because you aren't sending the token in your request (Authorization: Bearer+{{token}})那是因为您没有在请求中发送令牌(授权:Bearer+{{token}})

If you're trying to log in but you see that message it's because you put如果您尝试登录但看到该消息,那是因为您输入了

'DEFAULT_PERMISSION_CLASSES': [
    'rest_framework.permissions.IsAuthenticated',
]

In REST_FRAMEWORK so by default, all your endpoints are gonna check if the user is authenticated, you need to allow any in the login.在 REST_FRAMEWORK 中,默认情况下,您的所有端点都会检查用户是否已通过身份验证,您需要允许any登录。 You can see more information here.您可以在此处查看更多信息。Link关联

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM