如何使用Devise要求对所有页面进行身份验证?

时间:2016-01-15 21:03:10

标签: ruby-on-rails authentication devise

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

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

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

3 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

但是,如果要重定向到登录名,则应使用authenticate而不是authenticated

  

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

     

在上面的代码中将“ 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')
相关问题