Mettre en place une authentification symfony
Authentification avec formulaire de connexion
- Creation du projet
composer create-project symfony/website-skeleton auth-symfony
cd auth-symfony/
- Creation utilisateur
php bin/console m:user
- Creation authentification
php bin/console m:auth
- Migrations
Configurer le .env avec les informations sur la base de données (exemple base sqlite)
DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
Creation de la base
php bin/console d:d:c
php bin/console m:m
php bin/console d:m:m
- Creation du crud utilisateur
php bin/console m:crud
Attention la route /user/new ne permet pas de hasher le password par defaut. Vous avez 2 options :
-
Modifier le controller
-
créer un formulaire de registration (étape 6)
- Creation du formulaire de registration
php bin/console m:registration-form
Pour visualiser les toutes routes du projet
php bin/console debug:router
Authentification avec token jwt
L’authentification token nécessite l’implementation d’une authentification classique. reportez vous au étape 1 à 4 de la partie précédente.
- dependencies
composer req "lexik/jwt-authentication-bundle"
- Generate ssh key
mkdir config/jwt
openssl genrsa -out config/jwt/private.pem -aes256 4096
openssl rsa -pubout -in config/jwt/private.pem -out config/jwt/public.pem
chmod 777 config/jwt/*
La première fois il faut faire :
openssl rsa -in config/jwt/private.pem -out config/jwt/private2.pem
mv config/jwt/private.pem config/jwt/private.pem-back
mv config/jwt/private2.pem config/jwt/private.pem
- Create routes
edit config/routes.yml
register:
path: /register
controller: App\Controller\AuthController::register
methods: POST
api:
path: /api
controller: App\Controller\AuthController::api
login_check:
path: /login_check
methods: [POST]
create src/Controller/AuthController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Entity\User;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class AuthController extends AbstractController
{
public function register(Request $request, UserPasswordEncoderInterface $encoder)
{
$em = $this->getDoctrine()->getManager();
$username = $request->request->get('_username');
$password = $request->request->get('_password');
$user = new User();
$user->setUsername($username);
$user->setPassword($encoder->encodePassword($user, $password));
$em->persist($user);
$em->flush();
return new Response(sprintf('User %s successfully created', $user->getUsername()));
}
public function api()
{
return new Response(sprintf('Logged in as %s', $this->getUser()->getUsername()));
}
}
complete config/packages/security.yaml
security:
encoders:
App\Entity\User:
algorithm: bcrypt
providers:
entity_provider:
entity:
class: App\Entity\User
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/login
stateless: true
anonymous: true
json_login:
check_path: /login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
register:
pattern: ^/register
stateless: true
anonymous: true
api:
pattern: ^/api
stateless: true
anonymous: false
provider: entity_provider
guard:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
Utilisation
- Démarer le serveur
php bin/console server:start
- Enregistrer un nouvel utilisateur
curl -X POST http://localhost:8000/register -d _username=johndoe -d _password=test
User johndoe successfully created
- Recupérer son token
curl -X POST -H "Content-Type: application/json" http://localhost:8000/login_check -d '{"username":"johndoe","password":"test"}'
{ "token": "[TOKEN]" }