开发者

Omniauth: How to set authentication provider details at runtime

开发者 https://www.devze.com 2023-02-10 11:14 出处:网络
I have a rails app that is accessible from 2 domains. Facebook requires me to register a facebook app for each of these domains and gives me credentials for each. With Omniauth I can only specify one

I have a rails app that is accessible from 2 domains. Facebook requires me to register a facebook app for each of these domains and gives me credentials for each. With Omniauth I can only specify one set of credentials that is set on application startup. However, I would need to supply FB with different credentials depending on the host of the request.

There are 2 problems here:

  1. How can I change the Omniauth credentials for facebook at runtime?
  2. How can I i开发者_如何转开发ntercept the call to facebook, check the domain and set the credentials accordingly? A before filter will not work, as Omniauth uses Rack Middleware.

Any suggestions are highly appreciated!


Copying the answer from the comments in order to remove this question from the "Unanswered" filter:

I solved this myself now. The problem was that the fb strategy calls back to fb a second time to get an access token. In that second call the wrong credentials were used (the ones set in the initializer). So I had to patch the OAuth2 strategy so that it calls through to the rails app again, to set the runtime credentials for that second call. In the call back, which normally only handles the response form Omniauth, I set the credentials and return a 404 unless request.env["omniauth.auth"] is present. That works fine but has some side effects for apps without dynamic providers.

The problem is now, that even if an application doesn't want to set the credentials at runtime, it has to add a condition to the callback like if request.env["omniauth.auth"] to avoid the callback code being executed when it is called the first time. The solution is probably to add a parameter to the Omniauth builder like :dynamic_provider and only call through to the app if it is set.

~ answer per Nico


This question is fairly old but still relevant. Nowdays it is also possible to set provider details dynamically during OmniAuth's Setup Phase.

For example:

Rails.application.config.middleware.use do
  provider :example, 
    setup: ->(env) do
      env['omniauth.strategy'].options[:foo] = env['rack.session']['foo']
      env['omniauth.strategy'].options[:client_options][:site] = Something.dynamic('param')
  end
end

Source: https://github.com/omniauth/omniauth/wiki/Dynamic-Providers

0

精彩评论

暂无评论...
验证码 换一张
取 消