问题描述
我正在使用 Tastypie 创建基于 Django 1.4.3 的 API.我使用 ApiKey 来验证用户.默认 ApiKey 不能过期.但是在 apikey 表中有带有日期时间的列 created
.即使我将其更改为 2010
年份,密钥仍然有效.
I am creating API based on Django 1.4.3 with Tastypie. I use ApiKey to authenticate users. As default ApiKey cannot be expired. But there is column created
with datetime in apikey table. Even when I change it to 2010
year, the key is still valid.
我的问题是如何以最简单的方式使 created
列有用并禁止访问超过 24 小时的密钥,这是否有意义?
My question is how can I make the column created
useful and forbid access for keys older than let say 24 hours, in easiest way and does it make sense?
目前我不知道如何才能实现这一目标.
At the moment I have no idea how I could even try to achieve that.
我不期望现成的解决方案.一些有用的提示.
I don't expect ready solution. Some useful hints.
推荐答案
我通过覆盖 ApiKeyAuthentication 中的方法 get_key
找到了解决方案.
I found solution by overriding method get_key
in ApiKeyAuthentication.
class MyApiKeyAuthentication(ApiKeyAuthentication):
def get_key(self, user, api_key):
"""
Attempts to find the API key for the user. Uses ``ApiKey`` by default
but can be overridden.
"""
from tastypie.models import ApiKey
try:
api_key = ApiKey.objects.get(user=user, key=api_key)
current_time = datetime.utcnow()
current_time = current_time.replace(tzinfo=pytz.utc)
week = timedelta(7)
if not (current_time - api_key.created) < week:
api_key.delete()
return self._unauthorized()
else:
api_key.created = current_time
api_key.save()
except ApiKey.DoesNotExist:
return self._unauthorized()
return True
这篇关于Tastypie 自动注销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!