Skip to content

Commit

Permalink
Merge pull request #321 from OpenConext/bugfix/cookie-deletion-and-ex…
Browse files Browse the repository at this point in the history
…piring

Manually expire cookies after a configured amount of time
  • Loading branch information
parijke authored Jun 12, 2024
2 parents e92f23d + 3d28e82 commit c6ee51b
Show file tree
Hide file tree
Showing 10 changed files with 180 additions and 6 deletions.
1 change: 1 addition & 0 deletions bin/console
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env php
<?php


use Surfnet\StepupRa\Kernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;

Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"Surfnet\\": "src\\Surfnet"
},
"classmap": [
"src/Kernel.php"
"src/Surfnet/StepupRa/Kernel.php"
]
},
"minimum-stability": "stable",
Expand Down
2 changes: 1 addition & 1 deletion config/routes/controllers.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ controllers:
type: attribute

kernel:
resource: ../../src/Kernel.php
resource: ../../src/Surfnet/StepupRa/Kernel.php
type: attribute
10 changes: 10 additions & 0 deletions config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,13 @@ services:
arguments:
- '@security.helper'
- "%logout_redirect_url%"

Surfnet\StepupRa\RaBundle\EventListener\AuthenticatedUserListener:

Surfnet\StepupRa\RaBundle\EventListener\ExplicitSessionTimeoutListener:

Surfnet\StepupRa\RaBundle\Security\Authentication\Session\SessionLifetimeGuard:
alias: ra.security.authentication.session.session_lifetime_guard

Surfnet\StepupRa\RaBundle\Security\Authentication\AuthenticatedSessionStateHandler:
alias: ra.security.authentication.session.session_storage
1 change: 0 additions & 1 deletion public/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
* limitations under the License.
*/


use Surfnet\StepupRa\Kernel;

require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
Expand Down
2 changes: 1 addition & 1 deletion src/Kernel.php → src/Surfnet/StepupRa/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,6 @@ class Kernel extends BaseKernel
// see https://symfony.com/doc/current/reference/configuration/kernel.html#kernel-project-dir
public function getProjectDir(): string
{
return dirname(__DIR__, 1);
return dirname(__DIR__, 3);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

declare(strict_types = 1);

/**
* Copyright 2024 SURFnet bv
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Surfnet\StepupRa\RaBundle\EventListener;

use Psr\Log\LoggerInterface;

use Surfnet\StepupRa\RaBundle\Security\Authentication\AuthenticatedSessionStateHandler;
use Surfnet\StepupRa\RaBundle\Security\Authentication\Session\SessionLifetimeGuard;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class AuthenticatedUserListener implements EventSubscriberInterface
{
public function __construct(
private readonly TokenStorageInterface $tokenStorage,
private readonly SessionLifetimeGuard $sessionLifetimeGuard,
private readonly AuthenticatedSessionStateHandler $sessionStateHandler,
private readonly LoggerInterface $logger,
) {
}

public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['updateLastInteractionMoment', 6],
];
}

public function updateLastInteractionMoment(RequestEvent $event): void
{
$token = $this->tokenStorage->getToken();

if ($token === null || !$this->sessionLifetimeGuard->sessionLifetimeWithinLimits($this->sessionStateHandler)) {
return;
}
$this->logger->notice('Logged in user with a session within time limits detected, updating session state');

// see ExplicitSessionTimeoutHandler for the rationale
if ($event->getRequest()->getMethod() === 'GET') {
$this->sessionStateHandler->setCurrentRequestUri($event->getRequest()->getRequestUri());
}
$this->sessionStateHandler->updateLastInteractionMoment();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php

declare(strict_types = 1);

/**
* Copyright 2024 SURFnet bv
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Surfnet\StepupRa\RaBundle\EventListener;

use Psr\Log\LoggerInterface;
use Surfnet\StepupRa\RaBundle\Security\Authentication\AuthenticatedSessionStateHandler;
use Surfnet\StepupRa\RaBundle\Security\Authentication\Session\SessionLifetimeGuard;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Http\Event\LogoutEvent;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

final readonly class ExplicitSessionTimeoutListener implements EventSubscriberInterface
{
public function __construct(
private TokenStorageInterface $tokenStorage,
private AuthenticatedSessionStateHandler $authenticatedSession,
#[Autowire(service: 'ra.security.authentication.session.session_lifetime_guard')]
private SessionLifetimeGuard $sessionLifetimeGuard,
private RouterInterface $router,
private LoggerInterface $logger,
private EventDispatcherInterface $eventDispatcher,
) {
}

public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['checkSessionTimeout', 5],
];
}

public function checkSessionTimeout(RequestEvent $event): void
{
$token = $this->tokenStorage->getToken();

if ($token === null || $this->sessionLifetimeGuard->sessionLifetimeWithinLimits($this->authenticatedSession)) {
return;
}

$invalidatedBy = [];
if (!$this->sessionLifetimeGuard->sessionLifetimeWithinAbsoluteLimit($this->authenticatedSession)) {
$invalidatedBy[] = 'absolute';
}

if (!$this->sessionLifetimeGuard->sessionLifetimeWithinRelativeLimit($this->authenticatedSession)) {
$invalidatedBy[] = 'relative';
}

$this->logger->notice(sprintf(
'Authenticated user found, but session was determined to be outside of the "%s" time limit. User will '
. 'be logged out and redirected to session-expired page to attempt new login.',
implode(' and ', $invalidatedBy),
));

$request = $event->getRequest();

// if the current request was not a GET request we cannot safely redirect to that page after login as it
// may require a form resubmit for instance. Therefor, we redirect to the last GET request (either current
// or previous).
$afterLoginRedirectTo = $this->authenticatedSession->getCurrentRequestUri();

if ($event->getRequest()->getMethod() === 'GET') {
$afterLoginRedirectTo = $event->getRequest()->getRequestUri();
}

// log the user out using Symfony methodology, see the LogoutListener
$event->setResponse(new RedirectResponse($this->router->generate('selfservice_security_session_expired')));

// something to clear cookies
$this->eventDispatcher->dispatch(new LogoutEvent($request, $token));
$this->tokenStorage->setToken(null);

// the session is restarted after invalidation during the logout, so we can (re)store the last GET request
$this->authenticatedSession->setCurrentRequestUri($afterLoginRedirectTo);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ private function setCurrentTime(DateTime $now = null): void
{
$nowProperty = new ReflectionProperty(DateTime::class, 'now');
$nowProperty->setAccessible(true);
$nowProperty->setValue($now);
$nowProperty->setValue(null, $now);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,6 @@ private function setCurrentTime(DateTime $now = null): void
{
$nowProperty = new ReflectionProperty(DateTime::class, 'now');
$nowProperty->setAccessible(true);
$nowProperty->setValue($now);
$nowProperty->setValue(null, $now);
}
}

0 comments on commit c6ee51b

Please sign in to comment.