使用Ajax进行Omniauth授权调用

当我使用它作为链接时,我的Rails 3应用程序中的omniauth正常工作:

link_to("Connect Twitter", "/auth/twitter", :id => "connect-to-twitter") 

现在我想通过ajax调用’/ auth / twitter’。 但是,在请求阶段之后不会返回任何内容。 这是最后一个日志条目:

 Started GET "/auth/twitter" for 127.0.0.1 at 2012-10-30 17:53:02 -0700 (twitter) Request phase initiated. 

这是我的ajax代码(在Coffeescript中):

 $("#connect-to-twitter").live("click", -> alert('get twitter') $.get('/auth/twitter', (data) -> alert(data) ) return false ) 

(我知道这个问题在此之前已被问过,但我没有看到任何真正的答案。)

我知道这个问题有点旧,但我仍然会回答它。 在面对问题并寻求实现与OP意图相同的事情之后

我写了一个中间件,并在Omniauth正上方插入中间件的外观

 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 

在这里我如何通过中间件插入中间件堆栈

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

这是我的中间件堆栈的外观

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

有了这个,我就能实现我想要的

注意 :我没有在Omniauth文档中找到任何有关ajax内容的信息,因为我正在运行时间,因此我实现了此修复程序(因为谷歌搜索从来没有给我一个有利的答案)。 有可能Omniauth也支持ajax响应,但据说我无法在文档中找到一个。 答案是那些希望实现完全相同function但又不确定如何在Omniauth中实现它的用户。

我仍然在寻找Omniauth,通过设置/调整配置来查找是否存在直接在Omniauth中执行此操作的方法

希望这有帮助

两件事:首先,由于您使用的是localhost,因此您必须设置端口号(假设为3000),因此端点应为localhost:3000 。 其次,您还必须设置重定向,也应该是localhost:3000