Rails and HttpAuthentication Token
Rails has some controller helper modules for authentication:
So you can have on your controller like that:
# app/controllers/users_controller.rb
class UsersController < ApplicationController
include UserAuthentication
before_action :authenticate, only: %i(show)
def show
render json: current_user, status: :ok
end
end
And a controller concern like this:
# app/controllers/concerns/user_authentication.rb
module UserAuthentication
# you might need to include:
# include ActionController::HttpAuthentication::Token::ControllerMethods
def authenticate
head :forbidden unless current_user
end
def current_user
@current_user ||= authenticate_or_request_with_http_token do |token|
Session.find_by(token: token).try(:user)
end
end
end
Then your controller will read and parse the token from the header:
{
headers: {
"HTTP_AUTHORIZATION"=>'Token token="82553421c8f4e5e34436"'
}
}
Tweet