Using auth_token from request headers instead from POST/PUT parameters with Rails 3 / devise

前端 未结 4 903
长情又很酷
长情又很酷 2021-01-30 18:18

I need to use token based authentication in a Rails 3.1 API in conjunction with the most recent version of devise. No problem so far.

Now I do not want to append my :au

相关标签:
4条回答
  • 2021-01-30 18:25

    It is possible in Devise to pass a standard authentication token through query string or the header for HTTP Basic Authentication, see here. The Ruby code from the specs to pass token in the HTTP_Authorization header is

    header = "Basic #{Base64.encode64("#{VALID_AUTHENTICATION_TOKEN}:X")}"
    get users_path(:format => :xml), {}, "HTTP_AUTHORIZATION" => header
    

    Testing from the command line with curl would go like this:

    echo  "HUGP59gXsd7773a75Dvc:X" | base64
    => SFVHUDU5Z1hzZDc3NzNhNzVEdmM6WAo=
    curl --header "Authorization: Basic SFVHUDU5Z1hzZDc3NzNhNzVEdmM6WAo=" \ 
         http://localhost/users.xml
    
    0 讨论(0)
  • 2021-01-30 18:30

    I had the same need and came up with this solution:

    class YourController < ApplicationController
      prepend_before_filter :get_api_key
      before_filter :authenticate_user!
    
      private
      def get_api_key
        if api_key = params[:api_key].blank? && request.headers["X-API-KEY"]
          params[:api_key] = api_key
        end
      end
    end
    

    Note I have my devise Devise.token_authentication_key set to api_key.

    config.token_authentication_key = :api_key
    
    0 讨论(0)
  • 2021-01-30 18:41

    Using devise and devise-token_authenticatable, I had to set this in my config/initializers/devise.rb in order to pass the token via http headers:

    config.http_authenticatable = true

    0 讨论(0)
  • 2021-01-30 18:44

    I'm using a custom "strategy" for this: https://gist.github.com/4492569

    0 讨论(0)
提交回复
热议问题