Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Security] Add #[IsGranted()] #46907

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
use Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Http\Controller\UserValueResolver;
use Symfony\Component\Security\Http\EventListener\IsGrantedAttributeListener;
use Symfony\Component\Security\Http\Firewall;
use Symfony\Component\Security\Http\FirewallMapInterface;
use Symfony\Component\Security\Http\HttpUtils;
Expand Down Expand Up @@ -269,5 +270,9 @@
service('security.expression_language'),
])
->tag('kernel.cache_warmer')

->set('controller.is_granted_attribute_listener', IsGrantedAttributeListener::class)
->args([service('security.authorization_checker')])
->tag('kernel.event_subscriber')
;
};
6 changes: 3 additions & 3 deletions src/Symfony/Bundle/SecurityBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
"php": ">=8.1",
"composer-runtime-api": ">=2.1",
"ext-xml": "*",
"symfony/config": "^5.4|^6.0",
"symfony/dependency-injection": "^5.4|^6.0",
"symfony/config": "^6.1",
"symfony/dependency-injection": "^6.1",
"symfony/event-dispatcher": "^5.4|^6.0",
"symfony/http-kernel": "^5.4|^6.0",
"symfony/http-kernel": "^6.2",
"symfony/http-foundation": "^5.4|^6.0",
"symfony/password-hasher": "^5.4|^6.0",
"symfony/security-core": "^5.4|^6.0",
Expand Down
43 changes: 43 additions & 0 deletions src/Symfony/Component/Security/Http/Attribute/IsGranted.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Security\Http\Attribute;

/**
* @author Ryan Weaver <[email protected]>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm getting credit without even opening a PR 😎

*/
#[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::TARGET_FUNCTION)]
class IsGranted
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should probably be final, because the usage of $event->getAttributes()[IsGranted::class] means that the listener does not support subclasses of that attribute.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see #46915

{
public function __construct(
/**
* Sets the first argument that will be passed to isGranted().
*/
public array|string|null $attributes = null,

/**
* Sets the second argument passed to isGranted().
*/
public array|string|null $subject = null,

/**
* The message of the exception - has a nice default if not set.
*/
public ?string $message = null,

/**
* If set, will throw HttpKernel's HttpException with the given $statusCode.
* If null, Security\Core's AccessDeniedException will be used.
*/
public ?int $statusCode = null,
) {
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/Security/Http/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Add maximum username length enforcement of 4096 characters in `UserBadge`
* Add `#[IsGranted()]`

6.0
---
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Security\Http\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Http\Attribute\IsGranted;

/**
* Handles the IsGranted attribute on controllers.
*
* @author Ryan Weaver <[email protected]>
*/
class IsGrantedAttributeListener implements EventSubscriberInterface
{
public function __construct(
private AuthorizationCheckerInterface $authChecker,
) {
}

public function onKernelControllerArguments(ControllerArgumentsEvent $event)
{
/** @var IsGranted[] $attributes */
if (!\is_array($attributes = $event->getAttributes()[IsGranted::class] ?? null)) {
return;
}

$namedArguments = [];
$arguments = $event->getArguments();
$r = $event->getRequest()->attributes->get('_controller_reflectors')[1] ?? new \ReflectionFunction($event->getController());

foreach ($r->getParameters() as $i => $param) {
if ($param->isVariadic()) {
$namedArguments[$param->name] = \array_slice($arguments, $i);
break;
}
if (\array_key_exists($i, $arguments)) {
$namedArguments[$param->name] = $arguments[$i];
}
}

foreach ($attributes as $attribute) {
$subjectRef = $attribute->subject;
$subject = null;

if ($subjectRef) {
if (\is_array($subjectRef)) {
foreach ($subjectRef as $ref) {
if (!\array_key_exists($ref, $namedArguments)) {
throw new \RuntimeException(sprintf('Could not find the subject "%s" for the #[IsGranted] attribute. Try adding a "$%s" argument to your controller method.', $ref, $ref));
}
$subject[$ref] = $namedArguments[$ref];
}
} elseif (!\array_key_exists($subjectRef, $namedArguments)) {
throw new \RuntimeException(sprintf('Could not find the subject "%s" for the #[IsGranted] attribute. Try adding a "$%s" argument to your controller method.', $subjectRef, $subjectRef));
} else {
$subject = $namedArguments[$subjectRef];
}
}

if (!$this->authChecker->isGranted($attribute->attributes, $subject)) {
$message = $attribute->message ?: sprintf('Access Denied by #[IsGranted(%s)] on controller', $this->getIsGrantedString($attribute));

if ($statusCode = $attribute->statusCode) {
throw new HttpException($statusCode, $message);
}

$accessDeniedException = new AccessDeniedException($message);
$accessDeniedException->setAttributes($attribute->attributes);
$accessDeniedException->setSubject($subject);

throw $accessDeniedException;
}
}
}

public static function getSubscribedEvents(): array
{
return [KernelEvents::CONTROLLER_ARGUMENTS => ['onKernelControllerArguments', 10]];
}

private function getIsGrantedString(IsGranted $isGranted): string
{
$attributes = array_map(fn ($attribute) => '"'.$attribute.'"', (array) $isGranted->attributes);
$argsString = 1 === \count($attributes) ? reset($attributes) : '['.implode(', ', $attributes).']';

if (null !== $isGranted->subject) {
$argsString .= ', "'.implode('", "', (array) $isGranted->subject).'"';
}

return $argsString;
}
}
Loading