【发布时间】:2017-03-26 02:04:11
【问题描述】:
我是 Django 世界的新手。
我已经为我的 REST API 实现了TokenAuthentication。
settings.py
'DEFAULT_AUTHENTICATION_CLASSES': (
'auth.authentication.TokenAuthentication',
),
authentication.py
class TokenAuthentication(RestTokenAuthentication):
model = RestAPIToken
def authenticate_credentials(self, key):
try:
token = self.model.objects.get(key=key)
except self.model.DoesNotExist:
if self.model.objects.has_expired(key):
raise SessionExpired()
raise exceptions.AuthenticationFailed(_('Invalid token.'))
# Django auth framework expects
# (user, auth) tuple. However, here we don't need user object.
# So, keeping it None
return None, token
views.py
class HistoryViewSet(viewsets.ModelViewSet):
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
queryset = History.objects.all()
serializer_class = HistorySerializer
filter_backends = (DjangoFilterBackend,)
filter_fields = ('contract_id',)
models.py
class RestAPIToken(models.Model):
# This model does not inherits from DRF Token to avoid including
# rest.authtoken app in INSTALLED_APPS and user may have multiple tokens
# so ForeignKey field should be used (one active token and many expired for example)
key = models.CharField(max_length=40, primary_key=True, default=generate_token)
user_id = models.IntegerField()
created = models.DateTimeField(auto_now_add=True)
expire = models.DateTimeField(default=get_expiration_date)
objects = TokenManager()
def __str__(self):
return self.key
def invalidate(self):
self.expire = timezone.now()
self.save()
def refresh(self):
self.expire = get_expiration_date()
self.save()
def is_valid(self):
return self.expire > timezone.now()
class Meta:
db_table = "rest_restapitoken"
现在,如果我提供 Authorization 标头,它可以正常工作。但是,如果我根本不提供 Auth 标头,它仍然可以正常工作。我没有用户模型。我不需要User 模型,因为我不想检查它是否有效。所以,完全跳过了User 模型。
我不明白,没有Authorization 标头,为什么请求会成功执行?
【问题讨论】:
-
RestAPIToken 和rest框架的Token模型一样吗?还是定制写的?
-
是的,是Token模型。让我编辑问题。
标签: python django django-models django-rest-framework django-authentication