如何将用户从 django rest 框架中的中间件重定向到登录页面?

How to redirect user to login page from middleware in django rest framework?

我正在与 django rest framework 一起构建我的 api,并且在前端我正在使用 Angular framework

我开发了一个拦截每个请求的自定义 middleware。我想在不满足条件时注销用户。

class MyCustomMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if not request.user.is_authenticated():
            #user is not allowed to do this request 
             #logout the user

我知道从backend我无法将用户重定向到登录页面,这是一个front end工作人员,但我想向前端发送通知或其他内容以告诉它应该将用户重定向到登录页面。

我试过提高 PermissionErrorHTTP_403_FORBIDDEN 但其中 none 成功了。

我想在请求的 header 中添加一些东西 (attribute/parameter) 以便在前端拦截器中测试 attribute/parameter 是否存在,但我做不到想办法。

我也尝试将请求的用户设置为 None : request.user=None 但也失败了。

有人能告诉我这是否可能吗?

如果可以,我该如何实现?

非常感谢。

我找到了 :D

from django.http.response import HttpResponseForbidden


class MyCustomMiddleware(MiddlewareMixin):
   def process_request(self, request):
      if not request.user.is_authenticated():
         #user is not allowed to do this request 
         return HttpResponseForbidden()

它只是引发一个 403 error 并且从前端我读取了错误的状态代码,如果它 403 然后将用户重定向到登录页面。

希望对以后的人有所帮助。