【发布时间】:2015-09-18 01:58:59
【问题描述】:
我在我的主应用程序中使用 Devise 进行身份验证,并且
我已经使用“http_basic_authenticate_with”构建了一个 API(用于 PABX),当我将 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
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
当我想在引擎中执行类似于该 API 的操作时,就会出现问题。
当我尝试访问该路由时,Devise 似乎不允许在未经身份验证的情况下访问它,即使我使用的是before_action :authenticate_user!, except: [:method_name]。
config/routes.rb(我的引擎)
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(我的引擎)
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)
(如果我做错了什么或有人有更好的想法,请在此处分享。) (我正在使用带 Rails 4.2.0 的 Devise 3.5.2)
非常感谢您阅读我的问题。
【问题讨论】:
标签: ruby-on-rails authentication devise rails-engines ruby-on-rails-4.2