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

Symfony中如何从安全路径规则中排除特定路由?

Absolutely, you must place the anonymous access rule for /api/doc and /api/doc.json above your existing /api rule—here's why, plus how to make sure you only target those exact two paths:

First, Symfony processes access_control rules in top-to-bottom order: the first rule that matches the request path is the one that gets applied, and it stops checking subsequent rules. If you put your /api/doc rule below the ^/api rule, every request starting with /api (including /api/doc and /api/doc.json) will hit the IS_AUTHENTICATED_FULLY rule first, and your exception rule will never run.

Next, to make sure you only exclude those two specific paths (and not every path starting with /api/doc, like /api/doc/secret), you need to adjust the regex pattern to match exactly those URLs. Using ^/api/doc would match any path starting with that string, so we add anchors and an optional suffix to lock it down.

Here's the corrected configuration for your security.yaml:

security:
    # ... your other security config ...
    access_control:
        # Exact match for /api/doc and /api/doc.json
        - { path: ^/api/doc(\.json)?$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        # Catch-all for all other /api paths
        - { path: ^/api, roles: IS_AUTHENTICATED_FULLY }

Let's break down the regex ^/api/doc(\.json)?$:

  • ^ = Start of the URL string
  • /api/doc = The base path we want to target
  • (\.json)? = An optional .json suffix (the ? makes the group optional)
  • $ = End of the URL string

This ensures only the two exact paths you mentioned are allowed for anonymous users, while all other /api paths still require full authentication.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 00:42:42