您可以编写自己的身份验证模块。这是一个例子:
class ApiKeyAuthentication(object):
def is_authenticated(self, request):
auth_string = request.META.get("HTTP_AUTHORIZATION")
if not auth_string:
return False
key = get_object_or_None(ApiKey, key=auth_string)
if not key:
request.user = AnonymousUser()
return False
request.user = key.user
return True
def challenge(self):
resp = HttpResponse("Authorization Required")
resp['WWW-Authenticate'] = "Key Based Authentication"
resp.status_code = 401
return resp
您需要一个模型来存储 API 密钥到用户的映射:
class ApiKey(models.Model):
user = models.ForeignKey(User, related_name='keys')
key = models.CharField(max_length=KEY_SIZE)
您需要一些方法来生成实际的密钥。这样的事情会起作用(比如,在 ApiKey 模型的save
方法中:
key = User.objects.make_random_password(length=KEY_SIZE)
while ApiKey.objects.filter(key__exact=key).count():
key = User.objects.make_random_password(length=KEY_SIZE)
最后,连接新的身份验证后端:
# urls.py
key_auth = ApiKeyAuthentication()
def ProtectedResource(handler):
return resource.Resource(handler=handler, authentication=key_auth)
your_handler = ProtectedResource(YourHandler)
至于将用户名/密码交换为 API 密钥,只需编写一个使用 BasicAuthentication 的处理程序来创建并返回新的 ApiKey(用于 request.user)。