Symfony Lab 4: authentication

Implementing UserInterface and PasswordAuthenticatedUserInterface

First, our users need to implement Symfony's UserInterface interface (use Symfony\Component\Security\Core\User\UserInterface;) as well as PasswordAuthenticatedUserInterface.

To do so, add the following code (the missing methods) to User:

public function getUserIdentifier(): string { return $this->getEmail(); }
public function getRoles(): array { return ['ROLE_USER']; }
public function eraseCredentials(): void { }

Configuring security

In Lab 2, users were configured automatically. Here, however, the user entity was imported from the database. You can configure security like this (config/packages/security.yaml):

security:
    ...
    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email
    ...

And change the provider from users_in_memory to app_user_provider.

Logging in

You can automatically generate the security controller using the command:

symfony console make:auth

Open the generated file (for example AppAuthenticator.php). Edit the code so that the user is redirected to series_index after logging in.

Registration

Use the make:registration command. As in Lab 2, answer no to the question offering to send e-mails.

Test the registration form. To make it work, you will need to add the name field.

Then go to /login and /logout, and logging in should work!

Menu

Set up a menu, in which you will display, among other things, "log in" and "register" when the user is logged out, and "log out" when the user is logged in.

Access restriction

Protect some pages, such as the list of series made during the previous lab, which will then only be visible to logged-in users.

To do so, you can edit the security.yaml file, and in particular its access_control section.

Followed series

Using the series association of the User entity (stored in the user_series table in the database), make it possible for a user to "follow" a series (which will then be associated with them) or stop following a series.

When they visit the series page, they will see whether they follow it or not.

Create a page displaying the list of series followed by the user