Using Devise before_action :authenticate_user! doesn't do anything

会有一股神秘感。 提交于 2020-01-13 09:05:11

问题


I am trying to require login on all pages on my Rails 4 web site. In the ApplicationController I have added before_action :authenticate_user!, but it simply doesn't do anything. I have tried to add the same before_action :authenticate_user! to another controller, and it works fine.

Do I need to do something else to the ApplicationController, to make the login be required on all actions (Except signup/signin)?


回答1:


Here's the actual code we use:

#app/controllers/application_controller.rb
Class ApplicationController < ActionController::Base
   #Actions
   before_action :authenticate_user! #-> routes to the login / signup if not authenticated
end

The problem you probably have is two-fold:

--

Make sure your other controllers are inheriting from application_controller:

#app/controllers/other_controller.rb
Class OtherController < ApplicationController 
    ...
end

--

You're somehow "skipping" the before_action callback

If you're using skip_before_action anywhere, you need to remove it. It will likely cause a problem with your authenticate_user! method. To fix this, I would firstly test without any skip_before_action callbacks, and then see what gets it working correctly


A further note - signin / signup won't matter. They all inherit from the Devise controllers; they'll just run as required.




回答2:


UPDATED 2019

In your routes.rb file you may have mentioned only authenticated_user path like below

authenticated :user do
    root to: 'home#index', as: :root_app
  end

You should mention unauthenticated_user path too to make it work or just root path without unauthenticated_user or authenticated_user



来源:https://stackoverflow.com/questions/23855893/using-devise-before-action-authenticate-user-doesnt-do-anything

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!