florimondmanca / djangorestframework-api-key

🔐 API key permissions for Django REST Framework
https://florimondmanca.github.io/djangorestframework-api-key/
MIT License
678 stars 104 forks source link

How to list all available api keys from account. #197

Closed MatthiasMuller closed 2 years ago

MatthiasMuller commented 2 years ago

Hey! Im currently using this amazing library to store API Keys for users, each API Key is used for some services in my API.

Each User is connected to a APIKey.

class UserApiKey(AbstractAPIKey):
    """
    APIKey model
    """

    user = models.ForeignKey(User, on_delete=models.DO_NOTHING,
                             related_name='api_keys',
                             verbose_name='User')

As a user, I want to retrieve all available API Keys, is there any way to fetch them all? My problem is that API Keys are hashed, and I want to list all client available API Keys.

florimondmanca commented 2 years ago

Hi @MatthiasMuller,

This library was actually designed to (mostly) prevent the server from reading API keys in cleartext once they've been generated. (I write mostly because the server can theoretically access them on a per-request basis in views, see #98.) I wasn't expecting that users of this library use it to manage API keys, although that makes total sense now. My original use case was "internal API keys", e.g. between an internal frontend app and the Django API server. So there's still some work required to make it easier to manage "external API keys"… There are a couple of other issues around here that sort of prompt this too.

If your use case is something like "show available API keys to clients" and you don't actually need to get the actual API key, would the API key prefixes be sufficient?

api_keys = UserApiKey.objects.all()
prefixes = [api_key.prefix for api_key in api_keys]  # ['PdIgApov', ...]

This is actually what the default API key admin displays, see:

https://github.com/florimondmanca/djangorestframework-api-key/blob/7ed909a2d7ea7a4bc3fcde2de19854b77909309e/src/rest_framework_api_key/admin.py#L10-L20