我正在开发 Spree Commerce 应用程序,并尝试创建需要身份验证的自定义 API 控制器/页面,并且我想使用 spree_devise_auth gem。 但是,尽管提供了有效的身份验证令牌,我还是遇到了身份验证问题。这是我的设置的简化版本:
我有一个名为 Api::V2::CustomController 的自定义控制器,位于 app/controllers/api/v2/custom_controller.rb:
class Api::V2::CustomController < Spree::Api::V2::BaseController
before_action :authenticate_spree_user!
def index
render json: { message: 'Custom Controller Working!' }
end
end
我已经在 config/routes.rb 中为此控制器设置了一条路由:
Rails.application.routes.draw do
namespace :api do
namespace :v2 do
get '/custom', to: 'custom#index'
end
end
end
当我尝试使用有效的身份验证令牌访问 /api/v2/custom 端点时,我收到以下响应:
{
"error": "You need to sign in or sign up before continuing."
}
但实际上这个问题最有趣的方面是,当我输入这个问题时,我尝试再次提出请求并得到:
{
"error": "The access token expired"
}
所以现在我很困惑 xD,因为它检查令牌和所有这些,但它只是不进行身份验证!
这是我迄今为止尝试解决该问题的方法:
仔细检查身份验证令牌以确保其正确。 已验证 spree 中的其他“默认”端点(例如 /api/v2/storefront/account)是否可以使用相同的身份验证令牌正常工作。
我不知道还能尝试什么来解决这个问题:/关于我做错了什么有什么想法吗?
没关系!我意识到 helper_method - spree_current_user - 在整个应用程序中都可用,当 access_token 正确时,助手返回用户对象,如果不返回“null”,所以我实际上可以做一个简单的 before_action :check_if_current_user 并对其进行身份验证