我编写了一个非常基本的自定义身份验证类,以实现简单的JWT库来满足我的自定义身份验证需求
然后将访问令牌发送到我的API。默认情况下,这就足够了,但是因为我没有使用默认的Django用户模型,所以我得到了“user not found”。这是因为我需要实现一个自定义的身份验证后端
我需要读取该令牌,以便使用给定的用户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()...
试试这个:
这里,我向JWTAuthentication类的
get_validated_token()
方法提供一个原始访问令牌。它返回一个包含以下键的字典:token_type
,jti
,user_id
,exp
,以及它们的相关值。我在示例中使用了默认的Django用户模型,但它应该与您的自定义模型一起使用。
还有更有用的方法,如
get_header()
。也选中this document和this one相关问题 更多 >
编程相关推荐