在Django 3.0.3中,使用rest_framework_jwt从简单API调用中获取用户对象,而不使用viewset
我想检索user对象,以便检查用户是否可以访问基于Django和rest\u framework\u jwt的rest WebServices web应用程序中的文件 我的web应用有以下设置:在Django 3.0.3中,使用rest_framework_jwt从简单API调用中获取用户对象,而不使用viewset,django,django-rest-framework,Django,Django Rest Framework,我想检索user对象,以便检查用户是否可以访问基于Django和rest\u framework\u jwt的rest WebServices web应用程序中的文件 我的web应用有以下设置: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
'DEFAULT_PAGINATION_CLASS':'swiftapp.custom_pagination.CustomPagination',
}
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
我定义的路由:
router = routers.DefaultRouter(trailing_slash=False)
#router.register(r'operation/<str:branch>/<str:filename>/', SwiftFileViewSet, basename='get_queryset') # This didn't work and I don't need a Viewset anyways
router.register(r'operations/(?P<start_date>\d{4}-\d{2}-\d{2})/(?P<end_date>\d{4}-\d{2}-\d{2})$', OperationViewSet, basename='get_queryset')
urlpatterns = [
path(r'api/', include(router.urls)),
path('api/operation/<str:branch>/<str:filename>/', get_operation, name='get_operation'),
]
但不是在这个简单的GET API控制器中:
def get_operation(request, section, filename):
authentication_classes = (authentication.JSONWebTokenAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
user = self.request.user # I cannot get the user object here
logger.warning("logged user", user)
with open("C:\\operations\\" + section + "\\" + filename + ".op", "r") as f:
file_content = f.read()
f.close()
enc = base64.b64encode(bytes(file_content, 'utf-8'))
return HttpResponse(enc)
用户自定义类:
class CustomUserManager(BaseUserManager):
def create_user(self, first_name, last_name, username, branch, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not branch:
raise ValueError('Users must have a branch')
user = self.model(
first_name=first_name,
last_name=last_name,
username=username,
branch=branch,
)
user.is_superuser = False
user.is_active = True
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, first_name, last_name, username, branch, password=None):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
first_name,
last_name,
username,
password=password,
branch=branch,
)
user.is_superuser = True
user.is_active = True
user.save(using=self._db)
return user
class CustomUser(AbstractBaseUser):
username = models.CharField(max_length=30, blank=True, null=True, unique=True)
first_name = models.CharField(max_length=30, blank=False, null=False, unique=False)
last_name = models.CharField(max_length=30, blank=False, null=False, unique=False)
branch = models.CharField(max_length=3, blank=True, null=True)
# is_staff = models.BooleanField(default=True, null=True)
is_active = models.BooleanField(default=True, null=False)
is_superuser = models.BooleanField(default=False, blank=False, null=False)
objects = CustomUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['first_name', 'last_name', 'branch']
class Meta:
db_table='auth_user'
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
def get_branch(self):
return self.branch
您的视图获取操作(…)与DRF不兼容。您必须使用decorator使其与DRF兼容。然后可以将类参数添加到装饰器中
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.response import Response
@api_view(http_method_names=["GET"], )
@authentication_classes((authentication.JSONWebTokenAuthentication,))
@permission_classes((permissions.IsAuthenticated,))
def get_operation(request, section, filename):
user = request.user
return Response({"user pk": user.pk})
从rest\u framework.decorators导入api\u视图、身份验证\u类、权限\u类
来自rest\u framework.response导入响应
@api_视图(http_方法_名称=[“获取”],)
@身份验证\类((authentication.JSONWebTokenAuthentication,))
@权限\u类((permissions.IsAuthenticated,))
def get_操作(请求、节、文件名):
user=request.user
返回响应({“user pk”:user.pk})
您的视图获取操作(…)
与DRF不兼容。您必须使用decorator使其与DRF兼容。然后可以将类参数添加到装饰器中
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.response import Response
@api_view(http_method_names=["GET"], )
@authentication_classes((authentication.JSONWebTokenAuthentication,))
@permission_classes((permissions.IsAuthenticated,))
def get_operation(request, section, filename):
user = request.user
return Response({"user pk": user.pk})
从rest\u framework.decorators导入api\u视图、身份验证\u类、权限\u类
来自rest\u framework.response导入响应
@api_视图(http_方法_名称=[“获取”],)
@身份验证\类((authentication.JSONWebTokenAuthentication,))
@权限\u类((permissions.IsAuthenticated,))
def get_操作(请求、节、文件名):
user=request.user
返回响应({“user pk”:user.pk})
Django调用了库
首先安装一个库,其中包含
pip3 install PyJWT
您可以定义一个函数,用您的密码检查JWT,并在视图函数中的任何响应之前调用该函数。例如:
import jwt
def jwt_authentication(token):
check = False
try:
request_jwt = jwt.decode(token, 'yoursecret', algorithms=['HS512'])
check = True
except:
check = False
return check
在views.py中:
@api_view(['POST'])
def obj_add(request):
if not 'Authorization' in request.headers:
return Response({'Authorization': 'token is required'}, status=status.HTTP_403_FORBIDDEN)
token = request.headers['Authorization']
authentication = jwt_authentication(token)
if not authentication:
return Response({'Authorization': 'token is not valid'}, status=status.HTTP_403_FORBIDDEN)
Django有一个名为
首先安装一个库,其中包含
pip3 install PyJWT
您可以定义一个函数,用您的密码检查JWT,并在视图函数中的任何响应之前调用该函数。例如:
import jwt
def jwt_authentication(token):
check = False
try:
request_jwt = jwt.decode(token, 'yoursecret', algorithms=['HS512'])
check = True
except:
check = False
return check
在views.py中:
@api_view(['POST'])
def obj_add(request):
if not 'Authorization' in request.headers:
return Response({'Authorization': 'token is required'}, status=status.HTTP_403_FORBIDDEN)
token = request.headers['Authorization']
authentication = jwt_authentication(token)
if not authentication:
return Response({'Authorization': 'token is not valid'}, status=status.HTTP_403_FORBIDDEN)
非常感谢你!它救了我!:谢谢你!它救了我!:D