【发布时间】:2015-09-10 00:06:41
【问题描述】:
我已使用 TokenAuthentication 通过 DRF 启用用户身份验证
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication'
),
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.ModelSerializer',
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
#'EXCEPTION_HANDLER': 'apps.core.exceptions.custom_exception_handler'
}
我有以下型号:
class Device(CreationModificationMixin):
"""
Contains devices (WW controllers). A device may be associated with the Owner
"""
_STATUSES = (
('A', 'Active'), # when everything is okay
('I', 'Inactive'), # when we got nothing from SPA controllers for X minutes
('F', 'Failure'), # when controller says it has issues
)
_TYPES = (
('S', 'Spa'),
('P', 'Pool'),
)
udid = models.CharField(max_length=255, verbose_name="Unique ID / MAC Address", help_text="MAC Address of WiFi controller", unique=True, null=False, blank=False, db_index=True)
type = models.CharField(max_length=1, choices=_TYPES, null=False, blank=False)
title = models.CharField(max_length=255, null=False, blank=False, db_index=True)
status = models.CharField(max_length=1, default='A', choices=_STATUSES)
pinged = models.DateTimeField(null=True)
owner = models.ForeignKey(Owner, verbose_name="Owner", null=True, blank=True, db_index=True)
def __str__(self):
return self.udid
这表示将向 API 端点发送离散请求的硬件设备,因此我需要对每个请求进行身份验证,最好使用基于令牌的标识,例如
POST /api/devices/login
{
udid: '...mac address...',
hash: '...sha256...hash string',
time: '2015-01-01 12:24:30'
}
哈希将在设备端计算为 sha256(salt + udid + current_time) 将在 /login 内部的 DRF 端计算相同的哈希值,以比较并生成将保存在 REDIS 中并返回响应的令牌。
所有未来的请求都会将此令牌作为标头传递,这将在自定义 Permission 类中进行检查。
我的问题:
- 我想为请求类设置一个自定义属性,例如 request.device, request.device.is_authenticated()
我应该把这个功能放在哪里?
- 您发现我的方法有问题吗?也许是改进的建议?
【问题讨论】:
-
这是 this question 的副本,但我目前没有标记。
标签: django authentication django-rest-framework django-authentication