在使用API密钥时跳过Devise身份验证,可以通过以下步骤实现:
authenticate_user_from_token
的方法,该方法用于验证API密钥。class ApiController< ApplicationController
before_action :authenticate_user_from_token!
private
def authenticate_user_from_token!
authenticate_with_http_token do |token, options|
user_email = options[:user_email].presence
user = user_email && User.find_by(email: user_email)
if user && Devise.secure_compare(user.authentication_token, token)
sign_in user, store: false
else
render json: { error: 'Invalid API key' }, status: :unauthorized
end
end
end
end
config/initializers/devise.rb
文件中,添加以下代码以允许API密钥身份验证:config.http_authenticatable = true
config.http_authenticatable_on_xhr = true
class MyApiController < ApiController
def index
# Your code here
end
end
Authorization
字段,格式为Token token="your_api_key", user_email="your_email"
。require 'net/http'
require 'uri'
uri = URI('https://example.com/my_api')
request = Net::HTTP::Get.new(uri)
request['Authorization'] = "Token token=\"your_api_key\", user_email=\"your_email\""
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
这样,在使用API密钥时,就可以跳过Devise身份验证。推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云