为每个页面设计身份验证

时间:2013-03-12 10:56:21

标签: ruby-on-rails devise

我网站上的每个页面都需要用户身份验证(用户必须登录才能访问它)。我在Devise文档中找到了这个,但它似乎对我不起作用......

https://github.com/plataformatec/devise/wiki/How-To:-Require-authentication-for-all-pages

我已经复制了这个:

 authenticated :user do
   root :to => 'home#index'
 end
 root :to => redirect('/users/sign_in')

如何实现这一非常自然的功能?

1 个答案:

答案 0 :(得分:1)

这是我做的:

app/controllers/application_controller.rb中,添加一行,如下所示:

class ApplicationController < ActionController::Base
    # Prevent CSRF attacks by raising an exception.
    # For APIs, you may want to use :null_session instead.
    protect_from_forgery with: :exception

    before_action :authenticate_user!

    # ...
end

这会强制authenticate_user!在任何操作之前运行。

如果您有一些不需要身份验证的操作/控制器,您可以将以下行添加到其控制器文件中:

class StaticPagesController < ApplicationController
    prepend_before_filter :require_no_authentication

    # ...
end

require_no_authentication函数还带有一个可选参数,一个名为only的数组,其中包含不需要身份验证的操作列表。

n.b。我知道这是先进的死灵法术,但问题没有得到解决,我花了很多时间追逐正确的答案。