Skip to content

Instantly share code, notes, and snippets.

@danielalvarenga
Last active April 30, 2018 21:39
Show Gist options
  • Save danielalvarenga/d9ca06c892d5286cfa33c74611bb3ef4 to your computer and use it in GitHub Desktop.
Save danielalvarenga/d9ca06c892d5286cfa33c74611bb3ef4 to your computer and use it in GitHub Desktop.
Bearer Authentication in Rails Controller
# application_controller.rb
class ApplicationController < ActionController::API
include ActionController::HttpAuthentication::Token::ControllerMethods
before_action :authenticate
protected
def authenticate
authenticate_token || render_unauthorized
end
def authenticate_token
authenticate_with_http_token do |token, _options|
Credential.authenticated(token)
end
end
def render_unauthorized(realm = 'Application')
headers['WWW-Authenticate'] = %(Token realm="#{realm.delete('"')}")
render json: { error: :bad_credentials }.to_json, status: :unauthorized
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment