【发布时间】:2018-06-21 04:16:10
【问题描述】:
我同时使用了 JWT 和会话身份验证中间件。
我发现我无法登录管理员。后来当我删除 JWT 中间件时,它起作用了。
我的网站将同时用作 api 登录和普通浏览器登录。如何同时使用它。
剩下的唯一选项是 jwt 的以下条件。
if request.content_type == 'application/json':
如何解决这个问题
我没有使用 DRF 创建 api 端点。这就是为什么我必须创建自定义中间件来验证 JWT 令牌
Django 设置:
MIDDLEWARE = (
'debug_toolbar.middleware.DebugToolbarMiddleware',
'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',
'webarticles.middleware.jwtWebtoken_mod.BaseJSONWebTokenAuthentication_mod',
)
webarticles.middleware.jwtWebtoken_mod.BaseJSONWebTokenAuthentication_mod
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework import exceptions
import json
from django.http import HttpResponse
from rest_framework.settings import api_settings as api_settings2
from rest_framework_jwt.settings import api_settings
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
jwt_get_username_from_payload = api_settings.JWT_PAYLOAD_GET_USERNAME_HANDLER
class BaseJSONWebTokenAuthentication_mod(JSONWebTokenAuthentication):
"""
Token based authentication using the JSON Web Token standard.
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
if request.content_type == 'application/json':
try:
user_auth_tuple = self.authenticate(request)
except exceptions.APIException as e:
self._not_authenticated(request)
hare = e.get_full_details()
#hare = {"e": str(e)}
# return HttpResponse(
# json.dumps(hare),
# content_type="application/json"
# )
return HttpResponse(
json.dumps(hare),
content_type="application/json",
status=e.status_code
)
if user_auth_tuple is not None:
request._authenticator = self
request.user, request.auth = user_auth_tuple
else:
self._not_authenticated(request)
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
def _not_authenticated(self,request):
"""
Set authenticator, user & authtoken representing an unauthenticated request.
Defaults are None, AnonymousUser & None.
"""
request._authenticator = None
if api_settings2.UNAUTHENTICATED_USER:
request.user = api_settings2.UNAUTHENTICATED_USER()
else:
request.user = None
if api_settings2.UNAUTHENTICATED_TOKEN:
request.auth = api_settings2.UNAUTHENTICATED_TOKEN()
else:
request.auth = None
目前我已将以下条件进行管理
if request.content_type == 'application/json':
【问题讨论】:
-
我希望你正在使用 Django REST 框架作为 API,显示你的 settings.py
标签: django