django - Django 服务器返回身份验证错误
问题描述
即使请求中包含 jwt 令牌,我部署在 Linux 服务器上的 Django 服务器也会返回 401 身份验证错误。
它在我的本地机器上运行良好,但是在我部署在服务器上并尝试从邮递员获取、发布请求后,它返回 401 身份验证错误。
我正在使用 Django Rest Framework、corsheader、JWT 令牌。
这是我的源代码。
设置.py
import os
from datetime import timedelta
from django.urls import reverse
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
ALLOWED_HOSTS = ['*']
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# SECURITY WARNING: don't run with debug turned on in production!
try:
from .secret_key import *
except ImportError:
pass
# Application definition
INSTALLED_APPS = [
'channels',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'djoser',
'users',
'invitations',
'dm',
'posts',
'corsheaders',
"rest_framework_serializer_field_permissions",
]
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 = '[アプリ名].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 = 'evers_backend.wsgi.application'
ASGI_APPLICATION = 'evers_backend.routing.application'
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
},
},
}
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
'DATE_INPUT_FORMATS': ['iso-8601', '%Y-%m-%dT%H:%M:%S.%fZ'],
}
SIMPLE_JWT = {
'AUTH_HEADER_TYPES': ('JWT',),
'ACCESS_TOKEN_LIFETIME': timedelta(weeks=200),
}
# 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 = 'ja-jp'
TIME_ZONE = 'Asia/Tokyo'
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/'
AUTH_USER_MODEL = 'users.User'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
视图.py
class MyProfileListView(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = serializers.UserProfileWithFriendsSerializer
permission_classes = (IsAuthenticated,)
def get_queryset(self):
return self.queryset.filter(email=self.request.user)
但是由于它在本地计算机上运行良好,因此代码可能没有任何问题。
我在 linode 服务器上所做的如下。
git克隆...
pip3 install -r requirements.txt,
python3 manage.py migrate,
python manage.py collectstatic
chown www-data mysite/
chown www-data mysite/db.sqlite3
我觉得我忘了做一些我必须做的事情才能发送身份验证头。
谢谢你
解决方案
推荐阅读
- python - 具有特定值的 Python 圆形数据框列(如果存在)
- javascript - 如何在单独的文件中隔离一些在反应组件中互连的功能
- vue.js - Vue动态组件覆盖
- python - torch.softmax 和 torch.sigmoid 在二进制情况下不等价
- oracle - 使用 FSAL 运行功能将 oracle 报告 12c 与运行的 oracle 表单 12c 集成
- node.js - 何从特定位置将文件上传到 node.js 中的 Amazon S3
- c - 我需要一种只接受大写字母的方法
- synchronization - 如何在 DirectX / Direct3D 12 中使用栅栏同步 CPU 和 GPU?
- php - 具有引用列名的多对多原则
- android - Cordova-res 未安装在 ionic cordova