我在我的主应用程序中使用Devise进行身份验证,并且我已经使用"http_basic_authenticate_with“构建了一个应用程序接口(用于用户交换机),当我将before_action :authenticate_user!, except: [:method_name]添加到我的控制器中时,它工作得很好。我之所以这样做,是因为except: [:method_name]不需要在Devise上记录用户会话,而我只想对这些API控制器使用基本身份验证。
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
endcontrollers/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当我想要在引擎中执行类似于该API的操作时,问题就会发生。当我尝试访问路由时,Devise似乎不允许在没有身份验证的情况下访问它,即使我使用的是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)
非常感谢您阅读我的问题。
发布于 2015-12-15 02:51:35
我解决了这个问题,这很简单。现在我在我的Engine Application Controller中进行身份验证,而不是通过我的主Application Controller上的路由。
module Myengine
class ApplicationController < ActionController::Base
before_action :authenticate_user!
end
end我还删除了配置/routes.rb(主应用程序)上的authenticate :user
mount Myengine::Engine, at: '/myengine'这样,我就可以在任何控制器中使用以下代码
before_action :authenticate_user!, except: [:mypublic_method]https://stackoverflow.com/questions/32642681
复制相似问题