【问题标题】:Django + django-rest-framework-simplejwt protect viewDjango + django-rest-framework-simplejwt 保护视图
【发布时间】:2020-02-06 08:04:02
【问题描述】:

我刚刚在 Django 项目中安装了 django-rest-framework-simplejwt,如果我发送了无效的 Authentication Bearer <<token>> 标头,它会使用 401 代码阻止我的请求。这是预期的行为。问题是,如果我删除 Authentication 标头,我可以访问我的视图,因此它不受保护。

如果没有 Authentication 标头,如何保护视图返回 401?

查看代码如下:

class AuthTestView(views.APIView):
    http_method_names = ['get']

    def get(self, request):
        response_data = {
            'result': 'Restricted access test ok.',
        }
        return Response(data=response_data, status=status.HTTP_200_OK)

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    尝试:

    from rest_framework.permissions import IsAuthenticated
    class AuthTestView(views.APIView):
        http_method_names = ['get']
        permission_classes=[IsAuthenticated] 
        def get(self, request):
            response_data = {
                'result': 'Restricted access test ok.',
            }
            return Response(data=response_data
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-24
      • 2021-09-09
      • 2021-06-23
      • 1970-01-01
      • 1970-01-01
      • 2019-06-29
      • 1970-01-01
      • 2021-10-03
      相关资源
      最近更新 更多