入口点:帮助用户开始身份验证
当未经身份验证的用户尝试访问受保护的页面时,Symfony 会向他们提供合适的响应,以让他们开始身份验证(例如,重定向到登录表单或为 API 显示 401 Unauthorized HTTP 响应)。
但是,有时,一个防火墙有多种身份验证方式(例如,表单登录和社交登录)。在这些情况下,需要配置*身份验证入口点*。
您可以使用 entry_point
设置来配置它
1 2 3 4 5 6 7 8 9 10 11 12 13
# config/packages/security.yaml
security:
# ...
firewalls:
main:
# allow authentication using a form or a custom authenticator
form_login: ~
custom_authenticators:
- App\Security\SocialConnectAuthenticator
# configure the form authentication as the entry point for unauthenticated users
entry_point: form_login
注意
您还可以通过创建一个实现 AuthenticationEntryPointInterface 的类来创建您自己的身份验证入口点。然后,您可以将 entry_point
设置为服务 ID(例如 entry_point: App\Security\CustomEntryPoint
)
具有独立入口点的多个验证器
但是,在某些用例中,您的验证器保护应用程序的不同部分。例如,您有一个登录表单来保护主网站,而外部方使用的 API 端点受 API 密钥保护。
由于每个防火墙只能配置一个入口点,因此解决方案是将配置拆分为两个单独的防火墙
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# config/packages/security.yaml
security:
# ...
firewalls:
api:
pattern: ^/api/
custom_authenticators:
- App\Security\ApiTokenAuthenticator
main:
lazy: true
form_login: ~
access_control:
- { path: '^/login', roles: PUBLIC_ACCESS }
- { path: '^/api', roles: ROLE_API_USER }
- { path: '^/', roles: ROLE_USER }
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。