自定义表单登录验证器响应
表单登录验证器创建一个登录表单,用户可以使用标识符(例如,电子邮件地址或用户名)和密码进行身份验证。在 安全 中解释了此验证器的用法。
成功登录后的重定向
默认情况下,表单将重定向到用户请求的 URL(即,触发显示登录表单的 URL)。例如,如果用户请求了 http://www.example.com/admin/post/18/edit
,那么在他们成功登录后,他们将被发送回 http://www.example.com/admin/post/18/edit
。
这是通过将请求的 URL 存储在会话中来完成的。如果会话中没有 URL(可能是用户直接访问登录页面),则用户将被重定向到 /
(即主页)。您可以通过多种方式更改此行为。
更改默认页面
定义 default_target_path
选项以更改用户在会话中未存储先前页面时重定向到的页面。该值可以是相对/绝对 URL 或 Symfony 路由名称
1 2 3 4 5 6 7 8 9
# config/packages/security.yaml
security:
# ...
firewalls:
main:
form_login:
# ...
default_target_path: after_login_route_name
始终重定向到默认页面
定义 always_use_default_target_path
布尔选项以忽略先前请求的 URL 并始终重定向到默认页面
1 2 3 4 5 6 7 8 9
# config/packages/security.yaml
security:
# ...
firewalls:
main:
form_login:
# ...
always_use_default_target_path: true
使用请求参数控制重定向
登录后要重定向到的 URL 可以使用 GET 或 POST 请求的 _target_path
参数动态定义。其值必须是相对或绝对 URL,而不是 Symfony 路由名称。
对于 GET,使用查询字符串参数
1
http://example.com/some/path?_target_path=/dashboard
对于 POST,使用隐藏的表单字段
1 2 3 4 5 6 7
{# templates/login/index.html.twig #}
<form action="{{ path('app_login') }}" method="post">
{# ... #}
<input type="hidden" name="_target_path" value="{{ path('account') }}">
<input type="submit" name="login">
</form>
使用引荐来源 URL
如果会话中未存储先前的 URL 且请求中未包含 _target_path
参数,则可以使用 HTTP_REFERER
标头的值,因为这通常是相同的。定义 use_referer
布尔选项以启用此行为
1 2 3 4 5 6 7 8 9 10
# config/packages/security.yaml
security:
# ...
firewalls:
main:
# ...
form_login:
# ...
use_referer: true
注意
引荐来源 URL 仅在它与 login_path
路由生成的 URL 不同时使用,以避免重定向循环。
失败登录后的重定向
登录失败后(例如,提交了无效的用户名或密码),用户将被重定向回登录表单本身。使用 failure_path
选项通过相对/绝对 URL 或 Symfony 路由名称定义新的目标
1 2 3 4 5 6 7 8 9 10
# config/packages/security.yaml
security:
# ...
firewalls:
main:
# ...
form_login:
# ...
failure_path: login_failure_route_name
此选项也可以通过 _failure_path
请求参数设置
1
http://example.com/some/path?_failure_path=/forgot-password
1 2 3 4 5 6 7
{# templates/security/login.html.twig #}
<form action="{{ path('login') }}" method="post">
{# ... #}
<input type="hidden" name="_failure_path" value="{{ path('forgot_password') }}">
<input type="submit" name="login">
</form>
自定义目标和失败请求参数
用于定义成功和失败登录重定向的请求属性的名称可以使用定义登录表单的防火墙的 target_path_parameter
和 failure_path_parameter
选项进行自定义。
1 2 3 4 5 6 7 8 9 10
# config/packages/security.yaml
security:
# ...
firewalls:
main:
# ...
form_login:
target_path_parameter: go_to
failure_path_parameter: back_to
使用上述配置,查询字符串参数和隐藏的表单字段现在已完全自定义
1
http://example.com/some/path?go_to=/dashboard&back_to=/forgot-password
1 2 3 4 5 6 7 8
{# templates/security/login.html.twig #}
<form action="{{ path('login') }}" method="post">
{# ... #}
<input type="hidden" name="go_to" value="{{ path('dashboard') }}">
<input type="hidden" name="back_to" value="{{ path('forgot_password') }}">
<input type="submit" name="login">
</form>