Omniauth authorization call with Ajax

不问归期 提交于 2019-12-05 04:41:05

I know the question is bit old but I'll still answer it . After facing the issue for and looking to achieve the same what the OP intended to I did this

I wrote a middleware and inserted in right above the Omniauth here how the middleware look

class OmniAuthMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, body = @app.call(env)
    request = Rack::Request.new(env)
    if request.xhr? and status == 302 and request.path_info =~ /\/auth\/\w+\z/ and body.class == Rack::BodyProxy
      location = headers["Location"]
      body = ActionDispatch::Response.new
      headers = {'Content-Type'=>'text/javascript; charset=utf-8'}
      body.body = ["window.location.href='#{location}'"]
      body.headers = headers
      status = 200
    end
    [status,headers,body]
  end
end

And here how I insert by middleware in the middleware stack

Rails.application.config.middleware.insert_before OmniAuth::Builder,OmniAuthMiddleware

Here how my middleware stack look

...
...
...
use Warden::Manager
use Rack::Mongoid::Middleware::IdentityMap
use ExceptionNotifier
use OmniAuthMiddleware
use OmniAuth::Builder
run PoasterApi::Application.routes

With this I was able to achieve what I wanted

Note: I haven't found any info about ajax stuff in the Omniauth doc and since I was running against time hence I implemented this fix (since a google search never gave me a favourable answer) . It could be possible that Omniauth support ajax response as well but as said I was not able to find one in the documentation . The answer is for those users who wish to implement the exact same functionality but just not sure how to achieve it in Omniauth .

I'm still looking at Omniauth to find if their exist a way to do this directly in Omniauth by setting/tweaking the configuration

Hope this help

Two things: First, since you're using localhost, you'll have to set the port number (assuming 3000), so the endpoint should be localhost:3000. Secondly, you also have to set a redirect, which should also be localhost:3000.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!