0

我正在使用 Django REST Framework 提供的 TokenAuthentication 并遵循这篇文章https://simpleisbetterthancomplex.com/tutorial/2018/11/22/how-to-implement-token-authentication-using-django-rest-framework.html

在标头中发送令牌时,我没有指定为其生成令牌的用户,但它会自动选择正确的用户。我想知道这是如何工作的?

这是我正在拨打的电话(注意我只传递令牌而不是与令牌关联的用户名)

r = requests.post(url, headers={Authentication: 'Token my_token'}, data=data)

我正在使用传递特定用户名的 manage.py 命令创建令牌。

4

1 回答 1

0

那么为什么不只看实现TokenAuthentication呢?

如果您查看实现,您会发现以下authenticate方法。如我们所见,令牌与用户一起存储在数据库中。

authenticate方法只是检索并检查令牌,authenticate_credentials如果令牌存在,则实际检查表。

def authenticate(self, request):
    auth = get_authorization_header(request).split()

    if not auth or auth[0].lower() != self.keyword.lower().encode():
        return None

    if len(auth) == 1:
        msg = _('Invalid token header. No credentials provided.')
        raise exceptions.AuthenticationFailed(msg)
    elif len(auth) > 2:
        msg = _('Invalid token header. Token string should not contain spaces.')
        raise exceptions.AuthenticationFailed(msg)

    try:
        token = auth[1].decode()
    except UnicodeError:
        msg = _('Invalid token header. Token string should not contain invalid characters.')
        raise exceptions.AuthenticationFailed(msg)

    return self.authenticate_credentials(token)

def authenticate_credentials(self, key):
    model = self.get_model()
    try:
        token = model.objects.select_related('user').get(key=key)
    except model.DoesNotExist:
        raise exceptions.AuthenticationFailed(_('Invalid token.'))

    if not token.user.is_active:
        raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))

    return (token.user, token)
于 2019-10-23T15:21:55.877 回答