我正在使用rest_framework_simplejwt对我的用户进行身份验证,但是在某些视图中我需要忽略它,因为这些是公共视图。我想将令牌检查到视图流中。预期的行为是:
在公众视野中
实际上rest_framework_simplejwt检查令牌并401在令牌无效或过期时引发......
我尝试authentication_classes在 APIView 中像这样禁用:
class SpecificProductApi(APIView):
def get_authenticators(self):
if self.request.method == 'GET':
self.authentication_classes = []
return super(SpecificProductApi, self).get_authenticators()
Run Code Online (Sandbox Code Playgroud)
但是如果我在输入GET APIView方法之前禁用它,我不能这样做,if reques.user.is_authenticated:因为我禁用了令牌:(
是否存在启用进入 api http 方法并手动检查用户查看的方法?谢谢
django python-3.x django-rest-framework jwt-auth django-rest-framework-simplejwt
我正在使用DRF ( djangorestframework_simplejwt ) 建议的库,使用安装
pip install djangorestframework_simplejwt
Run Code Online (Sandbox Code Playgroud)
将其添加到settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
]
}
Run Code Online (Sandbox Code Playgroud)
从导入的视图创建两个端点
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
# JWT Token
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain'),
# get a new token before the old expires.
path('api/token/refresh/', TokenRefreshView.as_view, name='token_refresh'),
]
Run Code Online (Sandbox Code Playgroud)
在数据库中创建用户没有任何问题,并且密码正在被散列。
如果我访问http://localhost:8000/api/token/,然后得到以下视图
发布正确的用户及其密码,然后出现以下错误
[17/4/2020 12:06:51] “POST /api/token/ HTTP/1.1” 500 122221 内部服务器错误:/api/token/ Traceback(最近一次调用):文件“C:\Users\tiago \Desktop\letsgo\authenticationJwt\lib\site-packages\django\core\handlers\exception.py”,第 34 行,内部响应 = get_response(request) 文件“C:\Users\tiago\Desktop\letsgo\authenticationJwt\ lib\site-packages\django\core\handlers\base.py”,第 115 行,在 _get_response 响应 = self.process_exception_by_middleware(e, request) 文件“C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site -packages\django\core\handlers\base.py”,第 113 行,在 _get_response 响应 =wrapped_callback(request, …
python django jwt django-rest-framework django-rest-framework-simplejwt
我已经安装了djangorestframework-simplejwt软件包并尝试导入该模块urls.py,views.py但仍然无法正常工作。请指导我解决这个问题。
点值列表
Package Version
----------------------------- -------
asgiref 3.3.1
Django 3.1.4
djangorestframework 3.12.2
djangorestframework-simplejwt 4.6.0
pip 20.2.3
PyJWT 1.7.1
pytz 2020.4
setuptools 49.2.1
sqlparse 0.4.1
Run Code Online (Sandbox Code Playgroud)
设置.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Django_MedicalApp',
'rest_framework',
'rest_framework_simplejwt',]
REST_FRAMEWORK = {'DEFAULT_AUTHENTICATION_CLASSES':
['rest_framework_simplejwt.authentication.JWTAuthentication',],
'DEFAULT_PERMISSION_CLASSES':
('rest_framework.permissions.AllowAny','rest_framework.permissions.IsAuthenticatedOrReadOnly',)}
Run Code Online (Sandbox Code Playgroud)
urls.py
from rest_framework_simplejwt.views import TokenObtainPairView
router = routers.DefaultRouter()
router.register('Company',views.CompanyViewset,basename='Company')
urlpatterns = [
path('admin/', admin.site.urls),
path('api/',include(router.urls),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'))]
Run Code Online (Sandbox Code Playgroud)
视图.py
from rest_framework_simplejwt.authentication import JWTAuthentication
class CompanyViewset(viewsets.ViewSet):
authentication_classes = [JWTAuthentication]
Run Code Online (Sandbox Code Playgroud)
请帮助我解决此导入错误。
python django django-rest-framework django-rest-framework-jwt django-rest-framework-simplejwt
在 Django 中,我使用rest_framework_simplejwt 应用程序设置了 JWT 身份验证。
我相信访问令牌的默认超时为 1 天,即使在 settings.py 中明确将其配置为 1 天后,令牌在大约 10 分钟后就不再起作用,并且服务器返回 401 响应。
设置.py:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
}
SIMPLE_JWT = {
'TOKEN_LIFETIME': timedelta(days=1),
'TOKEN_REFRESH_LIFETIME': timedelta(days=7),
}
Run Code Online (Sandbox Code Playgroud)
我认为Django中的时间设置可能有问题,因此在settings.py中我放置了datetime.datetime.now()的打印,奇怪的是在startapp期间调用了两次,时差为2小时。不过,如果令牌生命周期应该是 1 天,它应该是有效的,所以我不确定问题是什么。
关于问题可能是什么的任何想法吗?预先非常感谢您。
python django jwt django-rest-framework django-rest-framework-simplejwt
我正在 django 中使用 simple-jwt 模块实现登录功能。这时候,只有通过邮箱认证的用户才能登录,这个条件句出现如下错误。
TypeError 'bool' 对象在 Django 中不可调用
我不知道为什么我不能引入 bool 类型变量。我该如何解决这个错误?这是我的代码。
视图.py
from .models import User
from .utils import Util
from .serializers import customRegisterSerializer, customLoginSerializer, customTokenRefreshSerializer, userProfileSerializer
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import GenericAPIView
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from django.urls import reverse
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
import jwt
class customSignUpView (GenericAPIView) :
serializer_class = customRegisterSerializer
def post (self, request) : …Run Code Online (Sandbox Code Playgroud) 我想在后端接收刷新令牌以将令牌列入黑名单。
当用户传递访问令牌request.header以调用 API 时,我正在获取访问令牌,是否有任何方法可以在用户未传递标头时获取刷新令牌。
django jwt django-rest-framework django-rest-framework-jwt django-rest-framework-simplejwt
我正在尝试向注册用户发送电子邮件验证链接,但我不断收到此错误,我不知道为什么,但每当我向此端点发送发布请求时,我总是收到此错误
Internal Server Error: /auth/register
Traceback (most recent call last):
File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
response …Run Code Online (Sandbox Code Playgroud) python django django-rest-framework django-rest-framework-jwt django-rest-framework-simplejwt
我将 DRF 与djangorestframework-simplejwt包一起使用。在我的settings.py中:
INSTALLED_APPS = [
...
'rest_framework',
...
]
...
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTTokenUserAuthentication',
),
}
SWAGGER_SETTINGS = {
'SECURITY_DEFINITIONS': {
'Bearer': {
'type': 'apiKey',
'name': 'Authorization',
'in': 'header',
'description': 'E.g. \'Bearer jwt.token.here\''
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的应用程序的views.py中:
...
class PublicCreateView(generics.CreateAPIView):
"""
Should be available for unauthenticated users
"""
serializer_class = PublicThingSerializer
def post(self, request, *args, **kwargs):
return Response("It works!", 200)
...
Run Code Online (Sandbox Code Playgroud)
然而由于某种原因,此视图返回401未经身份验证的用户的响应。我尝试了很多事情,我得到的最好的结果是注意到当我完全删除配置时REST_FRAMEWORK,settings.py …
django jwt django-rest-framework django-rest-framework-simplejwt
我正在使用 django_rest_passwordreset 在 Django Rest 框架上进行身份验证。
我按照他们官方文档上的教程进行操作并登录,注册效果很好。
登录返回访问和刷新令牌。我想做的还包括返回用户对象以及访问和刷新令牌。
我有一个定制模型
# auth/models.py
# Inherited from user
class MUser(AbstractUser, models.Model):
email = models.EmailField(unique=True)
role = models.CharField(max_length=40, default="student")
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'role']
Run Code Online (Sandbox Code Playgroud)
序列化器
# auth/serializers.py
class TokenObtainPairSerializer(TokenObtainSerializer):
@classmethod
def get_token(cls, user):
return RefreshToken.for_user(user)
def validate(self, attrs):
data = super().validate(attrs)
refresh = self.get_token(self.user)
data['refresh'] = str(refresh)
data['access'] = str(refresh.access_token)
if api_settings.UPDATE_LAST_LOGIN:
update_last_login(None, self.user)
return data
Run Code Online (Sandbox Code Playgroud)
我的看法
# auth/views.py
class TokenObtainPairView(TokenViewBase):
"""
Takes a set of user credentials and …Run Code Online (Sandbox Code Playgroud) authentication django django-rest-framework django-rest-framework-simplejwt