如果用户未使用Devise进行身份验证,则重定向到登录页面

Gde*_*lin 25 ruby-on-rails devise warden ruby-on-rails-4

我正在使用Devise和Ruby on Rails.

如果未经身份验证的用户尝试访问需要身份验证的页面,建议将其重定向到会话#new页面?

现在我得到一个错误,说明没有路由匹配他们尝试访问的路由(导致生产中出现404错误).

Gee*_*ToL 63

只需简单地添加此方法即可 application_controller.rb

  protected
  def authenticate_user!
    if user_signed_in?
      super
    else
      redirect_to login_path, :notice => 'if you want to add a notice'
      ## if you want render 404 page
      ## render :file => File.join(Rails.root, 'public/404'), :formats => [:html], :status => 404, :layout => false
    end
  end
Run Code Online (Sandbox Code Playgroud)

你可以在before_filter你想要的另一个控制器上调用这个方法.

例如:

class HomesController < ApplicationController
  before_filter :authenticate_user!
  ## if you want spesific action for require authentication
  ## before_filter :authenticate_user!, :only => [:action1, :action2]
end
Run Code Online (Sandbox Code Playgroud)

不要忘记添加login_pathroutes.rb

devise_scope :user do
  match '/sign-in' => "devise/sessions#new", :as => :login
end
Run Code Online (Sandbox Code Playgroud)

注意:我总是使用这种方式玩我的应用程序认证设计..(rails 3.2和rails 4.0.1)

  • 在Rails 5中,将''/ sign-in'替换为'get-sign-in' (2认同)

lea*_*otk 20

你可以像GeekTol那样写,或者只是放

before_action :authenticate_user!
Run Code Online (Sandbox Code Playgroud)

在你的控制器中.

在这种情况下,devise使用默认的authenticate_user!方法,将重定向到"user_session_path"并使用默认的Flash消息.

没有必要重写authenticate_user!方法,除非你想自定义它.