Hasty Briefsbeta

Bilingual

How to Implement API Key Authentication in Rails Without Devise

a day ago
  • Devise is overkill for API authentication; Rails provides built-in tools like `has_secure_password` and HTTP authentication methods.
  • Create a User model with `has_secure_password` and an ApiKey model with polymorphic association to support multiple bearer types.
  • Use `ActionController::HttpAuthentication::Token::ControllerMethods` for token-based authentication, and `Basic` for login.
  • Implement endpoints: POST /api-keys (login with Basic auth), GET /api-keys (list keys with token auth), DELETE /api-keys/:id (revoke key with token auth).
  • Store token digests (HMAC-SHA256) instead of plaintext tokens to prevent timing attacks and exposure.
  • Use `before_create` to generate HMAC digest and a virtual attribute `token` for only post-creation response.
  • The entire solution requires under 100 lines of application code (excluding migrations).