django rest framework加jwt认证,runserver调试使用token是ok的,挂到httpd下面就不行了

这是手工运行后端时的情况:

[root@astute astute-access]# python ./manage.py runserver 0.0.0.0:8000

╭─zhangwenjian@zhangwenjiandeMacBook-Pro ~
╰─$ curl -X POST -d "username=admin&password=astute-cloud" http://192.222.0.189:8000/api/token/get/                           2 ↵
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwib3JpZ19pYXQiOjE1MTQyOTQ5NTUsInVzZXJfaWQiOjEsImVtYWlsIjoiYUBhLmNvbSIsImV4cCI6MTUxNDI5NTU1NX0.PO1vSMNA2xMsf3CynezVLwsz2y3MS7CYw2IuhxDaHe4"}%                                               ╭─zhangwenjian@zhangwenjiandeMacBook-Pro ~
╰─$ curl -X GET --header "Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwib3JpZ19pYXQiOjE1MTQyOTQ5NTUsInVzZXJfaWQiOjEsImVtYWlsIjoiYUBhLmNvbSIsImV4cCI6MTUxNDI5NTU1NX0.PO1vSMNA2xMsf3CynezVLwsz2y3MS7CYw2IuhxDaHe4" http://192.222.0.189:8000/api/users
[{"id":1,"password":"pbkdf2_sha256$20000$ZLy1SMnqjzsH$bVVSxwk4e05P473aG0BtgPX4pN5e6SKy8GZ1FAS8EME=","last_login":"2017-12-26T13:29:15.837071Z","is_superuser":true,"username":"admin","first_name":"","last_name":"","email":"a@a.com","is_staff":true,"is_active":true,"date_joined":"2017-12-26T09:36:18.650172Z","telephone":"","mobile":"","department":"","position":"","description":"","extra":"","groups":[],"user_permissions":[]}]%                                                                                           

这是挂载到httpd之后的情况:

[root@astute astute-access]# systemctl restart httpd

╭─zhangwenjian@zhangwenjiandeMacBook-Pro ~
╰─$ curl -X POST -d "username=admin&password=astute-cloud" http://192.222.0.189/api/token/get/
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwib3JpZ19pYXQiOjE1MTQyOTUwMzAsInVzZXJfaWQiOjEsImVtYWlsIjoiYUBhLmNvbSIsImV4cCI6MTUxNDI5NTYzMH0.-bBNlyvcfen5BnGRtvI2Cwcqw6WsGoNBmI30fomv7fA"}%                                               ╭─zhangwenjian@zhangwenjiandeMacBook-Pro ~
╰─$ curl -X GET --header "Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwib3JpZ19pYXQiOjE1MTQyOTUwMzAsInVzZXJfaWQiOjEsImVtYWlsIjoiYUBhLmNvbSIsImV4cCI6MTUxNDI5NTYzMH0.-bBNlyvcfen5BnGRtvI2Cwcqw6WsGoNBmI30fomv7fA" http://192.222.0.189/api/users
{"detail":"Authentication credentials were not provided."}%

这是httpd配置文件:

[root@astute ~]# cat /etc/httpd/conf.d/astute-access.conf
<VirtualHost *:80>
    WSGIScriptAlias / /usr/share/astute-access/astute_access_api/wsgi.py
    alias /static/ /usr/share/astute-access/static/
    ServerName astute

    <Directory /usr/share/astute-access/astute_access_api/>
        Require all granted
    </Directory>

    <Directory /usr/share/astute-access/static>
        Require all granted
    </Directory>

    CustomLog "/var/log/httpd/astute-access.log" combined
    ErrorLog   /var/log/httpd/astute-access-error.log
    LogLevel warn
</VirtualHost>

这是settings:

"""
Django settings for astute_access_api project.

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

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,datetime

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


# 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 = 'v1*xin1-_-o(&ce(aochlrb!=&5p=l4-)qea*c3him0(nshyr('

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'django_filters',
    # 'rest_framework_word_filter',
    # 'generic_relations',
    'api',
    'api.users',
    'api.resource_pools',
    'api.desktop_pools',
    'api.desktops',
    'api.usb_rules',
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
        # 'rest_framework.permissions.AllowAny',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.BasicAuthentication',
    ),
    # 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    'DEFAULT_FILTER_BACKENDS': ('rest_framework_filters.backends.DjangoFilterBackend',
                                'rest_framework.filters.SearchFilter',),
    
    # 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    # 'PAGE_SIZE': 10
}

SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

AUTH_USER_MODEL = 'users.User'

JWT_AUTH = {
    # 'JWT_ENCODE_HANDLER':
    # 'rest_framework_jwt.utils.jwt_encode_handler',

    # 'JWT_DECODE_HANDLER':
    # 'rest_framework_jwt.utils.jwt_decode_handler',

    # 'JWT_PAYLOAD_HANDLER':
    # 'rest_framework_jwt.utils.jwt_payload_handler',

    # 'JWT_PAYLOAD_GET_USER_ID_HANDLER':
    # 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',

    # 'JWT_RESPONSE_PAYLOAD_HANDLER':
    # 'rest_framework_jwt.utils.jwt_response_payload_handler',

    # 'JWT_SECRET_KEY': settings.SECRET_KEY,
    # 'JWT_GET_USER_SECRET_KEY': None,
    # 'JWT_PUBLIC_KEY': None,
    # 'JWT_PRIVATE_KEY': None,
    # 'JWT_ALGORITHM': 'HS256',
    # 'JWT_VERIFY': True,
    # 'JWT_VERIFY_EXPIRATION': True,
    # 'JWT_LEEWAY': 0,
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=600),
    # 'JWT_AUDIENCE': None,
    # 'JWT_ISSUER': None,

    'JWT_ALLOW_REFRESH': True,
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
    # 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(seconds=60),

    'JWT_AUTH_HEADER_PREFIX': 'JWT',
    'JWT_AUTH_COOKIE': None,
}

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True


ROOT_URLCONF = 'astute_access_api.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # 'DIRS': [],
         'DIRS': ['/usr/share/astute-access/frontend'],
        '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 = 'astute_access_api.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }

   #  'default' : {
   #      'ENGINE': 'django.db.backends.mysql',
   #      'HOST': '127.0.0.1',
   #      'PORT': '3306',
   #      'NAME': 'astute_access',
   #      'USER': 'astute',       
   #      'PASSWORD': 'astutepass',
   # }
}

# sql:
# CREATE DATABASE IF NOT EXISTS astute_access;
# GRANT ALL PRIVILEGES ON astute_access.* to astute@'%' IDENTIFIED BY 'astutepass';
# FLUSH PRIVILEGES;
# SHOW GRANTS FOR 'astute';

# 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 = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'

# doc: http://python.usyiyi.cn/translate/django_182/topics/logging.html
LOGGING = {
    'version': 1,
    # When set to True this will disable all logging except
    # for loggers specified in this configuration dictionary. Note that
    # if nothing is specified here and disable_existing_loggers is True,
    # django.db.backends will still log unless it is disabled explicitly.
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(asctime)s %(process)d %(levelname)s %(name)s '
                      '%(message)s'
        },
        'normal': {
            'format': 'dashboard-%(name)s: %(levelname)s %(message)s'
        },
    },
    'handlers': {
        'null': {
            'class': 'logging.NullHandler',
        },
        'console': {
            # Set the level to "DEBUG" for verbose output logging.
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': '/var/log/astute_access_api/astute_access_api.log',
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'api': {
            'handlers': ['console'],
            # 'handlers': ['file'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
            'propagate': False,
        },
    }
}

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

STATICFILES_DIRS = (
    # ("js", os.path.join(STATIC_ROOT,'js')),
    # ("css", os.path.join(STATIC_ROOT,'css')),
    # ("images", os.path.join(STATIC_ROOT,'images')),
    # ("fonts", os.path.join(STATIC_ROOT,'fonts')),
    "/usr/share/astute-access/frontend/static",
)
阅读 3k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏