Designing Api Keys Solution

Did some research, thought about it, and decided I will be implementing the api keys myself. Seems like my initial concern about keeping all auth-related stuff on one place was unnecessary. Implementing api keys on the gateway is actually a common industry practice. So, here's what I'm going to do:

  • add a new table in the db, api_keys that will contain:
    • user_id (same as keycloak id, the sub claim, also a foreign key to users table),
    • key_hash (a hashed api key),
    • active (i'll soft delete rotated keys so i dont corrupt any analytics i might do),
  • add an endpoint for creating and rotating keys:
    • POST /apikeys
    • creates a key, saves the hash to db, returns plaintext key to user
  • in auth middleware
    • check for x-api-key header
    • if present, get user id from db by key hash
    • if not present, do the usual JWT flow

No time to finish today, hopefully tomorrow.