Last active
April 30, 2018 21:39
-
-
Save danielalvarenga/d9ca06c892d5286cfa33c74611bb3ef4 to your computer and use it in GitHub Desktop.
Bearer Authentication in Rails Controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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