我需要在访问已登录的登录页面时重定向用户。 我发现了一些问题,但建议的解决方案对我不起作用。这是原始问题: Redirect already logged in user Symfony2
这对我来说不起作用AuthenticationCredentialsNotFoundException
。
这是我的防火墙配置:
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/secured/login$
security: false
password_reset:
pattern: ^/secured/login\-password/
security: false
secured_area:
pattern: ^/secured/
form_login:
check_path: /secured/login_check
login_path: /secured/login
default_target_path: /secured/app
#provider: chain_provider
provider: user_db
success_handler: acme.security.authentication.success_handler
failure_handler: acme.security.authentication.failure_handler
logout:
path: /secured/logout
target: /secured/login
remember_me:
key: "%secret%"
lifetime: 31536000 # 365 days in seconds
path: /
domain: ~ # Defaults to the current domain from $_SERVER
我提到的问题中提出的解决方案导致以下例外:
AuthenticationCredentialsNotFoundException: The security context contains no authentication token. One possible reason may be that there is no firewall configured for this URL.
我做错了什么以及如何解决这个问题?
答案 0 :(得分:0)
这是我的解决方案。由于我无法通过API访问令牌,因此我决定从Session中获取并传递(如果找到)并将未序列化的值传递给访问决策管理器(通常在安全上下文内部使用)。也许可以有一个更好的解决方案,但至少这一点会有效,直到更好的解决方案变得明显。
<?php
namespace Acme\Bundle\Bundle\EventListener;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
class LoggedInListener
{
const APP_URL = 'acme_secured_app';
const LOGIN_URL = 'acme_secured_login';
private $router;
private $decisionManager;
/**
* @param Router $router
* @param AccessDecisionManagerInterface $decisionManager
*/
public function __construct(Router $router, AccessDecisionManagerInterface $decisionManager)
{
$this->router = $router;
$this->decisionManager = $decisionManager;
}
/**
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$firewallName = 'secured_area';
$tokenStr = $event->getRequest()->getSession()->get('_security_'.$firewallName);
if (!$tokenStr) {
return;
}
$token = unserialize($tokenStr);
if (!$token) {
return;
}
$authenticated = $this->decisionManager->decide($token, array('IS_AUTHENTICATED_FULLY'));
if ($authenticated) {
// authenticated (NON anonymous)
$routeName = $event->getRequest()->attributes->get('_route');
if ($routeName == self::LOGIN_URL) {
$url = $this->router->generate(self::APP_URL);
$event->setResponse(new RedirectResponse($url));
}
}
}
}
?>