【问题标题】:OmniAuth doesn't work with Route Globbing in Rails3OmniAuth 不适用于 Rails3 中的 Route Globbing
【发布时间】:2011-04-03 17:38:10
【问题描述】:

我正在尝试关注 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)

如果没有 globbing 路由,它会正确地进行身份验证。

有没有办法同时使用路由 globbing 和 OmniAuth?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 routes omniauth glob


    【解决方案1】:

    The OmniAuth process 是在调用/auth/:provider URL 时提供以下功能:

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

    由于您实际上是在使用路由通配符匹配所有内容,因此您的应用程序永远不会给出 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
    

    确定全局路由中的 404 状态

    我假设您的 glob 路由会以某种方式搜索与 URL 匹配的帖子;您可以错过(例如,当PostsController#index 找不到帖子时)然后生成 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
    

    【讨论】:

    • 谢谢!现在我看到了它是如何工作的。我已经按照您的建议设置了路线,并进行了细微的更改。如果我做错了,你能评论他们(见我的回答)吗?
    【解决方案2】:

    稍作修改suggestion of 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
    

    【讨论】:

    • 不要忘记 OmniAuth 使用其他路由,例如 /auth/failure,来指示身份验证失败(例如,用户拒绝了 Facebook 上的权限等)。使用这些路由,该 URL 将被 application#omniauth 吃掉。
    猜你喜欢
    • 2015-12-01
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 2019-07-07
    • 2021-03-14
    • 1970-01-01
    • 2020-04-13
    相关资源
    最近更新 更多