security core
v7.2.0
Security provides an infrastructure for sophisticated authorization systems, which makes it possible to easily separate the actual authorization logic from so called user providers that hold the users credentials.
composer require symfony/security-core
use SymfonyComponentSecurityCoreAuthenticationAuthenticationTrustResolver;
use SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken;
use SymfonyComponentSecurityCoreAuthorizationAccessDecisionManager;
use SymfonyComponentSecurityCoreAuthorizationVoterAuthenticatedVoter;
use SymfonyComponentSecurityCoreAuthorizationVoterRoleVoter;
use SymfonyComponentSecurityCoreAuthorizationVoterRoleHierarchyVoter;
use SymfonyComponentSecurityCoreExceptionAccessDeniedException;
use SymfonyComponentSecurityCoreRoleRoleHierarchy;
$accessDecisionManager = new AccessDecisionManager([
new AuthenticatedVoter(new AuthenticationTrustResolver()),
new RoleVoter(),
new RoleHierarchyVoter(new RoleHierarchy([
'ROLE_ADMIN' => ['ROLE_USER'],
]))
]);
$user = new AppEntityUser(...);
$token = new UsernamePasswordToken($user, 'main', $user->getRoles());
if (!$accessDecisionManager->decide($token, ['ROLE_ADMIN'])) {
throw new AccessDeniedException();
}
The Security component for Symfony 7.1 is backed by SymfonyCasts.
Learn Symfony faster by watching real projects being built and actively coding along with them. SymfonyCasts bridges that learning gap, bringing you video tutorials and coding challenges. Code on!
Help Symfony by sponsoring its development!