为了使用来自faraday docs的自定义中间件,我看到我必须使用use
方法。在我的用例中,我的自定义生成器仅在标头中添加了jwt auth令牌:
Faraday.new(url: wsconfig.base_url) do |builder|
builder.use CustomMiddlewares::JwtAuthentication
builder.request :url_encoded
builder.response :json
builder.adapter :net_http
end
jwt_authentication.rb
require 'jwt'
module CustomMiddlewares
class JwtAuthentication < Faraday::Middleware
def call(env)
payload = RequestStore.store[:jwt_claims].to_h.merge({method: env.method, path: env.url.request_uri})
token = jwt(payload)
Rails.logger.debug { " with token: #{token}" }
env[:request_headers]["Authorization"] = "Token: #{token}"
@app.call(env)
rescue StandardError => e
raise "problem in JwtAuthentication Middleware"
end
private
def jwt(payload, expiration = 1.minute.from_now)
payload = payload.dup
payload['exp'] = expiration.to_i
payload['iss'] = 'cgp'
JWT.encode(payload, key, 'RS256')
end
def key
OpenSSL::PKey::RSA.new(Rails.configuration.x.secrets.ws_config.jwt_private_key)
end
end
end
CustomMiddlewares::JwtAuthentication
仅应在url_encoded
方法添加的request
中间件之类的请求阶段使用。我不知道为什么我不能对我做同样的事情:
builder.request CustomMiddlewares::JwtAuthentication
我知道了:
CustomMiddlewares::VerbosingPseudonymizationWs is not registered on Faraday::Request (Faraday::Error)
答案 0 :(得分:0)
如果要使用builder.request
,则首先需要这样注册中间件:
Faraday::Request.register_middleware jwt: -> { CustomMiddlewares::JwtAuthentication }
之后,您应该可以致电builder.request :jwt
。这是由于Faraday::RackBuilder#request
本质上以Faraday::RackBuilder#use
作为第一个参数调用了Faraday::Request.lookup_middleware(key)
。
请参见https://github.com/lostisland/faraday/blob/master/lib/faraday/rack_builder.rb#L92 和https://github.com/lostisland/faraday/blob/master/lib/faraday/rack_builder.rb#L228
这也意味着builder.request :jwt
和builder.use CustomMiddlewares::JwtAuthentication
之间没有区别。
请求和响应中间件之间的区别在于,响应中间件应从Faraday::Response::Middleware
继承,以确保它们仅对响应(on_complete
)执行。参见https://github.com/lostisland/faraday/blob/master/lib/faraday/response.rb#L8
即,即使通过builder.request
注册了中间件,但如果它实现了on_complete
回调,它仍然可以对响应起作用。相反,如果不实现回调,则不会对响应执行任何代码。