独自の認証モジュールを作成できます。次に例を示します。
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 用) を作成して返すハンドラーを作成するだけです。