python - Django Rest Framework 中的 JWT 和自定义身份验证
问题描述
我编写了一个非常基本的自定义身份验证类,以便为我的自定义身份验证需求实现简单的 JWT 库。
我手动生成令牌,然后将访问令牌发送到我的 API。默认情况下,这就足够了,但由于我不使用默认的 Django 用户模型,我得到“找不到用户”。这是因为我需要实现自定义身份验证后端。
我需要读取该令牌以使用给定的用户 ID 查询数据库并检查该令牌是否也有效。在我的示例中,我有固定的数字 2。
class ExampleAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
try:
user = vAuthUser.objects.get(pk=2) #this should receive the user_id from the token
except:
raise AuthenticationFailed('No such user')
return (user, None)
我的 API 看起来像:
class MyAPI(APIView):
authentication_classes = (ExampleAuthentication,)
permission_classes = (IsAuthenticated ,)
def get()...
解决方案
试试这个:
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth.models import User
user = User.objects.first()
refresh = RefreshToken.for_user(user)
raw_token = str(refresh.access_token)
jwt_a = JWTAuthentication()
validated_token = jwt_a.get_validated_token(raw_token)
repr(validated_token)
print(validated_token["user_id"])
在这里,我将原始访问令牌提供给get_validated_token()
JWTAuthentication 类的方法。它返回一个包含以下键的字典:token_type
, jti
, user_id
, exp
, 以及它们的关联值。
我为我的示例使用了默认的 Django 用户模型,但它应该适用于您的自定义模型。
还有更多有用的方法,例如get_header()
. 检查这个文件和这个文件。
推荐阅读
- python - pandas ValueError:只能比较标签相同的系列对象python
- android - 由于 recyclerview 和 cursorloader 导致的空白主要活动
- bootstrap-4 - 如何在行之间垂直间隔
- python - 对嵌套表使用scrapy
- angular - 对象上确实存在属性目标
- javascript - IE8 正则表达式错误应为“/”
- python - 在 Windows 的 Python 3.6 中安装 mysqlclient
- python - Django form.errors 未显示在模板中
- javascript - Golang html模板无法在html文件中调用javascript文件
- android - 具有虹膜和面部识别功能的生物识别技术