-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathEndSessionController.php
More file actions
210 lines (182 loc) · 9.23 KB
/
EndSessionController.php
File metadata and controls
210 lines (182 loc) · 9.23 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
<?php
declare(strict_types=1);
namespace SimpleSAML\Module\oidc\Controllers;
use League\OAuth2\Server\Exception\OAuthServerException;
use Psr\Http\Message\ServerRequestInterface;
use SimpleSAML\Module\oidc\Bridges\PsrHttpBridge;
use SimpleSAML\Module\oidc\Factories\TemplateFactory;
use SimpleSAML\Module\oidc\Server\AuthorizationServer;
use SimpleSAML\Module\oidc\Server\LogoutHandlers\BackChannelLogoutHandler;
use SimpleSAML\Module\oidc\Server\RequestTypes\LogoutRequest;
use SimpleSAML\Module\oidc\Services\ErrorResponder;
use SimpleSAML\Module\oidc\Services\LoggerService;
use SimpleSAML\Module\oidc\Services\SessionService;
use SimpleSAML\Module\oidc\Stores\Session\LogoutTicketStoreBuilder;
use SimpleSAML\Session;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
class EndSessionController
{
public function __construct(
protected AuthorizationServer $authorizationServer,
protected SessionService $sessionService,
protected LogoutTicketStoreBuilder $sessionLogoutTicketStoreBuilder,
protected LoggerService $loggerService,
protected TemplateFactory $templateFactory,
protected PsrHttpBridge $psrHttpBridge,
protected ErrorResponder $errorResponder,
) {
}
/**
* @throws \SimpleSAML\Error\BadRequest
* @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException
* @throws \Throwable
*/
public function __invoke(ServerRequestInterface $request): Response
{
// TODO v7 Back-Channel Logout: https://openid.net/specs/openid-connect-backchannel-1_0.html
// [] Refresh tokens issued without the offline_access property to a session being logged out SHOULD
// be revoked. Refresh tokens issued with the offline_access property normally SHOULD NOT be revoked.
// - offline_access scope is now handled.
$logoutRequest = $this->authorizationServer->validateLogoutRequest($request);
// Set indication that the logout is initiated using OIDC protocol. This will be checked in the
// logoutHandler() method.
$this->sessionService->setIsOidcInitiatedLogout(true);
// Indication if any there was a call to logout action on any auth source at all...
$wasLogoutActionCalled = false;
$sidClaim = null;
// If id_token_hint was provided, resolve session ID
$idTokenHint = $logoutRequest->getIdTokenHint();
if ($idTokenHint !== null) {
$sidClaim = empty($idTokenHint->claims()->get('sid')) ?
null :
(string)$idTokenHint->claims()->get('sid');
}
// Check if RP is requesting logout for session that previously existed (not this current session).
// Claim 'sid' from 'id_token_hint' logout parameter indicates for which session should log out be
// performed (sid is session ID used when ID token was issued during authn). If the requested
// sid is different from the current session ID, try to find the requested session.
if (
$sidClaim !== null &&
$this->sessionService->getCurrentSession()->getSessionId() !== $sidClaim
) {
try {
if (($sidSession = $this->sessionService->getSessionById($sidClaim)) !== null) {
$sidSessionValidAuthorities = $sidSession->getAuthorities();
if (! empty($sidSessionValidAuthorities)) {
$wasLogoutActionCalled = true;
// Create a SessionLogoutTicket so that the sid is available in the static logoutHandler()
$this->sessionLogoutTicketStoreBuilder->getInstance()->add($sidClaim);
// Initiate logout for every valid auth source for the requested session.
foreach ($sidSessionValidAuthorities as $authSourceId) {
$sidSession->doLogout($authSourceId);
}
}
}
} catch (Throwable $exception) {
$this->loggerService->warning(
sprintf('Logout: could not get session with ID %s, error: %s', $sidClaim, $exception->getMessage()),
);
}
}
$currentSessionValidAuthorities = $this->sessionService->getCurrentSession()->getAuthorities();
if (!empty($currentSessionValidAuthorities)) {
$wasLogoutActionCalled = true;
// Initiate logout for every valid auth source for the current session.
foreach ($this->sessionService->getCurrentSession()->getAuthorities() as $authSourceId) {
$this->sessionService->getCurrentSession()->doLogout($authSourceId);
}
}
// Set indication for OIDC initiated logout back to false, so that the logoutHandler() method does not
// run for other logout initiated actions, like (currently) re-authentication...
$this->sessionService->setIsOidcInitiatedLogout(false);
return $this->resolveResponse($logoutRequest, $wasLogoutActionCalled);
}
public function endSession(Request $request): Response
{
try {
/**
* @psalm-suppress DeprecatedMethod Until we drop support for old public/*.php routes, we need to bridge
* between PSR and Symfony HTTP messages.
*/
return $this->__invoke($this->psrHttpBridge->getPsrHttpFactory()->createRequest($request));
} catch (OAuthServerException $exception) {
return $this->errorResponder->forException($exception);
}
}
/**
* Logout handler function registered using Session::registerLogoutHandler() during authn.
* @throws \Exception
*/
public static function logoutHandler(): void
{
$session = Session::getSessionFromRequest();
// Only run this handler if logout was initiated using OIDC protocol. This is important since this
// logout handler will (currently) also be called in re-authentication cases.
// https://groups.google.com/g/simplesamlphp/c/-uhiVE8TaF4
if (!SessionService::getIsOidcInitiatedLogoutForSession($session)) {
return;
}
$relyingPartyAssociations = SessionService::getRelyingPartyAssociationsForSession($session);
SessionService::clearRelyingPartyAssociationsForSession($session);
// Check for session logout tickets. If there are any, it means that the logout was initiated using OIDC RP
// initiated flow for specific session (not current one).
$sessionLogoutTicketStore = LogoutTicketStoreBuilder::getStaticInstance();
$sessionLogoutTickets = $sessionLogoutTicketStore->getAll();
if (!empty($sessionLogoutTickets)) {
// TODO v7 low mivanci This could brake since interface does not mandate type. Move to strong typing.
/** @var array $sessionLogoutTicket */
foreach ($sessionLogoutTickets as $sessionLogoutTicket) {
$sid = (string)$sessionLogoutTicket['sid'];
if ($sid === $session->getSessionId()) {
continue;
}
try {
if (($sessionLogoutTicketSession = Session::getSession($sid)) !== null) {
$relyingPartyAssociations = array_merge(
$relyingPartyAssociations,
SessionService::getRelyingPartyAssociationsForSession($sessionLogoutTicketSession),
);
SessionService::clearRelyingPartyAssociationsForSession($sessionLogoutTicketSession);
}
} catch (Throwable $exception) {
LoggerService::getInstance()->warning(
sprintf(
'Session Ticket Logout: could not get session with ID %s, error: %s',
$sid,
$exception->getMessage(),
),
);
}
}
$sessionLogoutTicketStore->deleteMultiple(
array_map(fn(array $slt): string => (string)$slt['sid'], $sessionLogoutTickets),
);
}
(new BackChannelLogoutHandler())->handle($relyingPartyAssociations);
}
/**
* @throws \SimpleSAML\Error\ConfigurationError
*/
protected function resolveResponse(LogoutRequest $logoutRequest, bool $wasLogoutActionCalled): Response
{
if (($postLogoutRedirectUri = $logoutRequest->getPostLogoutRedirectUri()) !== null) {
if ($logoutRequest->getState() !== null) {
$postLogoutRedirectUri .= (!str_contains($postLogoutRedirectUri, '?')) ? '?' : '&';
$postLogoutRedirectUri .= http_build_query(['state' => $logoutRequest->getState()]);
}
return new RedirectResponse($postLogoutRedirectUri);
}
return $this->templateFactory->build(
templateName: 'oidc:/logout.twig',
data: [
'wasLogoutActionCalled' => $wasLogoutActionCalled,
],
showMenu: false,
showModuleName: false,
showSubPageTitle: false,
);
}
}