在我的新 symfony 5.3 專案中,我剛剛實施了新的身份驗證系統,并且作業正常,但我的問題是我無法自定義身份驗證錯誤:
在該方法中:onAuthentificationFailure在AbstractLoginFormAuthenticator 但我認為它僅顯示這是正常的,因為我的控制器呼叫會話錯誤getLastAuthenticationError()方法。
但是如何 在我的視圖中顯示來自我的CustomUserMessageAuthenticationException 的自定義錯誤 ?
我的 AbstractLoginFormAuthenticator
namespace Symfony\Component\Security\Http\Authenticator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
/**
* A base class to make form login authentication easier!
*
* @author Ryan Weaver <ryan@symfonycasts.com>
*/
abstract class AbstractLoginFormAuthenticator extends AbstractAuthenticator implements AuthenticationEntryPointInterface, InteractiveAuthenticatorInterface
{
/**
* Return the URL to the login page.
*/
abstract protected function getLoginUrl(Request $request): string;
/**
* {@inheritdoc}
*
* Override to change the request conditions that have to be
* matched in order to handle the login form submit.
*
* This default implementation handles all POST requests to the
* login path (@see getLoginUrl()).
*/
public function supports(Request $request): bool
{
return $request->isMethod('POST') && $this->getLoginUrl($request) === $request->getPathInfo();
}
/**
* Override to change what happens after a bad username/password is submitted.
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response
{
if ($request->hasSession()) {
//$request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
throw new CustomUserMessageAuthenticationException('error custom ');
}
$url = $this->getLoginUrl($request);
return new RedirectResponse($url);
}
/**
* Override to control what happens when the user hits a secure page
* but isn't logged in yet.
*/
public function start(Request $request, AuthenticationException $authException = null): Response
{
$url = $this->getLoginUrl($request);
return new RedirectResponse($url);
}
public function isInteractive(): bool
{
return true;
}
}
我的安全控制器:
namespace App\Controller;
use App\Entity\User;
use DateTimeImmutable;
use App\Form\RegistrationType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class SecurityController extends AbstractController {
/**
* @Route("/test", name="test")
*/
public function test(Request $request, Response $response){
return $this->render('test.html.twig');
dump($response);
}
/**
* @Route("/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
// if ($this->getUser()) {
// return $this->redirectToRoute('target_path');
// }
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
/**
* @Route("/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.');
}
/**
* @Route("/Inscription", name="registration")
*/
public function registration(EntityManagerInterface $manager, Request $request, UserPasswordHasherInterface $passwordEncoder): Response
{
$user = new User;
$registrationForm = $this->createForm(RegistrationType::class, $user);
$registrationForm->handleRequest($request);
if($registrationForm->isSubmitted() && $registrationForm->isValid()){
$plainPassword = $registrationForm->getData()->getPassword();
$user->setPassword($passwordEncoder->hashPassword($user, $plainPassword));
$user->setCreatedAt( new \DateTimeImmutable('NOW'));
$user->setRoles($user->getRoles());
$manager->persist($user);
$manager->flush();
}
return $this->render('security/registration.html.twig',
['registrationForm' => $registrationForm->createView()]);
}
}
我的觀點樹枝(登錄資訊):
{% block title %}Log in!{% endblock %}
{% block body %}
<form method="post">
{% if error %}
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
{% if app.user %}
<div class="mb-3">
You are logged in as {{ app.user.username }}, <a href="{{ path('app_logout') }}">Logout</a>
</div>
{% endif %}
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="inputEmail">Email</label>
<input type="email" value="{{ last_username }}" name="email" id="inputEmail" hljs-string">" autocomplete="email" required autofocus>
<label for="inputPassword">Password</label>
<input type="password" name="password" id="inputPassword" hljs-string">" autocomplete="current-password" required>
<input type="hidden" name="_csrf_token"
value="{{ csrf_token('authenticate') }}"
>
{#
Uncomment this section and add a remember_me option below your firewall to activate remember me functionality.
See https://symfony.com/doc/current/security/remember_me.html
<div hljs-number">3">
<label>
<input type="checkbox" name="_remember_me"> Remember me
</label>
</div>
#}
<button hljs-string">" type="submit">
Sign in
</button>
</form>
{% endblock %}
uj5u.com熱心網友回復:
您應該擴展和覆寫而AbstractLoginFormAuthenticator不是直接修改它。
為什么你的方法不起作用
簡而言之,您需要在到達 Exception 之前拋出 Exception onAuthenticationFailure(),因為這AuthenticationException就是onAuthenticationFailure()Symfony 呼叫的原因。
該onAuthenticationFailure()方法是處理AuthenticationException從AuthenticatorManager::executeAuthenticator()行程中拋出的。
try {
// get the passport from the Authenticator
$passport = $authenticator->authenticate($request);
//...
} catch (AuthenticationException $e) {
// oh no! Authentication failed!
$response = $this->handleAuthenticationFailure($e, $request, $authenticator, $passport);
// ...
}
//...
private function handleAuthenticationFailure(AuthenticationException $authenticationException, Request $request, AuthenticatorInterface $authenticator, ?PassportInterface $passport): ?Response
{
// Avoid leaking error details in case of invalid user (e.g. user not found or invalid account status)
// to prevent user enumeration via response content comparison
if ($this->hideUserNotFoundExceptions && ($authenticationException instanceof UsernameNotFoundException || ($authenticationException instanceof AccountStatusException && !$authenticationException instanceof CustomUserMessageAccountStatusException))) {
$authenticationException = new BadCredentialsException('Bad credentials.', 0, $authenticationException);
}
$response = $authenticator->onAuthenticationFailure($request, $authenticationException);
//...
}
默認功能AbstractLoginFormAuthenticator::onAuthenticationFailure()的用途$request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);是什么是例外增加的訊息,那就是通過呼叫檢索AuthenticationUtils::getLastAuthenticationError();該呼叫$session->get(Security::AUTHENTICATION_ERROR);
public function getLastAuthenticationError(bool $clearSession = true)
{
$request = $this->getRequest();
$authenticationException = null;
//...
if ($request->hasSession() && ($session = $request->getSession())->has(Security::AUTHENTICATION_ERROR)) {
$authenticationException = $session->get(Security::AUTHENTICATION_ERROR);
//...
}
return $authenticationException;
}
如何顯示自定義錯誤訊息
應用程式中有多個點被呼叫,您可以在其中拋出傳遞給 的例外onAuthenticationFailure()。
默認情況下,Symfony 使用安全配置設定來生成通用訊息,但可以通過在您的類中實作它們來覆寫。
由于例外被上述條件覆寫。
if ($this->hideUserNotFoundExceptions && !$e instanceof CustomUserMessageAccountStatusException) {
throw new BadCredentialsException('Bad credentials.', 0, $e);
}
您將需要禁用hide_user_not_found,否則CustomUserMessageAuthenticationException將被替換為BadCredentialsException('Bad credentials.')例外。
否則跳過禁用hide_user_not_found并拋出CustomUserMessageAccountStatusException而不是CustomUserMessageAuthenticationException.
# /config/packages/security.yaml
security:
# ...
hide_user_not_found: false
firewalls:
# ...
在Authenticator 類中
有關最新的使用參考,請閱讀默認的FormLoginAuthenticator. 由于 Symfony Casts 站點上的教程尚未針對 Symfony 5 進行更新。
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
class MyLoginFormAuthenticator extends AbstractLoginFormAuthenticator
{
//...
public function getCredentials(Request $request)
{
//...
throw new CustomUserMessageAuthenticationException('Custom Error');
}
public function authenticate(Request $request): PassportInterface
{
//general usage of how the other exceptions are thrown here
$credentials = $this->getCredentials($request);
$method = 'loadUserByIdentifier';
$badge = new UserBadge($credentials['username'], [$this->userProvider, $method]),
$user = $badge->getUser(); //UserRepository::loadUserByIdentifier()
//...
throw new CustomUserMessageAuthenticationException('Custom Error');
}
}
在UserProvider 類中
class UserRepository extends ServiceEntityRepository implements UserProviderInterface
{
//....
public function loadUserByIdentifier(string $identifier)
{
throw new CustomUserMessageAuthenticationException('Custom Error');
//...
}
public function loadUserByUsername(string $username)
{
return $this->loadUserByIdentifier($username);
}
}
在UserChecker 類中
use Symfony\Component\Security\Core\User\{UserCheckerInterface, UserInterface};
class UserChecker implements UserCheckerInterface
{
public function checkPreAuth(UserInterface $user): void
{
throw new CustomUserMessageAuthenticationException('Custom Error');
//...
}
public function checkPostAuth(UserInterface $user): void
{
throw new CustomUserMessageAuthenticationException('Custom Error');
//...
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/343631.html
