使用Django REST框架的本地和mod_wsgi服务器之间的Django JWT身份验证行为不同

cer*_*erd 8 apache django mod-wsgi apache2.2 django-rest-framework

我试图确定为什么Authorization:使用本地开发服务器时使用标头的受保护资源的身份验证行为正常,而不是我部署的apache 2.2 w/mod_wsgi实现.

我正在使用django 1.8 django-rest-frameworkdjango-rest-framework-jwt基于JWT的身份验证的lib.apache服务器版本为2.2,带有mod_wsgi.这都是在ubuntu 12.04实例(python 2.7)上运行的.

在localhost上使用manage.py runserver的工作案例:

# manage.py runserver is running
curl -s -X POST \
  -d '{"username":"test@test.com", "password":}' \ 
  http://localhost:8000/portfolio/login

# Response as expected:
##> {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp..."}

# Using above token as $TOKEN_STR with JWT prefix for Auth header: 
curl -X GET -H "Content-Type: application/json" \ 
  -H "Authorization: $TOKEN_STR" \
  http://localhost:8000/portfolio 

# Response as expected
##> {"data":"[...]"}
Run Code Online (Sandbox Code Playgroud)

用apache2.2 mod_wsgi破案:

curl -s -X POST \
  -d '{"username":"test@test.com", "password":}' \ 
  http://myremote.com/django/portfolio/login

# Response as expected:
##> {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp..."}

# Using above token as $TOKEN_STR with JWT prefix for Auth header: 
curl -X GET -H "Content-Type: application/json" \ 
  -H "Authorization: $TOKEN_STR" \
  http://myremote.com/django/portfolio 

# Response behaves as authentication not even there w/403 or 401:
##> {"detail": "Authentication credentials were not provided."}
Run Code Online (Sandbox Code Playgroud)

Apache站点配置

 #### DJANGO APP ####
    LogLevel info
    WSGIDaemonProcess dev processes=2 threads=15
    WSGIProcessGroup dev

    WSGIScriptAlias /django /webapps/django/config/wsgi.py
    <Directory /webapps/django>
        Order allow,deny
        Allow from all
    </Directory>


    ###  DJANGO APP ####
Run Code Online (Sandbox Code Playgroud)

可能相关的配置

config.py

## Django rest frameowkr config
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',

    )
}

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': SECRET_KEY,
    'JWT_ALGORITHM': 'HS256',
    'JWT_AUTH_HEADER_PREFIX': 'JWT',
}
Run Code Online (Sandbox Code Playgroud)

Luk*_*ski 12

我遇到过类似的问题.我发现我在Apache配置文件中缺少下面的指令

WSGIPassAuthorization On
Run Code Online (Sandbox Code Playgroud)

  • 这正是它的本质. (3认同)