首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Django-rest框架api将SessionAuthentication添加为可选的

Django-rest框架api将SessionAuthentication添加为可选的
EN

Stack Overflow用户
提问于 2019-09-25 03:21:29
回答 1查看 377关注 0票数 0

嗨,我现在有我的api,它使用这个简单JWT包进行jwt令牌身份验证,效果很好。但是现在,当我试图使用Ajax从django网站应用程序调用api时,这个应用程序来自一个已经登录的页面用户,但它仍然要求我使用jwt access_token。

我来自页面用户的ajax调用已经登录:

代码语言:javascript
运行
复制
$.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中,如下所示:

代码语言:javascript
运行
复制
@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:

代码语言:javascript
运行
复制
$.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 (禁止)

我的设置:

代码语言:javascript
运行
复制
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调用来自已经登录的页面用户。

谢谢你的阅读!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-25 03:32:23

因为在ajax请求中添加了Authentication头,如果请求头上存在TokenAuthentication,Django会自动使用Authentication。删除它以使用SessionAuthentication。

当您切换到使用SessionAuthentication时,可能会出现一个问题,就是如果没有CSRF令牌,那么Django将拒绝您的CSRF请求,更详细的这里

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58090713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档