[英]Django restful API - get user id with token
How to obtain User ID from Django API having authentication token? 如何从具有身份验证令牌的Django API获取用户ID? Basically, I want to send authentication token and get back User id.
基本上,我想发送身份验证令牌并找回用户ID。 I have tried this solution: How can I return user ID with token in Django?
我已经尝试过以下解决方案: 如何在Django中返回带有令牌的用户ID? but it is returning token with provided username and password, which is not what I want.
但是它将返回具有提供的用户名和密码的令牌,这不是我想要的。
#myapp/views.py
class UserIdViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
def get_queryset(self):
return User.objects.filter(id=self.request.user.id)
#myapp/urls.py
router.register(r'api/user-id', userviews.UserIdViewSet, base_name="UserId")
sort out the problem. 解决问题。 Basically created View set and sort this out against current user.
基本上创建了视图集,并针对当前用户进行了整理。
What type of authentication you use ? 您使用哪种身份验证?
If for example, you use TokenAuthentication from rest_framework, you can have a look how this class implements request authentication. 例如,如果您使用rest_framework中的TokenAuthentication,则可以查看此类如何实现请求身份验证。
You can find there methods authenticate
and authenticate_credentials
and I believe that there - you will find your answer how to get the user. 您可以在其中找到
authenticate
和authenticate_credentials
方法,我相信在那里-您将找到如何获得用户的答案。
In the perform_create method you can assign the user to your model 在perform_create方法中,您可以将用户分配给模型
class EmailViewSet(viewsets.ModelViewSet):
authentication_classes = (TokenAuthentication)
permission_classes = (IsAuthenticated,)
queryset = Email.objects.all()
serializer_class = EmailSerializer
def perform_create(self, serializer):
serializer.save(user=self.request.user)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.