【问题标题】:Django REST Custom (token) authenticationDjango REST 自定义(令牌)身份验证
【发布时间】:2021-04-06 11:59:17
【问题描述】:

因为我把事情搞混了,只是让自己更加困惑,也许有人可以真正指导我。

我需要制作一个需要登录的 Django REST API。但是,用户表已经存在于 Postgres 数据库中。我认为基于令牌的身份验证最合适,但是,这些令牌还不存在。 (登录一次以检索/创建令牌,检查每个请求的令牌)

  1. 如何使用 POST 请求提交登录详细信息,纯粹用于验证用户?
  2. 成功登录后如何生成令牌,是否应将其存储在新的令牌表中?
  3. 在此之后,如何使用令牌为 API 数据请求提供身份验证/授权?

我能找到的所有示例都使用默认的 Django 用户模型,或者没有详细说明,在这种情况下我无法使用。 我制作了一个自定义身份验证器来检查用户名和密码,但是我无法完成接下来的步骤。

from api.models import LogonAccount
from rest_framework import authentication
from rest_framework import exceptions
import bcrypt

class ExampleAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):

        username = request.data.get('username') # get the username request header
        password = request.data.get('password') # get the password request header
        if not username or not password: # no username or password passed in request headers
            return None # authentication did not succeed
        try:
            user = LogonAccount.objects.get(username=username)

            if bcrypt.hashpw(password.encode(), user.password.encode()):
                print("succes")
                return (user, None) # authentication successful
        except LogonAccount.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user')

【问题讨论】:

    标签: python django rest django-rest-framework


    【解决方案1】:

    不要混淆,您只是尝试使用 DRF 实现基于令牌的身份验证。 DRF 已经带有此功能。本文将引导您完成 https://simpleisbetterthancomplex.com/tutorial/2018/11/22/how-to-implement-token-authentication-using-django-rest-framework.html

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-07
    • 2018-07-10
    • 2023-03-16
    • 2015-12-26
    • 2015-11-12
    • 1970-01-01
    • 2019-02-27
    • 2011-03-18
    相关资源
    最近更新 更多