从DRF中的令牌字符串中获取用户对象?

时间:2017-05-27 01:54:01

标签: python django authentication django-rest-framework http-token-authentication

我有来自Django REST Framework's TokenAuthentication的令牌字符串。

我需要获取相应的用户对象。我该怎么做呢?

5 个答案:

答案 0 :(得分:5)

from rest_framework.authtoken.models import Token
user = Token.objects.get(key='token string').user

答案 1 :(得分:3)

这里是 The default authorization token model

@python_2_unicode_compatible
class Token(models.Model):
    """
    The default authorization token model.
    """
    key = models.CharField(_("Key"), max_length=40, primary_key=True)
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL, related_name='auth_token',
        on_delete=models.CASCADE, verbose_name=_("User")
    )
    created = models.DateTimeField(_("Created"), auto_now_add=True)

    class Meta:
        # Work around for a bug in Django:
        # https://code.djangoproject.com/ticket/19422
        #
        # Also see corresponding ticket:
        # https://github.com/encode/django-rest-framework/issues/705
        abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS
        verbose_name = _("Token")
        verbose_name_plural = _("Tokens")

    def save(self, *args, **kwargs):
        if not self.key:
            self.key = self.generate_key()
        return super(Token, self).save(*args, **kwargs)

    def generate_key(self):
        return binascii.hexlify(os.urandom(20)).decode()

    def __str__(self):
        return self.key

如您所见,该模型与User模型具有 OneOnOne关系

因此,如果您想获得User,而不是映射到特定的Token

from rest_framework.authtoken.models import Token

try:
    Token.objects.get(key="token").user
except Token.DoesNotExist:
    pass

有关更多信息,请参见Authentication documents

答案 2 :(得分:1)

如果直接从Token类调用用户对象(如@aliva解决方案中所述),您将获得原始的部分Django用户,其中仅包含数据库中的字段。如果您需要获取真实的用户对象,请使用它的计算属性,您可以执行以下操作:

from rest_framework.authtoken.models import Token

user_id = Token.objects.get(key=request.auth.key).user_id
user = User.objects.get(id=user_id)

答案 3 :(得分:1)

假设你想在 Django Rest Framework 中获取 auth token 时获取 userid 和 username

更多信息可以从https://www.django-rest-framework.org/api-guide/authentication/#by-exposing-an-api-endpoint

# in views.py
from rest_framework.auth.models import Token
from rest_framework.auth.views import ObtainToken
from rest_framework.response import Response

class MyObtainToken(ObtainToken):
   """Return User Info along with token"""
   def post(self, request, *arg, **kwarg)
       serializer = self.serializer_class(request.data, context={'request':request})
       serializer.is_valid(raise_exception=True)
       user = serializer.valided_data['user']
       token, _ = Token.objects.get_or_create(user)
       return Response(
            {
                 'token': token.key,
                 'username': user.username,
                 'userid': user.pk
            })
# in urls.py
urlpatterns += [path(r'api/obtain_auth_token', MyObtainToken.as_view()]

答案 4 :(得分:0)

一种更好的使用方法是直接调用request.user,因为访问令牌意味着已验证请求。 DjangoRestFramework可以在成功的TokenAuthentication上访问request.authrequest.user