简体   繁体   English

Django - 让用户在每次 REST API 呼叫时登录身份验证检查

[英]Django - Have a user logged in authentication check on every REST API call

I have this code of 2 views in Django. You will notice that each REST API call has a verify_login() function call that ensures that the request contains a verified JWT token.我在 Django 中有 2 个视图的代码。您会注意到每个 REST API 调用都有一个 verify_login() function 调用,确保请求包含经过验证的 JWT 令牌。 I'm wondering if there's a better way to implement this so that I don't have to have these lines specifically in every REST endpoint我想知道是否有更好的方法来实现这一点,这样我就不必在每个 REST 端点中专门设置这些行

    verify_response = verify_login(request)
    if verify_response not None:
        return verify_response

I'm trying to follow the D.R.Y.我正在尝试遵循 D.R.Y。 (Do Not Repeat Yourself) principle of coding. (Do Not Repeat Yourself) 编码原则。 It'd be nice if there was a cleaner way to represent this.如果有一种更简洁的方式来表示这一点,那就太好了。 I thought about maybe creating a module extending APIView that automatically has this and then all my Views extend that, but runs into the issue of having to call super().API_REQUEST() and then having to do the same if-statement check to see if it's None or not.我考虑过可能创建一个扩展 APIView 的模块,它自动拥有这个,然后我所有的视图都扩展那个,但是遇到了必须调用 super().API_REQUEST() 然后必须执行相同的 if 语句检查才能看到的问题是否为 None。

class PostView(APIView):
    """
    View for Post object

    * requires token authentication
    """
    # Create post
    @swagger_auto_schema(
        request_body=PostSerializer,
        operation_description="Create a post object"
    )
    def post(self, request):
        verify_response = verify_login(request)
        if verify_response not None:
            return verify_response

        serializer = PostSerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    # get all posts
    @swagger_auto_schema(
        operation_description="Get all posts from the DB"
    )
    def get(self, request):
        verify_response = verify_login(request)
        if verify_response not None:
            return verify_response

        posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

You can use authentication classes alongside permission classes.您可以将身份验证类与权限类一起使用。 If you want the authentication check to happen for all the APIs of your application, put your classes in settings.REST_FRAMEWORK.如果您希望对应用程序的所有 API 进行身份验证检查,请将您的类放在 settings.REST_FRAMEWORK 中。 If you want it for specific APIView's, put them in permission_classes & authentication_classes class variables.如果你想要它用于特定的 APIView,请将它们放在 permission_classes & authentication_classes class 变量中。 Check out the doc for more details.查看文档以获取更多详细信息。

Example,例子,

class JWTAuthenticataion(BaseAuthentication):
    def authenticate(self, request):
        ...    # write your JWT implementation here


# settings.py:
REST_FRAMEWORK = {
    ...
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "path.to.JWTAuthentication",
    ),
    "DEFAULT_PERMISSION_CLASSES": (
        "rest_framework.permissions.IsAuthenticated",
    )
}

# or
# api.py
class YourAPIView(APIView):
    permission_classes = (IsAuthenticated, )
    authentication_classes = (JWTAuthentication, )

    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM