我们正在使用带有django-rest-framework-jwt的django-rest-framework进行身份验证,它除了在 ip:port/admin/ 的django管理页面以外的任何地方都可以使用 . 那仍然需要用户名和密码 .
ip:port/admin/
是否有设置或方法绕过它,以便它识别JWT?
是否始终要求 /admin/ 页面使用名称/密码?我认为内置令牌auth可以使用它 .
/admin/
jwt是settings.py文件中唯一的auth设置 . 会话身份验证不再存在 .
问题可能不在您使用的身份验证方法中 . 如果自定义 User 模型,则可能会发生 create_superuser 方法未将用户实例详细信息中的 is_active 标志更新为 True . 这种情况django身份验证后端(如果您使用 ModelBackend )可以识别该用户不活动且不允许进行身份验证 . 简单检查 - 只需查看您创建的超级用户的 is_active 字段的值 . 如果是 False ,请手动将其更新为 True ,然后尝试登录 . 如果是您遇到问题的原因,则需要覆盖UserManager类的 create_superuser 和 create_user 方法 .
User
create_superuser
is_active
True
ModelBackend
False
create_user
问题是Django不知道djangorestframework-jwt,而只知道djangorestframework本身 . 对我有用的解决方案是创建一个简单的中间件,利用djangorestframework-jwt的auth
在settings.py中:
MIDDLEWARE = [ # others 'myapp.middleware.jwt_auth_middleware', ]
然后在我的myapp / middleware.py中
from rest_framework_jwt.authentication import JSONWebTokenAuthentication from django.contrib.auth.models import AnonymousUser from rest_framework import exceptions def jwt_auth_middleware(get_response): """Sets the user object from a JWT header""" def middleware(request): try: authenticated = JSONWebTokenAuthentication().authenticate(request) if authenticated: request.user = authenticated[0] else: request.user = AnonymousUser except exceptions.AuthenticationFailed as err: print(err) request.user = AnonymousUser response = get_response(request) return response return middleware
Important Note: 这是一种天真的方法,你不应该在 生产环境 中运行所以我只启用这个中间件 if DEBUG . 如果在 生产环境 中运行,您可能应该像内置 django.contrib.auth 模块一样缓存并懒惰地评估用户 .
if DEBUG
django.contrib.auth
2 回答
问题可能不在您使用的身份验证方法中 . 如果自定义
User
模型,则可能会发生create_superuser
方法未将用户实例详细信息中的is_active
标志更新为True
. 这种情况django身份验证后端(如果您使用ModelBackend
)可以识别该用户不活动且不允许进行身份验证 . 简单检查 - 只需查看您创建的超级用户的is_active
字段的值 . 如果是False
,请手动将其更新为True
,然后尝试登录 . 如果是您遇到问题的原因,则需要覆盖UserManager类的create_superuser
和create_user
方法 .问题是Django不知道djangorestframework-jwt,而只知道djangorestframework本身 . 对我有用的解决方案是创建一个简单的中间件,利用djangorestframework-jwt的auth
在settings.py中:
然后在我的myapp / middleware.py中
Important Note: 这是一种天真的方法,你不应该在 生产环境 中运行所以我只启用这个中间件
if DEBUG
. 如果在 生产环境 中运行,您可能应该像内置django.contrib.auth
模块一样缓存并懒惰地评估用户 .