我能够使用 SimpleJWT 获取访问和刷新令牌。我有一个自定义装饰器,它试图从用户配置文件中识别用户类型。代码在这里失败,因为它找不到经过身份验证的用户。
我曾多次尝试通过 VS Code 中的调试模式获取用户,但没有成功。
这是我的settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken', # Add this line
'rest_auth', # Add this line
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount', # we will not be using this but not keeping this entry results in error while deleting user. A known issue https://github.com/Tivix/django-rest-auth/issues/412
'crispy_forms',
'users',
]
MIDDLEWARE = [
'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',
]
AUTH_USER_MODEL = 'users.User'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
#'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
REST_USE_JWT = True
'''
#https://www.techiediaries.com/django-rest-framework-jwt-tutorial/
JWT_AUTH = {
'JWT_ALLOW_REFRESH': True,
'JWT_RESPONSE_PAYLOAD_HANDLER': 'custom_jwt.jwt_response_payload_handler',
# 'JWT_PAYLOAD_HANDLER': 'custom_jwt.jwt_payload_handler',
# 'JWT_AUTH_HEADER_PREFIX': 'Bearer',
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300)
}
'''
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': True,
'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'VERIFYING_KEY': None,
'AUTH_HEADER_TYPES': ('Bearer',),
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
SITE_ID = 1
这是用户模型
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
class User(AbstractUser):
username = models.CharField(max_length=100,blank=True, null=True)
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name']
def __str__(self):
return "{}".format(self.email)
class UserProfile(models.Model):
USER_TYPE_CHOICES = (
(1, 'ADM'),
(2, 'GEM'),
(3, 'JET'),
(4, 'CAT'),
(5, 'SPR'),
)
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile')
title = models.CharField(max_length=5)
dob = models.DateField()
address = models.CharField(max_length=255)
country = models.CharField(max_length=50)
city = models.CharField(max_length=50)
zip = models.CharField(max_length=5)
photo = models.ImageField(upload_to='uploads', blank=True)
user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES,default=1,unique=False)
这是我要访问的视图
@method_decorator(user_is_ADM,name='dispatch')
class HelloView(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request):
content = {'message': 'Hello, World!'}
return Response(content)
这是令人不安的自定义装饰器
def user_is_ADM(fun_c):
@wraps(fun_c)
def wrapped(request, *args, **kwargs):
if request.user.profile.user_type == 1: <---throws error here
return fun_c(request, *args, **kwargs)
else:
raise PermissionDenied
return wrapped
我可以使用http://127.0.0.1:8000/api/token/从 simplejwt 获取访问/刷新令牌对,并提供用户名和密码。但是当我尝试使用带有 accesstoken 的http://127.0.0.1:8000/core/hello/(核心是应用程序名称)访问 HelloView 时(当然,使用 Authorisation: Bearer......),装饰器进来了图片。现在这个装饰器需要 request.user 来验证用户是否是'GEM'。问题是没有用户登录,因此系统给了我“匿名”用户没有属性“个人资料”的错误。即使,我作为先决条件登录,也会面临同样的错误。我是 Django 的新手。
如何解决?任何替代建议?