You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopware 6 Admin API自定义路由报错:资源所有者或授权服务器拒绝请求

解决Shopware 6自定义Admin API路由401认证问题

你的401错误是因为@RouteScope(scopes={"api"})标记的路由属于Admin API范围,该范围默认强制要求OAuth2 Bearer Token认证,所以请求时必须携带Authorization头。以下是两种针对性解决方案:

方案1:为Admin API请求添加认证Token

如果这个接口确实是给Admin端调用的,需要先获取Admin API的访问Token,再在请求中携带:

  1. 获取Token:向{baseUrl}/api/oauth/token发送POST请求,参数采用form-data格式:
    • grant_type: password
    • client_id: admin
    • client_secret: 你的Shopware Admin客户端密钥(可在后台「设置>系统>集成>默认Admin集成」中查看)
    • username: Admin后台用户名
    • password: Admin后台密码
  2. 请求自定义接口时,在请求头添加:
    Authorization: Bearer {获取到的access_token}
    

方案2:改为Storefront范围的公开接口(无需Admin认证)

如果这个接口是给Storefront前端调用的,不需要Admin权限,修改路由范围即可:

  1. 将控制器的@RouteScope注解改为storefront:
    /**
     * @RouteScope(scopes={"storefront"})
     */
    
  2. 可选调整路由路径(避免和Admin API路径冲突),比如改为/storefront-api/product:
    /**
     * @Route("/storefront-api/product", name="storefront.api.product.search", methods={"GET"})
     */
    
  3. 修复代码中的两个细节问题:
    • 补充缺失的use语句:
      use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
      use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
      
    • 正确序列化查询结果(直接返回Repository的search对象会导致序列化异常):
      public function getProducts(Context $context): JsonResponse
      {
          $criteria = new Criteria();
          $products = $this->productRepository->search($criteria, $context)->getEntities();
          return new JsonResponse($products->jsonSerialize());
      }
      

额外说明

  • Admin API的api范围路由仅允许携带有效Bearer Token的请求访问,主要用于第三方系统对接Admin后台功能;
  • Storefront的storefront范围路由会自动使用Storefront的用户会话认证,未登录用户也能访问公开数据(如商品列表)。

内容的提问来源于stack exchange,提问作者SMS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 19:55:10