Команда make:auth
Команда make:auth создаёт основу для
аутентификации пользователей в приложении.
Она генерирует контроллер SecurityController
с методами login и logout,
Twig-шаблон формы входа и добавляет блок
firewalls в конфигурацию безопасности.
Команда входит в пакет symfony/maker-bundle
и доступна через консольный скрипт bin/console.
После генерации каркаса Symfony использует
встроенный аутентификатор form_login,
который принимает email и пароль из формы.
Для проверки учётных данных требуется сущность
пользователя, создаваемая командой make:user.
Синтаксис
php bin/console make:auth
Пример
Давайте запустим команду и выберем тип аутентификации:
php bin/console make:auth
What style of authentication do you want? [Empty authenticator]:
[0] Empty authenticator
[1] Login form authenticator
> 1
The class name of the authenticator to create (e.g. AppCustomAuthenticator):
> LoginFormAuthenticator
Choose a name for the controller class (e.g. SecurityController) [SecurityController]:
> SecurityController
Do you want to generate a '/logout' URL? (yes/no) [yes]:
> yes
created: src/Security/LoginFormAuthenticator.php
updated: config/packages/security.yaml
created: src/Controller/SecurityController.php
created: templates/security/login.html.twig
Success!
Пример
В результате команда создаёт контроллер
SecurityController с методами входа и выхода:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
use SymfonyComponentSecurityHttpAuthenticationAuthenticationUtils;
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.');
}
}
?>
Пример
Команда также создаёт Twig-шаблон формы входа:
{% extends 'base.html.twig' %}
{% 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 %}
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="username">Email</label>
<input type="email" value="{{ last_username }}" name="_username" id="username" class="form-control" autocomplete="email" required autofocus>
<label for="password">Password</label>
<input type="password" name="_password" id="password" class="form-control" autocomplete="current-password" required>
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
<button class="btn btn-lg btn-primary" type="submit">
Sign in
</button>
</form>
{% endblock %}
Пример
В config/packages/security.yaml добавляется
провайдер пользователей и брандмауэр с формой входа:
security:
password_hashers:
SymfonyComponentSecurityCoreUserPasswordAuthenticatedUserInterface: 'auto'
providers:
users_in_memory: { memory: null }
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: users_in_memory
form_login:
login_path: app_login
check_path: app_login
enable_csrf: true
logout:
path: app_logout
Смотрите также
-
команда
make:user,
которая создаёт класс пользователя -
команда
make:registration-form,
которая генерирует форму регистрации -
команда
make:reset-password,
которая создаёт сброс пароля -
команда
debug:firewall,
которая показывает настройки брандмауэра