2

我在我的设计配置中有以下行以在 HTTP 标头中启用令牌身份验证:

config.http_authenticatable = [:token]

但是,每当我尝试访问资源时,运行以下命令时都会收到 401:

curl -v -H "Accept: application/json" -H "Content-type: application/json" -H "Authorization: Token token=\"c9G52z6n6LpGt5Ls6omW\"" http://localhost:3000/api/v1/objects/

作为令牌正确的证明,以下工作:

curl -v -H "Accept: application/json" -H "Content-type: application/json" http://localhost:3000/api/v1/objects?auth_token=c9G52z6n6LpGt5Ls6omW

有没有人设法在 HTTP 标头中获得令牌身份验证?除了以下内容,我找不到太多关于它的信息:

http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html https://groups.google.com/forum/#!topic/plataformatec-devise/o3Gqgl0yUZo

4

3 回答 3

3

我的实现基于这篇文章和这个要点

用户.rb

class User < ActiveRecord::Base

  devise :database_authenticatable, 
         :recoverable, :rememberable, :trackable, :validatable

  before_create :set_auth_token

  private

    def set_auth_token
      return if auth_token.present?

      begin
        self.auth_token = SecureRandom.hex
      end while self.class.exists?(auth_token: self.auth_token)
    end

end

api_controller.rb

class ApiController < ApplicationController

  before_action :authenticate

  protected

    def authenticate
      authenticate_token || render_unauthorized
    end

    def authenticate_token
      authenticate_with_http_token do |token, options|
        user = User.find_by(auth_token: token)

        if user
          sign_in user, store: false
        end

        user
      end
    end

    def render_unauthorized
      self.headers['WWW-Authenticate'] = 'Token realm="Application"'
      render json: 'Bad credentials', status: 401
    end

end
于 2014-08-12T08:53:02.783 回答
2

好吧,我尝试通过设计以这种方式启用它,但这对我来说并没有真正起作用:/

同时你可以在你的 ApiController 中使用它,如果你不想使用 http auth,但仍然支持 http header 的 token auth:

before_filter :authenticate_with_http_token
def authenticate_with_http_token
  auth_header = request.headers['Authorization'].to_s
  token = auth_header[/token="(.*?)"/,1]
  return unless token

  user = User.find_for_token_authentication(auth_token: token)
  sign_in user if user
end
于 2013-09-27T10:30:10.193 回答
0

授权标头的格式不同。

您的Authorization标题应如下所示:

# HASHED_TOKEN = Base64.encode64("#{AUTH_TOKEN}:X")
Authorization: Basic #{HASHED_TOKEN}
于 2013-09-25T13:39:51.943 回答