2017-10-17 67 views
0

我使用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 

回答

0

好吧,所以在做了研究之後,我看到了問題。由於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或任何類型的商店你喜歡