从 DRF 中的令牌字符串获取用户对象?
Get user object from token string in DRF?
我有一个来自 Django REST Framework's TokenAuthentication 的标记字符串。
我需要获取对应的用户对象。我该怎么做?
from rest_framework.authtoken.models import Token
user = Token.objects.get(key='token string').user
这里是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 关系。
So if you want to get the User
than mapped to specific Token
:
from rest_framework.authtoken.models import Token
try:
Token.objects.get(key="token").user
except Token.DoesNotExist:
pass
有关详细信息,请参阅 Authentication documents
如果您直接从 Token
class 调用用户对象,如@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)
更好的使用方法是简单地调用 request.user
,因为访问令牌意味着经过身份验证的请求。 DjangoRestFramework 允许在成功的 TokenAuthentication 上访问 request.auth
和 request.user
。
假设您想在 Django Rest Framework 中获取身份验证令牌时获取用户 ID 和用户名
更多信息可以从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()]
我有一个来自 Django REST Framework's TokenAuthentication 的标记字符串。
我需要获取对应的用户对象。我该怎么做?
from rest_framework.authtoken.models import Token
user = Token.objects.get(key='token string').user
这里是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 关系。
So if you want to get the
User
than mapped to specificToken
:
from rest_framework.authtoken.models import Token
try:
Token.objects.get(key="token").user
except Token.DoesNotExist:
pass
有关详细信息,请参阅 Authentication documents
如果您直接从 Token
class 调用用户对象,如@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)
更好的使用方法是简单地调用 request.user
,因为访问令牌意味着经过身份验证的请求。 DjangoRestFramework 允许在成功的 TokenAuthentication 上访问 request.auth
和 request.user
。
假设您想在 Django Rest Framework 中获取身份验证令牌时获取用户 ID 和用户名
更多信息可以从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()]