【问题标题】:How to require authentication for all pages with Devise?如何使用 Devise 要求对所有页面进行身份验证?
【发布时间】:2016-01-15 21:03:10
【问题描述】:

我已经开始使用 Devise gem,现在尝试实现代码,所以我的网络应用程序需要登录我应用程序上的每个页面。我根据this instruction将以下代码添加到routes.rb

authenticated :user do
  root to: 'home#index', as: :authenticated_root
end
root to: redirect('/users/sign_in')

但它不起作用。当我转到任何页面时 - 它只是打开该页面,而不会将我转发到登录页面。谁能澄清我错过了什么?任何帮助将不胜感激。

【问题讨论】:

    标签: ruby-on-rails authentication devise


    【解决方案1】:

    将此添加到您的应用控制器

    class ApplicationController < ActionController::Base
      ...
      before_action :authenticate_user!
    end
    

    【讨论】:

    • 如果您需要公开某些页面,您只能在 before_action 之后添加:[] 和除外:[]
    • 谢谢 - 我会这样做,但我希望登录页面是公开的 - 我必须在 [ ] 中添加什么才能使登录页面公开?
    • 正确。如果您有任何继承自 ApplicationController 的子控制器并且需要执行跳过/绕过该身份验证的操作(即它们是公共页面),您可以将其添加到其控制器的顶部:skip_before_action :authenticate_user!, only: [:index]跨度>
    【解决方案2】:

    这还不够。您仍然需要告诉您的控制器要求对任何操作进行身份验证。在您的情况下,最快的方法是将before_action :authenticate_user! 添加到ApplicationController

    【讨论】:

      【解决方案3】:

      您不需要在routes.rbbefore_action 中组合身份验证,只需在routes.rb 中就足够了。

      但是如果你想重定向到登录,你应该使用authenticate而不是authenticated

      使用“authenticate”,可以使资源和路由在被访问之前要求进行身份验证

      将上述代码中的“authenticate”替换为“authenticated”会导致如果用户未通过身份验证,资源将不可用

      https://github.com/plataformatec/devise/wiki/How-To:-Define-resource-actions-that-require-authentication-using-routes.rb

      应该是这样的:

      authenticate :user do
        root to: 'home#index', as: :authenticated_root
      end
      root to: redirect('/users/sign_in')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-23
        • 2014-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多