如何在基于类的视图中使用django REST JWT授权和身份验证

问题描述 投票:0回答:1

我正在使用JWT身份验证,我正在广泛使用这种类型的授权应用程序。

我正在尝试弄清如何在视图中使用它。

示例。假设我只允许用户在拥有正确权限的情况下创建批准的场所。我将在此视图中添加什么以访问用户?

我知道django具有request.user,但如何打开它?如果没有令牌传递到标头中,它是否始终打开并且request.user为null?还是中间件?我最终遇到的问题是,到此为止有很多信息,但是在视图上实际使用JWT的信息很少。

请帮助。

# for creating an approved venue add ons later
class CreateApprovedVenue(CreateAPIView):
    queryset = Venue.objects.all()
    serializer_class = VenueSerializer

Django rest framework jwt docshttps://jpadilla.github.io/django-rest-framework-jwt/

Django rest框架权限文档http://www.django-rest-framework.org/api-guide/permissions/

所以我发现了这个资源,现在正在研究它。https://code.tutsplus.com/tutorials/how-to-authenticate-with-jwt-in-django--cms-30460

此示例为前灯:

# users/views.py
class CreateUserAPIView(APIView):
    # Allow any user (authenticated or not) to access this url 
    permission_classes = (AllowAny,)

    def post(self, request):
        user = request.data
        serializer = UserSerializer(data=user)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
authentication permissions django-rest-framework authorization django-rest-framework-jwt
1个回答
0
投票

要使用JWT身份验证,您需要执行以下安装步骤:https://jpadilla.github.io/django-rest-framework-jwt/#installation

完成后,您可以通过简单地添加authentication_classes来包括auth,如下所示:>

# for creating an approved venue add ons later
class CreateApprovedVenue(CreateAPIView):
    authentication_classes = (JSONWebTokenAuthentication, )
    queryset = Venue.objects.all()
    serializer_class = VenueSerializer

并且在所有请求方法中,您都可以作为request.user获得用户。对于CreateAPIView,您可以执行以下操作:

def post(self, request, *args, **kwargs):
    user = request.user
    ...
© www.soinside.com 2019 - 2024. All rights reserved.