使用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 。
- 使用带远程的ajax的Ruby表单:true给出了ActionController :: InvalidAuthenticityToken错误。 经典提交没有
- Ruby rails – jquery ajax提交表单
- Ajax with Polymorphic Association(Destroy&Create)
- 使用rails-Ajax调用控制器方法?
- Ruby on Rails Ajax调用运行控制器代码,返回成功,但不渲染视图
- Rails:使用控制器呈现js.erb模板
- Rails呈现javascript显示文本
- 部分Javascript(Ruby on Rails)
- Hartl第11章Ajax未定义局部变量或方法`cookies’