gpt4 book ai didi

django - RESTful API 的 token 身份验证 : should the token be periodically changed?

转载 作者:行者123 更新时间:2023-11-28 19:32:36 24 4
gpt4 key购买 nike

我正在使用 Django 和 django-rest-framework 构建一个 RESTful API .

作为身份验证机制,我们选择了“ token 身份验证”,并且我已经按照 Django-REST-Framework 的文档实现了它,问题是,应用程序是否应该定期更新/更改 token ,如果是,如何更新?是移动应用程序需要更新 token 还是应该由网络应用程序自主完成?

什么是最佳实践?

这里有人使用过 Django REST Framework 并且可以提出技术解决方案吗?

(最后一个问题优先级较低)

最佳答案

让移动客户端定期更新其身份验证 token 是一种很好的做法。这当然要由服务器执行。

默认的 TokenAuthentication 类不支持这个,但是你可以扩展它来实现这个功能。

例如:

from rest_framework.authentication import TokenAuthentication, get_authorization_header
from rest_framework.exceptions import AuthenticationFailed

class ExpiringTokenAuthentication(TokenAuthentication):
def authenticate_credentials(self, key):
try:
token = self.model.objects.get(key=key)
except self.model.DoesNotExist:
raise exceptions.AuthenticationFailed('Invalid token')

if not token.user.is_active:
raise exceptions.AuthenticationFailed('User inactive or deleted')

# This is required for the time comparison
utc_now = datetime.utcnow()
utc_now = utc_now.replace(tzinfo=pytz.utc)

if token.created < utc_now - timedelta(hours=24):
raise exceptions.AuthenticationFailed('Token has expired')

return token.user, token

还需要覆盖默认的 rest framework 登录 View ,以便在登录完成时刷新 token :

class ObtainExpiringAuthToken(ObtainAuthToken):
def post(self, request):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
token, created = Token.objects.get_or_create(user=serializer.validated_data['user'])

if not created:
# update the created time of the token to keep it valid
token.created = datetime.datetime.utcnow()
token.save()

return Response({'token': token.key})
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

obtain_expiring_auth_token = ObtainExpiringAuthToken.as_view()

并且不要忘记修改 url:

urlpatterns += patterns(
'',
url(r'^users/login/?$', '<path_to_file>.obtain_expiring_auth_token'),
)

关于django - RESTful API 的 token 身份验证 : should the token be periodically changed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14567586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com