cache auth0公钥
问题描述:
我使用auth0进行身份验证,并使用其提供的方法之一(复制如下)来确认jwt令牌。他们提供的解决方案在每次向我的服务器发送请求时都会提供服务,这使得请求最多需要1秒才能完成。cache auth0公钥
我试图缓存由他们提供的方法生成但没有运气的公钥。起初,我以为我可以将其存储在Rails.cache
但后来意识到该方法将创建一个OpenSSL
对象,而不是一个字符串,当我尝试Rails.cache.write('KEY', openSslObject)
与Rails.cache.fetch('KEY')
我得到零返回
访问我也试图用与轨道缓存块存取:
cached_jwks_hash = Rails.cache.fetch("JWKS_HASH", expires_in: 10.hours) do
get_jwks_hash
end
但仍获得零
下get_jwks_hash
方法返回以下内容:{"key"=>#<OpenSSL::PKey::RSA:0x007fe29c545ef8>}
什么是缓存这些数据的最佳方式?是否有可能将其存储在内存中的变量?
def verify(token, jwks_hash)
JWT.decode(token, nil,
true, # Verify the signature of this token
algorithm: 'RS256',
iss: "https://#{ENV["AUTH0_DOMAIN"]}/",
verify_iss: true,
aud: ENV["AUTH0_API_AUDIENCE"],
verify_aud: true) do |header|
jwks_hash[header['kid']]
end
end
def get_jwks_hash
jwks_raw = Net::HTTP.get URI("https://#{ENV["AUTH0_DOMAIN"]}/.well-known/jwks.json")
jwks_keys = Array(JSON.parse(jwks_raw)['keys'])
Hash[
jwks_keys
.map do |k|
[
k['kid'],
OpenSSL::X509::Certificate.new(
Base64.decode64(k['x5c'].first)
).public_key
]
end
]
end
答
好吧,所以在做了研究之后,我看到了问题。由于rails.cache.fetch
方法正在使用不实际存储任何数据的null_store
,因此没有保存密钥。在我config/environments/development
文件那里有下面的代码:
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age=172800'
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
,因为我没有一个tmp/caching-dev.txt
文件,正在使用的null_store
。第二行到最后一行可更新为
config.cache_store = :memory_store
或任何类型的商店你喜欢