Hommer Smith
Hommer Smith

Reputation: 27852

How to get Authorization token in Rails

I have the following ApiController that deals with Authorization via a before_action filter:

class ApiController < ApplicationController
  before_action :restrict_access

  private

  def restrict_access
    authenticate_or_request_with_http_token do |token, options|
      ApiKey.exists?(access_token: token)
    end
  end
end

This works fine.

Now, I have a controller from that Api that needs to use that ApiKey in order to find the associated user. So, I have tried doing this:

class OrdersController < ApiController
  def index
    # How do I access the ApiKey that has been detected in the parent filter?
    @user = ApiKey.find_by(access_token: params[:token]).user # This is not working
  end
end

This doesn't work because params[:token] is empty, because the token is passed in the Authorization header like Authorization Token token='xxxx'. So, how can I get that from my controller?

Upvotes: 0

Views: 1777

Answers (2)

MBHNYC
MBHNYC

Reputation: 1258

Pretty simple, you should look up your user IN the authenticate method, and set it to @current_user or whatnot.

Then you have it available in all requests and can just do:

class OrdersController < ApiController
  def index
    @current_user
  end
end

And your restrict_accees could be:

  def restrict_access
    authenticate_or_request_with_http_token do |token, options|
      user = ApiKey.where(access_token: token).includes(:user) #preloads user if available
      if user.present?
        @current_user = user
        true
      else 
        false
      end
    end
  end

Upvotes: 0

blotto
blotto

Reputation: 3407

to grab the token from request.headers['Authorization'] use the following pattern

 /(.*)=\"(.*)\"/.match(request.headers["Authorization"])[2]

Upvotes: 1

Related Questions