我正在使用 Symfony 4 和 API 平台开发一个网站。我的用户资源受到标准 Symfony 安全性 ( "security": "is_granted('ROLE_USER')") 的保护:
/**
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
* @ApiResource(
* collectionOperations={
* "get_user_profile": {
* "method": "GET",
* "path": "/users/profile",
* "controller": GetUserProfile::class,
* "pagination_enabled": false,
* "openapi_context": {"summary": "Retrieves the current User's profile."},
* "security": "is_granted('ROLE_USER')"
* },
* },
* itemOperations={},
* normalizationContext={"groups": {"read"}},
* )
*/
class User implements UserInterface
{
}
问题是,如果我尝试访问此 API,则响应将重定向到登录页面。如何禁用重定向并将响应保留为 401?
重定向对网站用户非常有用,但 API 用户不应该收到 HTML 响应。
这是我的security.yml:
security:
encoders:
App\Entity\User:
algorithm: auto
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\User
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|img|js)/
security: false
main:
anonymous: lazy
guard:
authenticators:
- App\Security\LoginFormAuthenticator
logout:
path: app_logout
# where to redirect after logout
# target: app_any_route
remember_me:
secret: '%kernel.secret%'
lifetime: 604800 # 1 week in seconds
path: /
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#firewalls-authentication
# https://symfony.com/doc/current/security/impersonating_user.html
# switch_user: true
红糖糍粑