栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

RESTful API的令牌身份验证:令牌是否应该定期更改?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

RESTful API的令牌身份验证:令牌是否应该定期更改?

最好让移动客户端定期更新其身份验证令牌。这当然要由服务器来实施。

默认的TokenAuthentication类不支持此功能,但是你可以对其进行扩展以实现此功能。

例如:

from rest_framework.authentication import TokenAuthentication, get_authorization_headerfrom rest_framework.exceptions import AuthenticationFailedclass 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框架登录视图,以便在登录完成后刷新令牌:

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()

并且不要忘记修改网址:

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/415065.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号