如何在 symfony 4 注销中重定向到外部 url [英] How to redirect to external url in symfony 4 logout

查看:31
本文介绍了如何在 symfony 4 注销中重定向到外部 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道在 Symfony 4 中是否有一个简单的解决方案.通常用户会注销并被发送回主页.但是有一个页面可以检查用户当前是否在另一个站点上进行了身份验证,如果这是不正确的,我有一个链接可以让用户退出我的站点并重定向到外部站点.我使用 app.php 中的以下控制器路由在基于旧版 silex 的站点上管理此操作

Just wondering if there is an easy solution to this in Symfony 4. Normally users would logout and be sent back to the home page. But there is one page where it is checked that the user is currently authenticated on another site, if this is incorrect I have a link that logs the user out of my site and redirects to the external site. I managed this on an old silex based version of the site using the following routing of controllers in app.php

$app->get('/logout', $app->factory(function() use($app) {
$pid = $app['request_stack']->getCurrentRequest()->query->get('pid');
$message = $app['request_stack']->getCurrentRequest()->query->get('message');
$redirect = $app['request_stack']->getCurrentRequest()->query->get('redirect');
return $app->redirect(FRAMEWORK_URL."/logout?pid=$pid&message=$message&redirect=$redirect");
})

);

谢谢

马丁

推荐答案

不幸的是 logout.target 将不起作用,因为有特殊检查(在 Symfony\Component\Security\Http\HttpUtils::createRedirectResponse) 将请求域与重定向域进行匹配.如果它们不同,它会将目标设置为 /.

Unfortunately logout.target will not work as there is special check (in Symfony\Component\Security\Http\HttpUtils::createRedirectResponse) to match the request domain to the redirection domain. If they're not the same it will set the target to /.

重定向到外部 URL 的正确方法是创建实现 Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface 的类,例如像这样:

Proper way of redirecting to external URL is to create class which implements Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface, for example like this:

<?php

// src/Security/CustomLogoutSuccessHandler.php

class CustomLogoutSuccessHandler implements LogoutSuccessHandlerInterface
{
    private $target;

    public function __construct(string $target)
    {
        $this->target = $target;
    }

    public function onLogoutSuccess(Request $request)
    {
        return new RedirectResponse($this->target);
    }
}

然后在services.yaml中创建服务:

services:
  App\Security\CustomLogoutSuccessHandler:
    arguments: ['%env(resolve:LOGOUT_TARGET_URL)%'] # resolve from .env (or you can get from anywhere)

最后告诉 security.yaml 使用您的处理程序而不是默认处理程序:

and finally tell security.yaml to use your handler instead of default one:

security:
  firewalls:
    main:
      logout:
        success_handler: 'App\Security\CustomLogoutSuccessHandler'

这篇关于如何在 symfony 4 注销中重定向到外部 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆