florimondmanca/djangorestframework-api-key

How to list all available api keys from account.

Closed this issue · 1 comments

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.

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:

class APIKeyModelAdmin(admin.ModelAdmin):
model: typing.Type[AbstractAPIKey]
list_display = (
"prefix",
"name",
"created",
"expiry_date",
"_has_expired",
"revoked",
)