如何避免Devise从引擎内部进行身份validation?

我在我的主应用程序中使用Devise进行身份validation,并且我使用“http_basic_authenticate_with”构建了一个API(用于PABX),当我将before_action :authenticate_user!, except: [:method_name]到我的控制器时,它运行良好。 我这样做是因为except: [:method_name]不需要在Devise上记录用户会话,我只想对这些API控制器使用基本身份validation。

config/routes.rb (主应用程序)

 scope module: 'api' do scope module: 'pabx' do scope '/api/pabx' do get '/accounts/phone_number/:phone_number', to: 'accounts#phone_number' end end end 

controllers/api/pabx/accounts_controller.rb (主要应用)

 class Api::Pabx::AccountsController < ApplicationController http_basic_authenticate_with name: 'some_name', password: 'some_password' before_action :authenticate_user!, except: [:phone_number] skip_before_filter :verify_authenticity_token # POST api/pabx/accounts/phone_number.json def phone_number ... end end 

当我想在Engine中执行与API类似的操作时,问题就出现了。 当我尝试访问路由时,Devise似乎不允许在没有身份validation的情况下访问它,即使我正在使用before_action :authenticate_user!, except: [:method_name]

config/routes.rb (Myengine)

 scope module: 'api' do scope '/api' do get '/accounts/phone_number/:phone_number', to: 'accounts#phone_number' end end 

controllers/api/pabx/accounts_controller.rb (Myengine)

 require_dependency "myengine/application_controller" module Myengine class Api::AccountsController < ApplicationController http_basic_authenticate_with name: 'some_name', password: 'some_password' before_action :authenticate_user!, except: [:phone_number] skip_before_filter :verify_authenticity_token # POST api/pabx/accounts/phone_number.json def phone_number ... end end 

这是我在主应用程序中的代码

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 # Authentication using Devise (DO NOT REMOVE THIS LINE) before_action :authenticate_user! end 

config/routes.rb (主应用程序)

 authenticate :user do mount Myengine::Engine, at: '/myengine' end 

当我尝试在我的引擎中访问该方法时,终端向我显示:

 Started POST "/myengine/api/accounts/phone_number.json" for ::1 at 2015-09-17 21:15:31 -0300 Started GET "/users/sign_in" for ::1 at 2015-09-17 21:15:31 -0300 Processing by Devise::SessionsController#new as */* Rendered users/shared/_links.html.erb (6.3ms) Rendered users/sessions/new.html.erb within layouts/authentication (29.3ms) Rendered layouts/elements/_flash_messages.html.erb (2.3ms) Completed 200 OK in 720ms (Views: 714.4ms | ActiveRecord: 0.0ms) 

(如果我做错了或有人有更好的想法,请在这里分享。)(我正在使用Devise 3.5.2和Rails 4.2.0)

非常感谢您阅读我的问题。

我解决了这个问题,这很简单。 现在我在我的引擎应用程序控制器中进行身份validation,而不是在主应用程序控制器上进行身份validation。

 module Myengine class ApplicationController < ActionController::Base before_action :authenticate_user! end end 

我还删除了authenticate :user on my config / routes.rb(main application)

 mount Myengine::Engine, at: '/myengine' 

这样我就可以在任何控制器中使用以下代码

 before_action :authenticate_user!, except: [:mypublic_method]