Skip to content

Security ​

Sessions + password hashes + access rules - you already know the pieces. Symfony's Security component wires them into firewalls, authenticators, and IsGranted.

Mental model ​

  1. Firewall matches a path pattern (^/ or ^/admin)
  2. Authenticator checks credentials / session cookie
  3. User implements UserInterface (often via make:user)
  4. Access control / #[IsGranted] rejects unauthorized calls
  5. Logout clears the token / session

Same as the PHP tutorial sessions chapter - with YAML + attributes.

Make a user ​

bash
php bin/console make:user
php bin/console make:migration
php bin/console doctrine:migrations:migrate

You'll get an entity with email / password / roles (or similar) and a password hasher config.

Login form (Maker) ​

bash
php bin/console make:auth
# pick "Login form authenticator" while learning

That drops a security authenticator, login controller/template, and wires config/packages/security.yaml. Read the generated files - they're the curriculum 👌

Using the user in app code ​

php
<?php

$user = $this->getUser(); // null if anonymous

#[IsGranted('ROLE_USER')]
public function dashboard(): Response
{
    // …
}
twig
{% if app.user %}
  <p>Hi {{ app.user.userIdentifier }}</p>
{% endif %}

Protecting routes / controllers ​

yaml
# config/packages/security.yaml (illustrative)
access_control:
  - { path: ^/admin, roles: ROLE_ADMIN }
  - { path: ^/login, roles: PUBLIC_ACCESS }

Or attributes on controllers/methods - prefer whatever the generated code already uses so you don't fight two styles.

Voters (policies) ​

When "can this user edit this post?" isn't a simple role, write a Voter - same niche as Laravel Policies. Reach for them when role checks get soggy.

Passwords ​

php
<?php

$hashed = $passwordHasher->hashPassword($user, $plain);
$passwordHasher->isPasswordValid($user, $plain);

Underneath: modern password hashing algorithms - your password_hash knowledge still applies.

Next: JSON APIs without reinventing serialization.

Best,

-- ł.

Continues after /lab/php-tutorial-for-fe-devs/