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.jsonsuffix (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

