繁体   English   中英

Rails + Devise HTTP标头令牌

[英]Rails + Devise HTTP header token

我在设计配置中包含以下行以在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

我的实现基于此帖子和本要点

user.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

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

同时,如果您不想使用http auth,但仍可以通过http头支持令牌auth,则可以在ApiController中使用它:

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

授权标头的格式不同。

您的Authorization标头应如下所示:

# HASHED_TOKEN = Base64.encode64("#{AUTH_TOKEN}:X")
Authorization: Basic #{HASHED_TOKEN}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM