简体   繁体   English

如何在 django 令牌认证中检查用户是否登录?

[英]How to check if a user is logged in, in django token authentication?

Hi there I am currently starting a new rest api project with django.您好,我目前正在使用 django 开始一个新的 rest api 项目。 Normally when I start a new project I do a lot of planning and get a idea of how I want to build my app.通常,当我开始一个新项目时,我会做很多计划并了解我想如何构建我的应用程序。 For this app I want to use token authentication but can't find enough resources for this topic.对于这个应用程序,我想使用令牌身份验证,但找不到足够的资源用于这个主题。 Can anyone tell me these two things, how to check if a user is logged in/authenticated and how to check which user is logged in(of course with token authentication in django).谁能告诉我这两件事,如何检查用户是否已登录/已通过身份验证以及如何检查哪个用户已登录(当然在 django 中使用令牌身份验证)。 Thank you in advance.先感谢您。

Extra info(you don't need to read this):额外信息(您不需要阅读此内容):

The reason I want to use this kind of authentication is because I don't want to use the built in django models for my user model because my User model has to have some specific fields for this web app, obviously I can work my way around this but its not very efficient so I figured I'd use token authentication. The reason I want to use this kind of authentication is because I don't want to use the built in django models for my user model because my User model has to have some specific fields for this web app, obviously I can work my way around这但它不是很有效,所以我想我会使用令牌身份验证。

If you will use rest_framework.authtoken https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication you can set in each view to check whether the user is authenticated for admission or not.如果您将使用rest_framework.authtoken https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication您可以在每个视图中设置以检查用户是否通过了准入身份验证。 For example:例如:

class UserList(generics.ListAPIView):
    """List all users"""
    permission_classes = [IsAuthenticated] # allowed only by authenticated
    serializer_class = UserCreateSerializer
    queryset = CustomUser.objects.all()

To check which user is logged in, rest_framework.authtoken creates a table in the database that contains the token, the user and the time the token was created要检查哪个用户已登录, rest_framework.authtoken在数据库中创建一个表,其中包含令牌、用户和创建令牌的时间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM