我该如何更改使用
django
的 allauth
应用程序,以便在提供无效登录凭据时返回 401 响应?
我尝试将自定义逻辑放入自定义
ModelBackend
中,但发现无法实际修改那里的响应状态代码。
我还尝试将自定义逻辑放入
CustomAccountAdapter.authentication_failed
中,但同样的问题我发现无法更改状态代码。
我最后通过添加以下中间件成功更改了http状态代码
class Auth401Middleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
if request.path == "/accounts/login/" and request.method == "POST" and not request.user.is_authenticated:
response.status_code = 401
return response