103 lines
2.6 KiB
Markdown
103 lines
2.6 KiB
Markdown
# User Authentication
|
|
|
|
## Create a user class
|
|
|
|
Permissions are linked to a user object.
|
|
|
|
```bash
|
|
symfony console make:user # (All default yes)
|
|
symfony console make:auth # (1 for login form)
|
|
symfony console make:registration-form
|
|
symfony console make:reset-password
|
|
```
|
|
Now you will want to sync the database (using docker)
|
|
|
|
```bash
|
|
sudo docker-compose run symfony php bin/console make:migration
|
|
sudo docker-compose run symfony php bin/console doctrine:migrations:migrate
|
|
```
|
|
Note: 'symfony' is the name of your symfony app in docker-compose (such as app)
|
|
|
|
## Login Form
|
|
|
|
The above already created this.
|
|
|
|
```php bin/console make:controller Login```
|
|
|
|
You have to add
|
|
```yaml
|
|
form_login:
|
|
login_path: app_login
|
|
check_path: app_login
|
|
```
|
|
to the firewalls section under main of config/packages/security.yaml
|
|
|
|
### Modify the controller
|
|
|
|
```php
|
|
<?php
|
|
|
|
namespace App\Controller;
|
|
|
|
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
use Symfony\Component\Routing\Annotation\Route;
|
|
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
|
|
|
|
class LoginController extends AbstractController
|
|
{
|
|
#[Route('/login', name: 'app_login')]
|
|
public function index(AuthenticationUtils $authenticationUtils): Response
|
|
{
|
|
$error = $authenticationUtils->getLastAuthenticationError();
|
|
$lastUsername = $authenticationUtils->getLastUsername();
|
|
|
|
return $this->render('login/index.html.twig', [
|
|
'last_username' => $lastUsername,
|
|
'error' => $error,
|
|
]);
|
|
}
|
|
}
|
|
```
|
|
|
|
### Modify the template
|
|
```php
|
|
{% extends '@nytwig/master.html.twig' %}
|
|
|
|
{% block title %}Hello LoginController!{% endblock %}
|
|
|
|
{% block content %}
|
|
{% if error %}
|
|
<div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
|
|
{% endif %}
|
|
|
|
<form action="{{ path('app_login') }}" method="post">
|
|
<label for="username">Email:</label>
|
|
<input type="text" id="username" name="_username" value="{{ last_username }}"/>
|
|
|
|
<label for="password">Password:</label>
|
|
<input type="password" id="password" name="_password"/>
|
|
|
|
{# If you want to control the URL the user is redirected to on success
|
|
<input type="hidden" name="_target_path" value="/account"/> #}
|
|
|
|
<button type="submit">login</button>
|
|
</form>
|
|
|
|
{% endblock %}
|
|
```
|
|
|
|
## Loggging Out
|
|
|
|
https://symfony.com/doc/current/security.html#logging-out
|
|
|
|
|
|
## Access Control (Authorization)
|
|
|
|
https://symfony.com/doc/current/security.html#access-control-authorization
|
|
|
|
## References
|
|
|
|
* https://symfony.com/doc/current/security.html
|
|
* https://dev.to/nabbisen/symfony-6-user-authentication-4ek
|