Skip to content

Instantly share code, notes, and snippets.

@hopsoft
Last active April 19, 2019 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hopsoft/afb2508455509aa6aa0c to your computer and use it in GitHub Desktop.
Save hopsoft/afb2508455509aa6aa0c to your computer and use it in GitHub Desktop.
Simple API security with Rails

Simple API security with Rails

API clients set an HTML header.

Authorization: Token token="SECRET_API_KEY"

Your ApplicationController can then restrict access based on the token.

class ApplicationController < ActionController::Base
  before_action :restrict_access

  def restrict_access
    authenticate_or_request_with_http_token do |token, options|
      token == "SECRET_API_KEY"
    end
  end
end

While very basic, this works well for simple use cases.

You will likely want to add some sort of storage for your API keys. If you don't have many keys to manage, hard coding or environment variables will work.

No need to pull in solutions like Devise until your use case becomes more complex.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment