我正在尝试使用'enable_standard_devise_support = true'来使devise + devise_token_auth一起工作,而不需要为Web重复每个控制器和为API重复每个控制器。
我在初始化程序中打开标准设计支持
: config.enable_standard_devise_support = true
并将我的路线设置为嵌套
: namespace :api, defaults: {format: 'json'} do # namespace devise token routes to stop duplication
: namespace :v1 do
: mount_devise_token_auth_for 'User', at: 'auth'
: end
: end
本地路线仍在api之外
: resources :home, only: [:index]
: root to: "home#index"
我有一个api application_controller.rb;
: module Api
: module V1
: class ApplicationController < ActionController::API
: include DeviseTokenAuth::Concerns::SetUserByToken
: before_action :authenticate_user!
: before_action :configure_permitted_parameters, if: :devise_controller?
:
: protected
:
: def configure_permitted_parameters
: devise_parameter_sanitizer.permit(:sign_in, keys: [:email, :password])
: end
: end
: end
: end
和带有application_controller.rb的;
: class ApplicationController < ActionController::Base
: protect_from_forgery unless: -> { request.format.json? }
: end
为什么我的其他路线,例如home#index不起作用?
我从devise_token_auth访问/home.json区域时遇到错误
: Successfully synced application org.nativescript.NativeScriptTemplate2 on device emulator-5586.
: JS: Angular is running in the development mode. Call enableProdMode() to enable the production mode.
: JS: Login called
: JS: Logged in: 06rD-pZ-kstw_YZO7cWTCQ
: JS: ERROR {
: JS: "headers": {
: JS: "normalizedNames": {},
: JS: "lazyUpdate": null
: JS: },
: JS: "status": 401,
: JS: "statusText": "Unauthorized",
: JS: "url": "http://192.168.200.4:3000/[email protected]&client=vRardfTGtk10YTXwz8cSRg&access-token=06rD-pZ-kstw_YZO7cWTCQ",
: JS: "ok": false,
: JS: "name": "HttpErrorResponse",
: JS: "message": "Http failure response for http://192.168.200.4:3000/[email protected]&client=vRardfTGtk10YTXwz8cSRg&access-token=06rD-pZ-kstw_YZO7cWTCQ: 401 Unauthorized",
: JS: "error": {
: JS: "error": "You need to sign in or sign up before continuing."
: JS: }
: JS: }
这里是家庭控制器
class HomeController < ApplicationController
before_action :authenticate_user!
respond_to :html, :json
def index
respond_to do |format|
format.html
format.json { render json: {message: "Welcome to the Ruby on Rails backend"} }
end
end
end
尝试创建App::BaseController
并在此处放置身份验证方法:
class App::BaseController < ApplicationController
before_action :authenticate_user!
end
现在,继承您要获得授权的所有控制器的App::BaseController
。