【发布时间】:2021-04-06 11:59:17
【问题描述】:
因为我把事情搞混了,只是让自己更加困惑,也许有人可以真正指导我。
我需要制作一个需要登录的 Django REST API。但是,用户表已经存在于 Postgres 数据库中。我认为基于令牌的身份验证最合适,但是,这些令牌还不存在。 (登录一次以检索/创建令牌,检查每个请求的令牌)
- 如何使用 POST 请求提交登录详细信息,纯粹用于验证用户?
- 成功登录后如何生成令牌,是否应将其存储在新的令牌表中?
- 在此之后,如何使用令牌为 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