OmniAuth不适用于Rails3中的Route Globbing

我试图遵循Railscast 241 Simple OmniAuth ,除非我在/config/routes.rb末尾有Route Globbing,否则它可以正常工作:

 match '*uri' => "posts#index" 

如果我使用globbing请求/auth/twitter ,那么OmniAuth什么都不做:

 Started GET "/auth/twitter" for 127.0.0.1 at 2011-04-03 19:17:44 +0200 Processing by PostsController#index as HTML Parameters: {"uri"=>"auth/twitter"} Rendered posts/index.html.haml within layouts/application (9.0ms) Completed 200 OK in 103ms (Views: 14.6ms | ActiveRecord: 0.7ms) 

没有通配路线,它可以正确validation。

有没有办法让路线全球化和OmniAuth?

OmniAuth过程是在调用/auth/:provider URL时提供以下function:

  1. 将请求传递给底层的Rack / Rails应用程序,就好像OmniAuth不在那里一样;
  2. 确定底层应用程序是否生成404;
  3. 如果是,请调用实际的OmniAuthfunction。

由于你基本上使用你的路由通配符匹配所有内容 ,你的应用程序永远不会给404,OmniAuth无法完成它的工作。 我看到两个直接的选择。

手动将OmniAuth路由与404匹配

添加新路线如下:

 match '/auth/:provider' => 'omniauth#passthru' 

然后创建一个生成404的控制器和操作:

 class OmniauthController < ApplicationController def passthru render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false end end 

确定Glob Route中的404状态

我假设您的glob路线将以某种方式搜索与URL匹配的post; 你可以抓住失误(例如,当PostsController#index找不到post时)然后生成404。

 class PostsController < ApplicationController def index if @posts = Post.find_by_current_url_or_whatever render 'index' else render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false end end end 

对Brandon Tilley略有修改的建议 :

 # config/routes.rb match '/auth/:provider/callback' => 'sessions#create' match 'auth/*rest' => 'application#omniauth' match '*uri' => 'posts#index' # app/controllers/application_controller.rb def omniauth render text: 'Authentication', status: 404 end 
Interesting Posts