Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit ddf4977

Browse files
committedMay 31, 2022
[Security] Move the Security helper to SecurityBundle
1 parent 7350abf commit ddf4977

15 files changed

+72
-48
lines changed
 

‎Authentication/AuthenticationUtils.php

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
use Symfony\Component\HttpFoundation\Request;
1515
use Symfony\Component\HttpFoundation\RequestStack;
1616
use Symfony\Component\Security\Core\Exception\AuthenticationException;
17-
use Symfony\Component\Security\Core\Security;
17+
use Symfony\Component\Security\Http\SecurityRequestAttributes;
1818

1919
/**
2020
* Extracts Security Errors from Request.
@@ -35,13 +35,13 @@ public function getLastAuthenticationError(bool $clearSession = true): ?Authenti
3535
$request = $this->getRequest();
3636
$authenticationException = null;
3737

38-
if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) {
39-
$authenticationException = $request->attributes->get(Security::AUTHENTICATION_ERROR);
40-
} elseif ($request->hasSession() && ($session = $request->getSession())->has(Security::AUTHENTICATION_ERROR)) {
41-
$authenticationException = $session->get(Security::AUTHENTICATION_ERROR);
38+
if ($request->attributes->has(SecurityRequestAttributes::AUTHENTICATION_ERROR)) {
39+
$authenticationException = $request->attributes->get(SecurityRequestAttributes::AUTHENTICATION_ERROR);
40+
} elseif ($request->hasSession() && ($session = $request->getSession())->has(SecurityRequestAttributes::AUTHENTICATION_ERROR)) {
41+
$authenticationException = $session->get(SecurityRequestAttributes::AUTHENTICATION_ERROR);
4242

4343
if ($clearSession) {
44-
$session->remove(Security::AUTHENTICATION_ERROR);
44+
$session->remove(SecurityRequestAttributes::AUTHENTICATION_ERROR);
4545
}
4646
}
4747

@@ -52,11 +52,11 @@ public function getLastUsername(): string
5252
{
5353
$request = $this->getRequest();
5454

55-
if ($request->attributes->has(Security::LAST_USERNAME)) {
56-
return $request->attributes->get(Security::LAST_USERNAME, '');
55+
if ($request->attributes->has(SecurityRequestAttributes::LAST_USERNAME)) {
56+
return $request->attributes->get(SecurityRequestAttributes::LAST_USERNAME, '');
5757
}
5858

59-
return $request->hasSession() ? $request->getSession()->get(Security::LAST_USERNAME, '') : '';
59+
return $request->hasSession() ? $request->getSession()->get(SecurityRequestAttributes::LAST_USERNAME, '') : '';
6060
}
6161

6262
/**

‎Authentication/DefaultAuthenticationFailureHandler.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@
1616
use Symfony\Component\HttpFoundation\Response;
1717
use Symfony\Component\HttpKernel\HttpKernelInterface;
1818
use Symfony\Component\Security\Core\Exception\AuthenticationException;
19-
use Symfony\Component\Security\Core\Security;
2019
use Symfony\Component\Security\Http\HttpUtils;
2120
use Symfony\Component\Security\Http\ParameterBagUtils;
21+
use Symfony\Component\Security\Http\SecurityRequestAttributes;
2222

2323
/**
2424
* Class with the default authentication failure handling logic.
@@ -84,14 +84,14 @@ public function onAuthenticationFailure(Request $request, AuthenticationExceptio
8484
$this->logger?->debug('Authentication failure, forward triggered.', ['failure_path' => $options['failure_path']]);
8585

8686
$subRequest = $this->httpUtils->createRequest($request, $options['failure_path']);
87-
$subRequest->attributes->set(Security::AUTHENTICATION_ERROR, $exception);
87+
$subRequest->attributes->set(SecurityRequestAttributes::AUTHENTICATION_ERROR, $exception);
8888

8989
return $this->httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
9090
}
9191

9292
$this->logger?->debug('Authentication failure, redirect triggered.', ['failure_path' => $options['failure_path']]);
9393

94-
$request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
94+
$request->getSession()->set(SecurityRequestAttributes::AUTHENTICATION_ERROR, $exception);
9595

9696
return $this->httpUtils->createRedirectResponse($request, $options['failure_path']);
9797
}

‎Authenticator/AbstractLoginFormAuthenticator.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@
1515
use Symfony\Component\HttpFoundation\Request;
1616
use Symfony\Component\HttpFoundation\Response;
1717
use Symfony\Component\Security\Core\Exception\AuthenticationException;
18-
use Symfony\Component\Security\Core\Security;
1918
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
19+
use Symfony\Component\Security\Http\SecurityRequestAttributes;
2020

2121
/**
2222
* A base class to make form login authentication easier!
@@ -50,7 +50,7 @@ public function supports(Request $request): bool
5050
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response
5151
{
5252
if ($request->hasSession()) {
53-
$request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
53+
$request->getSession()->set(SecurityRequestAttributes::AUTHENTICATION_ERROR, $exception);
5454
}
5555

5656
$url = $this->getLoginUrl($request);

‎Authenticator/AuthenticatorInterface.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
*/
2727
interface AuthenticatorInterface
2828
{
29+
public const MAX_USERNAME_LENGTH = 4096;
30+
2931
/**
3032
* Does the authenticator support the given Request?
3133
*

‎Authenticator/FormLoginAuthenticator.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
2020
use Symfony\Component\Security\Core\Exception\AuthenticationException;
2121
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
22-
use Symfony\Component\Security\Core\Security;
2322
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
2423
use Symfony\Component\Security\Core\User\UserProviderInterface;
2524
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
@@ -32,6 +31,7 @@
3231
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
3332
use Symfony\Component\Security\Http\HttpUtils;
3433
use Symfony\Component\Security\Http\ParameterBagUtils;
34+
use Symfony\Component\Security\Http\SecurityRequestAttributes;
3535

3636
/**
3737
* @author Wouter de Jong <wouter@wouterj.nl>
@@ -132,11 +132,11 @@ private function getCredentials(Request $request): array
132132

133133
$credentials['username'] = trim($credentials['username']);
134134

135-
if (\strlen($credentials['username']) > Security::MAX_USERNAME_LENGTH) {
135+
if (\strlen($credentials['username']) > self::MAX_USERNAME_LENGTH) {
136136
throw new BadCredentialsException('Invalid username.');
137137
}
138138

139-
$request->getSession()->set(Security::LAST_USERNAME, $credentials['username']);
139+
$request->getSession()->set(SecurityRequestAttributes::LAST_USERNAME, $credentials['username']);
140140

141141
return $credentials;
142142
}

‎Authenticator/JsonLoginAuthenticator.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
2323
use Symfony\Component\Security\Core\Exception\AuthenticationException;
2424
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
25-
use Symfony\Component\Security\Core\Security;
2625
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
2726
use Symfony\Component\Security\Core\User\UserProviderInterface;
2827
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
@@ -151,7 +150,7 @@ private function getCredentials(Request $request)
151150
throw new BadRequestHttpException(sprintf('The key "%s" must be a string.', $this->options['username_path']));
152151
}
153152

154-
if (\strlen($credentials['username']) > Security::MAX_USERNAME_LENGTH) {
153+
if (\strlen($credentials['username']) > self::MAX_USERNAME_LENGTH) {
155154
throw new BadCredentialsException('Invalid username.');
156155
}
157156
} catch (AccessException $e) {

‎EventListener/LoginThrottlingListener.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@
1515
use Symfony\Component\HttpFoundation\RateLimiter\RequestRateLimiterInterface;
1616
use Symfony\Component\HttpFoundation\RequestStack;
1717
use Symfony\Component\Security\Core\Exception\TooManyLoginAttemptsAuthenticationException;
18-
use Symfony\Component\Security\Core\Security;
1918
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
2019
use Symfony\Component\Security\Http\Event\CheckPassportEvent;
2120
use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
21+
use Symfony\Component\Security\Http\SecurityRequestAttributes;
2222

2323
/**
2424
* @author Wouter de Jong <wouter@wouterj.nl>
@@ -42,7 +42,7 @@ public function checkPassport(CheckPassportEvent $event): void
4242
}
4343

4444
$request = $this->requestStack->getMainRequest();
45-
$request->attributes->set(Security::LAST_USERNAME, $passport->getBadge(UserBadge::class)->getUserIdentifier());
45+
$request->attributes->set(SecurityRequestAttributes::LAST_USERNAME, $passport->getBadge(UserBadge::class)->getUserIdentifier());
4646

4747
$limit = $this->limiter->consume($request);
4848
if (!$limit->isAccepted()) {

‎Firewall/ExceptionListener.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,11 @@
2828
use Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException;
2929
use Symfony\Component\Security\Core\Exception\LazyResponseException;
3030
use Symfony\Component\Security\Core\Exception\LogoutException;
31-
use Symfony\Component\Security\Core\Security;
3231
use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface;
3332
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
3433
use Symfony\Component\Security\Http\EntryPoint\Exception\NotAnEntryPointException;
3534
use Symfony\Component\Security\Http\HttpUtils;
35+
use Symfony\Component\Security\Http\SecurityRequestAttributes;
3636
use Symfony\Component\Security\Http\Util\TargetPathTrait;
3737

3838
/**
@@ -164,7 +164,7 @@ private function handleAccessDeniedException(ExceptionEvent $event, AccessDenied
164164
}
165165
} elseif (null !== $this->errorPage) {
166166
$subRequest = $this->httpUtils->createRequest($event->getRequest(), $this->errorPage);
167-
$subRequest->attributes->set(Security::ACCESS_DENIED_ERROR, $exception);
167+
$subRequest->attributes->set(SecurityRequestAttributes::ACCESS_DENIED_ERROR, $exception);
168168

169169
$event->setResponse($event->getKernel()->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true));
170170
$event->allowCustomResponseCode();

‎HttpUtils.php

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
1919
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
2020
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
21-
use Symfony\Component\Security\Core\Security;
2221

2322
/**
2423
* Encapsulates the logic needed to create sub-requests, redirect the user, and match URLs.
@@ -80,14 +79,14 @@ public function createRequest(Request $request, string $path): Request
8079
}
8180
$setSession($newRequest, $request);
8281

83-
if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) {
84-
$newRequest->attributes->set(Security::AUTHENTICATION_ERROR, $request->attributes->get(Security::AUTHENTICATION_ERROR));
82+
if ($request->attributes->has(SecurityRequestAttributes::AUTHENTICATION_ERROR)) {
83+
$newRequest->attributes->set(SecurityRequestAttributes::AUTHENTICATION_ERROR, $request->attributes->get(SecurityRequestAttributes::AUTHENTICATION_ERROR));
8584
}
86-
if ($request->attributes->has(Security::ACCESS_DENIED_ERROR)) {
87-
$newRequest->attributes->set(Security::ACCESS_DENIED_ERROR, $request->attributes->get(Security::ACCESS_DENIED_ERROR));
85+
if ($request->attributes->has(SecurityRequestAttributes::ACCESS_DENIED_ERROR)) {
86+
$newRequest->attributes->set(SecurityRequestAttributes::ACCESS_DENIED_ERROR, $request->attributes->get(SecurityRequestAttributes::ACCESS_DENIED_ERROR));
8887
}
89-
if ($request->attributes->has(Security::LAST_USERNAME)) {
90-
$newRequest->attributes->set(Security::LAST_USERNAME, $request->attributes->get(Security::LAST_USERNAME));
88+
if ($request->attributes->has(SecurityRequestAttributes::LAST_USERNAME)) {
89+
$newRequest->attributes->set(SecurityRequestAttributes::LAST_USERNAME, $request->attributes->get(SecurityRequestAttributes::LAST_USERNAME));
9190
}
9291

9392
if ($request->get('_format')) {

‎RateLimiter/DefaultLoginRateLimiter.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
use Symfony\Component\HttpFoundation\RateLimiter\AbstractRequestRateLimiter;
1515
use Symfony\Component\HttpFoundation\Request;
1616
use Symfony\Component\RateLimiter\RateLimiterFactory;
17-
use Symfony\Component\Security\Core\Security;
17+
use Symfony\Component\Security\Http\SecurityRequestAttributes;
1818

1919
/**
2020
* A default login throttling limiter.
@@ -37,7 +37,7 @@ public function __construct(RateLimiterFactory $globalFactory, RateLimiterFactor
3737

3838
protected function getLimiters(Request $request): array
3939
{
40-
$username = $request->attributes->get(Security::LAST_USERNAME, '');
40+
$username = $request->attributes->get(SecurityRequestAttributes::LAST_USERNAME, '');
4141
$username = preg_match('//u', $username) ? mb_strtolower($username, 'UTF-8') : strtolower($username);
4242

4343
return [

‎SecurityRequestAttributes.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Security\Http;
13+
14+
/**
15+
* List of request attributes used along the security flow.
16+
*
17+
* @author Robin Chalas <robin.chalas@gmail.com>
18+
*/
19+
final class SecurityRequestAttributes
20+
{
21+
public const ACCESS_DENIED_ERROR = '_security.403_error';
22+
public const AUTHENTICATION_ERROR = '_security.last_error';
23+
public const LAST_USERNAME = '_security.last_username';
24+
}

‎Tests/Authentication/DefaultAuthenticationFailureHandlerTest.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@
2020
use Symfony\Component\HttpFoundation\Session\SessionInterface;
2121
use Symfony\Component\HttpKernel\HttpKernelInterface;
2222
use Symfony\Component\Security\Core\Exception\AuthenticationException;
23-
use Symfony\Component\Security\Core\Security;
2423
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler;
2524
use Symfony\Component\Security\Http\HttpUtils;
25+
use Symfony\Component\Security\Http\SecurityRequestAttributes;
2626

2727
class DefaultAuthenticationFailureHandlerTest extends TestCase
2828
{
@@ -56,7 +56,7 @@ public function testForward()
5656

5757
$subRequest = $this->getRequest();
5858
$subRequest->attributes->expects($this->once())
59-
->method('set')->with(Security::AUTHENTICATION_ERROR, $this->exception);
59+
->method('set')->with(SecurityRequestAttributes::AUTHENTICATION_ERROR, $this->exception);
6060
$this->httpUtils->expects($this->once())
6161
->method('createRequest')->with($this->request, '/login')
6262
->willReturn($subRequest);
@@ -83,7 +83,7 @@ public function testRedirect()
8383
public function testExceptionIsPersistedInSession()
8484
{
8585
$this->session->expects($this->once())
86-
->method('set')->with(Security::AUTHENTICATION_ERROR, $this->exception);
86+
->method('set')->with(SecurityRequestAttributes::AUTHENTICATION_ERROR, $this->exception);
8787

8888
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, [], $this->logger);
8989
$handler->onAuthenticationFailure($this->request, $this->exception);
@@ -95,7 +95,7 @@ public function testExceptionIsPassedInRequestOnForward()
9595

9696
$subRequest = $this->getRequest();
9797
$subRequest->attributes->expects($this->once())
98-
->method('set')->with(Security::AUTHENTICATION_ERROR, $this->exception);
98+
->method('set')->with(SecurityRequestAttributes::AUTHENTICATION_ERROR, $this->exception);
9999

100100
$this->httpUtils->expects($this->once())
101101
->method('createRequest')->with($this->request, '/login')

‎Tests/Authenticator/FormLoginAuthenticatorTest.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@
1616
use Symfony\Component\HttpFoundation\Session\SessionInterface;
1717
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
1818
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
19-
use Symfony\Component\Security\Core\Security;
2019
use Symfony\Component\Security\Core\User\InMemoryUserProvider;
2120
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
2221
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
22+
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
2323
use Symfony\Component\Security\Http\Authenticator\FormLoginAuthenticator;
2424
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
2525
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PasswordUpgradeBadge;
@@ -62,8 +62,8 @@ public function testHandleWhenUsernameLength($username, $ok)
6262

6363
public function provideUsernamesForLength()
6464
{
65-
yield [str_repeat('x', Security::MAX_USERNAME_LENGTH + 1), false];
66-
yield [str_repeat('x', Security::MAX_USERNAME_LENGTH - 1), true];
65+
yield [str_repeat('x', AuthenticatorInterface::MAX_USERNAME_LENGTH + 1), false];
66+
yield [str_repeat('x', AuthenticatorInterface::MAX_USERNAME_LENGTH - 1), true];
6767
}
6868

6969
/**

‎Tests/Authenticator/JsonLoginAuthenticatorTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@
1616
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
1717
use Symfony\Component\Security\Core\Exception\AuthenticationException;
1818
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
19-
use Symfony\Component\Security\Core\Security;
2019
use Symfony\Component\Security\Core\User\InMemoryUserProvider;
20+
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
2121
use Symfony\Component\Security\Http\Authenticator\JsonLoginAuthenticator;
2222
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
2323
use Symfony\Component\Security\Http\HttpUtils;
@@ -121,7 +121,7 @@ public function provideInvalidAuthenticateData()
121121
$request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": "dunglas", "password": 1}');
122122
yield [$request, 'The key "password" must be a string.'];
123123

124-
$username = str_repeat('x', Security::MAX_USERNAME_LENGTH + 1);
124+
$username = str_repeat('x', AuthenticatorInterface::MAX_USERNAME_LENGTH + 1);
125125
$request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], sprintf('{"username": "%s", "password": 1}', $username));
126126
yield [$request, 'Invalid username.', BadCredentialsException::class];
127127
}

‎Tests/HttpUtilsTest.php

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@
2020
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
2121
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
2222
use Symfony\Component\Routing\RequestContext;
23-
use Symfony\Component\Security\Core\Security;
2423
use Symfony\Component\Security\Http\HttpUtils;
24+
use Symfony\Component\Security\Http\SecurityRequestAttributes;
2525

2626
class HttpUtilsTest extends TestCase
2727
{
@@ -162,9 +162,9 @@ public function testCreateRequestPassesSessionToTheNewRequest()
162162
}
163163

164164
/**
165-
* @dataProvider provideSecurityContextAttributes
165+
* @dataProvider provideSecurityRequestAttributes
166166
*/
167-
public function testCreateRequestPassesSecurityContextAttributesToTheNewRequest($attribute)
167+
public function testCreateRequestPassesSecurityRequestAttributesToTheNewRequest($attribute)
168168
{
169169
$request = $this->getRequest();
170170
$request->attributes->set($attribute, 'foo');
@@ -175,12 +175,12 @@ public function testCreateRequestPassesSecurityContextAttributesToTheNewRequest(
175175
$this->assertSame('foo', $subRequest->attributes->get($attribute));
176176
}
177177

178-
public function provideSecurityContextAttributes()
178+
public function provideSecurityRequestAttributes()
179179
{
180180
return [
181-
[Security::AUTHENTICATION_ERROR],
182-
[Security::ACCESS_DENIED_ERROR],
183-
[Security::LAST_USERNAME],
181+
[SecurityRequestAttributes::AUTHENTICATION_ERROR],
182+
[SecurityRequestAttributes::ACCESS_DENIED_ERROR],
183+
[SecurityRequestAttributes::LAST_USERNAME],
184184
];
185185
}
186186

0 commit comments

Comments
 (0)
Please sign in to comment.