forked from trikoder/oauth2-bundle
-
Notifications
You must be signed in to change notification settings - Fork 1
/
AuthorizationRequestAuthenticationResolvingListener.php
88 lines (74 loc) · 2.58 KB
/
AuthorizationRequestAuthenticationResolvingListener.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
declare(strict_types=1);
namespace Trikoder\Bundle\OAuth2Bundle\EventListener;
use Symfony\Bundle\SecurityBundle\Security\FirewallMap;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use Trikoder\Bundle\OAuth2Bundle\Event\AuthorizationRequestResolveEvent;
use Zend\Diactoros\Response\RedirectResponse;
/**
* Listener that redirects anonymous users to login screen.
* Enabled automatically with OpenId Connect
*/
final class AuthorizationRequestAuthenticationResolvingListener
{
use TargetPathTrait;
/**
* @var AuthorizationCheckerInterface
*/
protected $authorizationChecker;
/**
* @var SessionInterface
*/
protected $session;
/**
* @var FirewallMap
*/
protected $firewallMap;
/**
* @var RequestStack
*/
protected $requestStack;
/**
* @var UrlGeneratorInterface
*/
protected $urlGenerator;
/**
* @var string
*/
protected $loginRoute;
public function __construct(
AuthorizationCheckerInterface $authorizationChecker,
SessionInterface $session,
RequestStack $requestStack,
UrlGeneratorInterface $urlGenerator,
FirewallMap $firewallMap,
string $loginRoute = 'app_login'
) {
$this->authorizationChecker = $authorizationChecker;
$this->session = $session;
$this->requestStack = $requestStack;
$this->urlGenerator = $urlGenerator;
$this->firewallMap = $firewallMap;
$this->loginRoute = $loginRoute;
}
public function onAuthorizationRequest(AuthorizationRequestResolveEvent $event): void
{
if (null === $request = $this->requestStack->getMasterRequest()) {
throw new \RuntimeException('Authentication listener depends on the request context');
}
if (!$this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$firewallConfig = $this->firewallMap->getFirewallConfig($request);
$this->saveTargetPath($this->session, $firewallConfig->getProvider(), $request->getUri());
$this->setResponse($event);
}
}
protected function setResponse(AuthorizationRequestResolveEvent $event): void
{
$loginUrl = $this->urlGenerator->generate($this->loginRoute);
$event->setResponse(new RedirectResponse($loginUrl));
}
}