You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Error Output:
This page isn’t working127.0.0.1 redirected you too many times. Try deleting your cookies.
ERR_TOO_MANY_REDIRECTS
src/Security/CustomAuthAuthenticator.php
`<?php
namespace App\Security;
use App\Entity\User;
use App\Exception\UserNotFoundException;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\InvalidTokenException;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\RememberMeBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\SecurityRequestAttributes;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
class CustomAuthAuthenticator extends AbstractLoginFormAuthenticator
{
use TargetPathTrait;
public const LOGIN_ROUTE = 'app_login';
public function __construct(
private LoggerInterface $logger,
private Security $security,
private UserRepository $userRepository,
private EntityManagerInterface $entityManager,
// private UrlGeneratorInterface $urlGenerator,
private CsrfTokenManagerInterface $csrfTokenManager,
private RouterInterface $router)
{
}
public function supports(Request $request): bool
{
// dd('supports method is called');
return self::LOGIN_ROUTE === $request->attributes->get('_route') && $request->isMethod('POST');
}
// public function getCredentials(Request $request)
// {
// $credentials = [
// 'email' => $request->request->get('email'),
// 'password' => $request->request->get('password'),
// 'csrf_token' => $request->request->get('_csrf_token'),
// ];
// $this->logger->info('CSRF token: ' . $credentials['csrf_token']);
// $request->getSession()->set(
// SecurityRequestAttributes::LAST_USERNAME,
// $credentials['email']
// );
// return $credentials;
// }
// public function getUser($credentials, UserProviderInterface $userProvider)
// {
// $token = new CsrfToken('authenticate', $credentials['csrf_token']);
// if (!$this->csrfTokenManager->isTokenValid($token)) {
// throw new InvalidTokenException();
// }
// $user = $this->entityManager->getRepository(User::class)->findOneBy(['email' > $credentials['email']]);
// if (!$user) {
// throw new UserNotFoundException('Email could not be found');
// }
// return $user;
// }
public function authenticate(Request $request): Passport
{
$email = $request->request->get('email', '');
$request->getSession()->set(SecurityRequestAttributes::LAST_USERNAME, $email);
// dd(Passport)
return new Passport(
new UserBadge($email, function (string $userIdentifier) {
$user = $this->userRepository->findOneBy(['email' => $userIdentifier]);
if (!$user) {
throw new UserNotFoundException();
}
return $user;
}),
new PasswordCredentials($request->request->get('password', '')),
[
new CsrfTokenBadge('authenticate', $request->request->get('_csrf_token')),
new RememberMeBadge(),
]
);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
return new RedirectResponse($targetPath);
}
if ($this->security->isGranted('ROLE_ADMIN')) {
return new RedirectResponse($this->router->generate('app_admin'));
}
// dump('onAuthenticationSuccess is called');
// dump($this->router->generate('app_admin'));
return new RedirectResponse($this->router->generate('home_page'));
}
// public function start(Request $request, AuthenticationException $authException = null): Response
// {
// // add a custom flash message and redirect to the login page
// // $request->getSession()->getFlashBag()->add('note', 'You have to login in order to access this page.');
// return new RedirectResponse($this->router->generate('app_login'));
// }
protected function getLoginUrl(Request $request): string
{
return $this->router->generate(self::LOGIN_ROUTE);
}
}`
src/Controller/SecurityController.php
`<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
#[Route(path: '/login', name: 'app_login')]
public function login(AuthenticationUtils $authenticationUtils): Response
{
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
]);
}
#[Route(path: '/logout', name: 'app_logout')]
public function logout(): void
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
when@test:
security:
password_hashers:
# By default, password hashers are resource intensive and take time. This is
# important to generate secure password hashes. In tests however, secure hashes
# are not important, waste resources and increase test times. The following
# reduces the work factor to the lowest possible values.
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
algorithm: auto
cost: 4 # Lowest possible value for bcrypt
time_cost: 3 # Lowest possible value for argon
memory_cost: 10 # Lowest possible value for argon
`
templates/security/login.html.twig
`{# {% extends 'base.html.twig' %} #}
{% block stylesheets %}
{% endblock %}
<title>{% block title %}Log in!{% endblock %}</title>
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Error Output:
This page isn’t working127.0.0.1 redirected you too many times.
Try deleting your cookies.
ERR_TOO_MANY_REDIRECTS
src/Security/CustomAuthAuthenticator.php
`<?php
namespace App\Security;
use App\Entity\User;
use App\Exception\UserNotFoundException;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\InvalidTokenException;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\RememberMeBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\SecurityRequestAttributes;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
class CustomAuthAuthenticator extends AbstractLoginFormAuthenticator
{
use TargetPathTrait;
}`
src/Controller/SecurityController.php
`<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
#[Route(path: '/login', name: 'app_login')]
public function login(AuthenticationUtils $authenticationUtils): Response
{
$error = $authenticationUtils->getLastAuthenticationError();
}
`
config/packages/security.yaml
`security:
role_hierarchy:
ROLE_USER: ROLE_USER
ROLE_ADMIN: ROLE_ADMIN
ROLE_AUTHOR: ROLE_AUTHOR
when@test:
security:
password_hashers:
# By default, password hashers are resource intensive and take time. This is
# important to generate secure password hashes. In tests however, secure hashes
# are not important, waste resources and increase test times. The following
# reduces the work factor to the lowest possible values.
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
algorithm: auto
cost: 4 # Lowest possible value for bcrypt
time_cost: 3 # Lowest possible value for argon
memory_cost: 10 # Lowest possible value for argon
`
templates/security/login.html.twig
`{# {% extends 'base.html.twig' %} #}
{% block stylesheets %}
<title>{% block title %}Log in!{% endblock %}</title>{% endblock %}
{% block body %}
{% if error %}
{% endif %}
{% endblock %}
`
Beta Was this translation helpful? Give feedback.
All reactions