嗨,我现在有我的api,它使用这个简单JWT包进行jwt令牌身份验证,效果很好。但是现在,当我试图使用Ajax从django网站应用程序调用api时,这个应用程序来自一个已经登录的页面用户,但它仍然要求我使用jwt access_token。
我来自页面用户的ajax调用已经登录:
$.ajax({
type: "POST",
url: "/api/add_favorite/" + property_id + "/",
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer {{ refresh_token }}');
},
success: function (data) {
if (data.code == 200) {
alert('added to favorite');
replace_part_1 = '<a id="mylink2" href="#" value="' + property_id +'"><i class="fas fa-heart fa-lg" style="color: red" title="Remove from favorite"></i></a>'
$("a[value='" + property_id + "']").replaceWith(replace_part_1);
}
}
});
现在,我不想使用授权来设置标题,因为在页面中,用户已经登录,所以会话已经设置好了。
因此,我尝试将Django会话身份验证添加到api中,如下所示:
@api_view(['POST'])
@authentication_classes([SessionAuthentication, JWTAuthentication])
@permission_classes([IsAuthenticated])
def add_favorite(request, property_id):
if request.method == 'POST':
try:
favorite_property = Property.objects.get(pk=property_id)
if request.user.is_authenticated:
login_user = request.user
if not login_user.properties.filter(pk=property_id).exists():
login_user.properties.add(favorite_property)
return JsonResponse({'code':'200','data': favorite_property.id}, status=200)
else:
return JsonResponse({'code':'404','errors': "Property already exists in favorite"}, status=404)
except Property.DoesNotExist:
return JsonResponse({'code':'404','errors': "Property not found"}, status=404)
删除标题后的Ajax:
$.ajax({
type: "POST",
url: "/api/add_favorite/" + property_id + "/",
},
success: function (data) {
if (data.code == 200) {
alert('added to favorite');
replace_part_1 = '<a id="mylink2" href="#" value="' + property_id +'"><i class="fas fa-heart fa-lg" style="color: red" title="Remove from favorite"></i></a>'
$("a[value='" + property_id + "']").replaceWith(replace_part_1);
}
}
});
现在,我从Ajax调用中删除了set头,得到403返回代码:
加载资源失败:服务器响应状态为403 (禁止)
我的设置:
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
# 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}
我不知道为什么会话身份验证不能工作,因为Ajax调用来自已经登录的页面用户。
谢谢你的阅读!
发布于 2019-09-25 03:32:23
因为在ajax请求中添加了Authentication
头,如果请求头上存在TokenAuthentication
,Django会自动使用Authentication
。删除它以使用SessionAuthentication。
当您切换到使用SessionAuthentication时,可能会出现一个问题,就是如果没有CSRF
令牌,那么Django将拒绝您的CSRF
请求,更详细的这里
https://stackoverflow.com/questions/58090713
复制相似问题