我正在编写基于Cookie的Symfony身份验证器,从配置好的UserProvider(远程服务调用)获得响应后,我需要在最终响应中设置Cookie。从配置的UserProvider(远程服务调用)获得响应后,我需要在最终的Response中设置Cookie。我不知道在这个阶段如何访问Response对象来添加新的Cookie到它的头文件中。
添加Cookie的代码通常是这样的。
$cookie = new Cookie('foo', 'bar', strtotime('Wed, 28-Dec-2016 15:00:00 +0100'), '/', '.example.com', true, true, true),
$response->headers->setCookie(new Cookie('foo', 'bar'));
我需要引用 $response
我不想创建自己的Response实例并将其返回,因为我想让Response的创建保持原样,但我只需要这一个cookie被添加到Response中。在Symfony 5中,有什么最好的方法可以实现?
这是我正在使用的简化的Authenticator代码。
<?php
namespace App\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
class SessionCookieAuthenticator extends AbstractGuardAuthenticator
{
public function supports(Request $request)
{
// check if php-sid cookie is provided
return !empty($request->cookies->get('php-sid'));
}
/**
* Credentials are global cookies
* @param Request $request
* @return mixed|string
*/
public function getCredentials(Request $request)
{
$cookie = implode('; ', array_map(
function($k, $v) {
return $k . '=' . $v;
},
array_keys($_COOKIE),
$_COOKIE
));
return $cookie;
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
return $userProvider->loadUserByCookie($credentials);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return null; // @todo set Cookie here for example. Can I get Response here?
}
}
UserProvider
不应该设置一个Cookie,因为Cookie与提供一个用户无关。我建议在其他地方设置Cookie(例如,创建一个事件监听器,为 security.authentication.success
或直接在你的Authenticator里面。
编辑
onAuthenticationSuccess
让你返回一个 Response
(你,基本上需要创建它)。响应后,你就可以设置需要的cookie了。