gpt4 book ai didi

ruby-on-rails - Rails + Devise HTTP header token

转载 作者:行者123 更新时间:2023-12-02 21:49:13 25 4
gpt4 key购买 nike

我在我的设计中配置了以下行,以在 HTTP header 中启用 token 身份验证:

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/

作为 token 正确性的证明,以下内容有效:

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

有人设法在 HTTP header 中进行 token 身份验证吗?除了以下内容之外,我找不到太多关于它的信息:

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

最佳答案

我的实现是基于这个post还有这个gist .

用户.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

关于ruby-on-rails - Rails + Devise HTTP header token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18987267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com