我使用 Django + Rest-Framework + jQuery 开发了一个 Web 应用程序,并希望有一个外部应用程序来消耗同样的 REST API,使用 JWT Tokens 进行身份验证。
我的当前配置如下。
settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
'DEFAULT_RENDERER_CLASS': [
'rest_framework.renderers.JSONRenderer',
]
}
SIMPLE_JWT = {
'AUTH_HEADER_TYPES': ('Bearer',),
}
views.py
class ListFileView(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request, *args, **kwargs):
user = request.user
if user:
obj = Foo.objects.filter(owner=user)
serializer = FooSerializer(obj, many=True)
data = serializer.data
return Response(data, status=status.HTTP_200_OK)
return Response({'detail': 'You have no access to files.'}, status=status.HTTP_400_BAD_REQUEST)
棘手的部分是当我使用以下语句时:
permission_classes = (IsAuthenticated,)
我可以使用有效的 JWT
令牌从外部应用程序执行 ajax
调用,但在应用程序内(已认证用户)使用 jQuery
调用时会失败并出现以下错误:
{"detail":"Authentication credentials were not provided."}
另一方面,如果我使用autentication_classes
而不是permission_classes
:
authentication_classes = (SessionAuthentication, BasicAuthentication)
我可以使用
jQuery
在Web应用程序中执行ajax调用,但是外部调用会出现相同的403
错误。我尝试使用以下两种方式:
class ListFileView(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
def get(self, request, *args, **kwargs):
...
但是外部调用也被拒绝了。
这两种Auth
是否可以在同一个class
视图中一起使用,还是应该将其分为两个端点?
编辑
来自应用程序内部使用jQuery
的示例调用:
<script type="text/javascript">
function loadTblDocs() {
$("#tbl-docs > tbody").empty();
$.ajaxSetup({
headers: { "X-CSRFToken": '{{csrf_token}}' }
});
$.ajax({
type: 'GET',
contentType: "application/json; charset=utf-8",
url: "/api/list/",
dataType: "json",
success: function (data) {
console.log(data);
}
});
};
</script>
同时,也可以通过VBA
代码的方式来进行外部操作:
Set web = CreateObject("WinHttp.WinHttpRequest.5.1")
web.Open "GET", "/api/list/", False
web.SetRequestHeader "Authorization", "Bearer <JWT_TOKEN_HERE>"
web.Send
jQuery
内部还是外部的@JPG? - drec4s