如何在 Django-rest-auth 中验证请求?

How to authenticate request in Django-rest-auth?

我正在尝试将 django-rest-auth 包集成到我的网络应用程序中。到目前为止,我可以使用 django-rest-auth 包提供的 API 注册用户、发送密码重置电子邮件和登录。

现在,当我发送登录请求时,returns "token" 身份验证成功。

如何在进一步的请求中发送身份验证令牌?例如,我正在尝试使用 GET /rest-auth/user 获取用户,但它给我的响应是 Authentication credentials not provided。我尝试通过 HTTP 基本身份验证传递令牌(base64 编码令牌作为用户名并将密码保留为空)。我仍然无法工作。

有人知道我应该如何在请求中传递这个令牌吗?

如果您想使用 Token Authentication,您必须设置 Authorization HTTP header。来自文档:

For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example:

Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

在 ajax 调用中,您可以这样调用 header:

$.ajax({
    type: 'POST',
    url: url,
    beforeSend: function (request)
    {
       request.setRequestHeader("Authorization", "Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b");
    },
});

您需要在headers

发送token

$.ajax({
            type:"POST",
            beforeSend: function (request)
            {
                request.setRequestHeader("Authority", 'Bearer 33a95862173cc0565fe502eb062b2e7c67e23a3a');
            },

并在 Django 代码中使用

user = request.user
if user:
 return "User token verified"
elif :
 return "User token not verified"

在 django 中自动在 headers 中查找令牌并使用令牌获取用户数据。