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,再在请求中携带:
- 获取Token:向
{baseUrl}/api/oauth/token发送POST请求,参数采用form-data格式:grant_type:passwordclient_id:adminclient_secret: 你的Shopware Admin客户端密钥(可在后台「设置>系统>集成>默认Admin集成」中查看)username: Admin后台用户名password: Admin后台密码
- 请求自定义接口时,在请求头添加:
Authorization: Bearer {获取到的access_token}
方案2:改为Storefront范围的公开接口(无需Admin认证)
如果这个接口是给Storefront前端调用的,不需要Admin权限,修改路由范围即可:
- 将控制器的
@RouteScope注解改为storefront:/** * @RouteScope(scopes={"storefront"}) */ - 可选调整路由路径(避免和Admin API路径冲突),比如改为
/storefront-api/product:/** * @Route("/storefront-api/product", name="storefront.api.product.search", methods={"GET"}) */ - 修复代码中的两个细节问题:
- 补充缺失的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()); }
- 补充缺失的use语句:
额外说明
- Admin API的
api范围路由仅允许携带有效Bearer Token的请求访问,主要用于第三方系统对接Admin后台功能; - Storefront的
storefront范围路由会自动使用Storefront的用户会话认证,未登录用户也能访问公开数据(如商品列表)。
内容的提问来源于stack exchange,提问作者SMS
相关产品推荐
相关产品推荐

