终于解决了!问题是permission
我正在使用。事实上,IsAuthenticated
权限检查request.user
这是None
当你使用时client credentials
授予。既然没有permission
用于支持clien credentials
DRF 中的补助金,您必须使用自己的DRF自定义权限 https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions。这就是我需要和使用的:
from rest_framework.permissions import BasePermission
class IsAuthenticatedOrClientCredentialPermission(BasePermission):
def has_permission(self, request, view):
if request.auth is None:
return False
grant_type = request.auth.application.get_authorization_grant_type_display()
if request.user is None:
if grant_type == 'Client credentials':
request.user = request.auth.application.user # <-- this is because I needed to get the user either the grant is 'password' or 'client credentials'
return True
else:
return False
else:
return True
但是您可能只想获得一个权限来检查授予类型是否为client credentials
并给予许可,如果是这样,这就是您所需要的:
from rest_framework.permissions import BasePermission
class ClientCredentialPermission(BasePermission):
def has_permission(self, request, view):
if request.auth is None:
return False
grant_type = request.auth.application.get_authorization_grant_type_display()
if request.user is None and grant_type == 'Client credentials':
return True
else:
return False
Note:如果您想使用第二个自定义权限,请注意request.user
is None
您可以通过以下方式获取客户端的所有者(正在向您发送请求)request.auth.application.user
.
使用(自定义)权限:
您可以通过将自定义权限添加到适当的视图来使用它们。 (就像使用任何 DRF 权限一样rest_framework.permissions
)
基于类的视图:
class ExampleView(APIView):
permission_classes = [ClientCredentialPermission] # <-- Add your permissions to this list
def get(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
基于功能的视图:
@api_view(['GET'])
@permission_classes([ClientCredentialPermission]) # <-- Add your permissions to this list
def example_view(request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)