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

pkln4tw6  于 2023-11-20  发布在  Go
关注(0)|答案(6)|浏览(174)

我有一个来自Django REST Framework的TokenAuthentication的令牌字符串。
我需要得到相应的用户对象。我该怎么做呢?

uklbhaso

uklbhaso1#

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

字符串

i1icjdpr

i1icjdpr2#

如果你直接从Token类调用user对象,如@aliva的解决方案所示,你将得到一个原始的部分Django User,只有数据库中的字段。如果你需要得到真实的user对象,例如它的计算属性,你可以这样做:

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)

字符串

aor9mmx1

aor9mmx13#

下面是**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,而不是Map到特定的Token

from rest_framework.authtoken.models import Token

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

更多信息请参见Authentication documents

yhived7q

yhived7q4#

一个更好的方法是简单地调用request.user,因为对Token的访问意味着一个经过身份验证的请求。DjangoRestFramework在成功的TokenAuthentication上提供对request.authrequest.user的访问。

wfveoks0

wfveoks05#

假设在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()]

字符串

zi8p0yeb

zi8p0yeb6#

为了简洁起见,您可以使用现有ModelViewSet的@action

class UserViewSet(viewsets.ModelViewSet):
    ...
    @action(
        detail=False,
        methods=["get"],
        url_path=r"current",
    )
    def current_user(self, request):
        return Response(
            UserSerializer(request.user, context={"request": request}).data
        )

字符串
然后GET它在:http://localhost:8000/yourapi/users/current/

相关问题