Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

composer require seguridad

Video not working?

It looks like your browser may not support the H264 codec. If you're using Linux, try a different browser or try installing the gstreamer0.10-ffmpeg gstreamer0.10-plugins-good packages.

Thanks! This saves us from needing to use Flash or encode videos in multiple formats. And that let's us get back to making more videos :). But as always, please feel free to message us.

¡Bienvenidos de nuevo amigos! Estoy muy contento de que hayáis tropezado con mi tutorial de seguridad de Symfony 5 por un montón de razones. La primera es que, bueno... eh... el sitio que hemos estado construyendo NO tiene seguridad... y los rapaces están empezando a sacudir los pomos de las puertas.

La otra razón es que, una vez que lleguemos al cobertizo de mantenimiento en el otro lado del recinto, vamos a explorar el nuevo sistema de seguridad de Symfony, llamado sistema "autentificador". Ooh. Si has utilizado el sistema antiguo, te sentirás como en casa. Si eres nuevo en la seguridad de Symfony, has elegido un buen momento para empezar. El nuevo sistema es más fácil de aprender y entender... pero también es más potente.

Configuración del Proyecto

Y como el sistema de seguridad no se va a poner en marcha por sí solo, pongámonos a trabajar. Para aprender a autenticar, autorizar y hacer otras cosas interesantes de seguridad a nivel profesional, deberías descargar el código del curso desde esta página y codificar conmigo. Cometer errores en el mundo real.... sí, es la mejor manera de recordar estas cosas.

Después de descomprimir el archivo, encontrarás un directorio start/ con el mismo código que ves aquí. Abre el archivo README.md para obtener todas las instrucciones de configuración. El último paso será buscar un terminal, entrar en el proyecto e iniciar un servidor web. Para ello voy a utilizar el binario symfony:

symfony serve -d

Esto inicia un nuevo servidor en https://127.0.0.1:8000. Ábrelo en tu navegador... o sé perezoso y ejecuta

symfony open:local

para... "delegar" el trabajo a otra persona. ¡Saluda a Cauldron Overflow! Un sitio de preguntas y respuestas para brujas y magos, que... por desgracia... siguen lanzando sus hechizos en directo en producción sin probarlos... y normalmente un viernes por la tarde. Por supuesto. Luego vienen aquí a preguntar cómo deshacer el daño.

Instalando Seguridad

Como la filosofía de Symfony es empezar poco a poco y permitirte instalar las cosas que necesitas más tarde, ahora mismo nuestra aplicación... no tiene literalmente un sistema de seguridad.

Eso no es divertido, ¡así que vamos a instalar uno! Vuelve a tu terminal y ejecuta:

composer require security

Esto instala el paquete de seguridad de Symfony. Cuando termine... ejecuta

git status

para ver lo que hizo su receta. Además de las cosas normales, ha añadido un nuevo archivo de configuración: security.yaml. Vamos a comprobarlo:config/packages/security.yaml:

security:
# https://symfony.com/doc/current/security/authenticator_manager.html
enable_authenticator_manager: true
# https://symfony.com/doc/current/security.html#c-hashing-passwords
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
users_in_memory: { memory: null }
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: users_in_memory
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#firewalls-authentication
# https://symfony.com/doc/current/security/impersonating_user.html
# switch_user: true
# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
# - { path: ^/admin, roles: ROLE_ADMIN }
# - { path: ^/profile, roles: ROLE_USER }

Como habrás adivinado por su nombre, ¡este archivo alimenta el sistema de seguridad! Cuando terminemos, cada sección de aquí te resultará sencilla y aburrida. Me encanta cuando las cosas de programación son aburridas.

enable_authenticator_manager

Oh, ¿pero ves esta clave enable_authenticator_manager?

security:
# https://symfony.com/doc/current/security/authenticator_manager.html
enable_authenticator_manager: true
... lines 4 - 29

En Symfony 5.3 -la versión que estoy utilizando- los sistemas de seguridad antiguos y nuevos conviven y puedes elegir cuál quieres Cuando ponesenable_authenticator_manager en true, estás activando el nuevo sistema. ¡Sí! ¡Brillante! Si estás trabajando en un proyecto heredado y necesitas aprender el sistema antiguo, echa un vistazo a nuestro tutorial Seguridad en Symfony 4. ¡También es muy bueno!

Autenticación y Autorización

De todos modos, cuando se habla de seguridad, hay dos grandes partes: la autenticación y la autorización. La autenticación plantea la pregunta "¿quién eres? Y "¿puedes demostrarlo?" Los usuarios, los formularios de inicio de sesión, las cookies "recuérdame", las contraseñas, las claves API... todo eso está relacionado con la autenticación.

La autorización plantea una pregunta diferente: "¿Deberías tener acceso a este recurso?" A la autorización no le importa mucho quién eres... se trata de permitir o denegar el acceso a diferentes cosas, como diferentes URLs o controladores.

En Symfony, o realmente en cualquier sistema de seguridad, la autenticación es la parte complicada. Quiero decir, ¡sólo piensa en cuántas formas hay de autenticarse! Formularios de inicio de sesión, autenticación con tokens de la API, autenticación social con OAuth, SSO, LDAP, ponerse un bigote falso y pasar con confianza por delante de un guardia de seguridad. Es decir... las posibilidades son infinitas. Pero también creo que la autenticación es súper divertida.

Así que a continuación: vamos a empezar nuestro viaje hacia el nuevo y brillante sistema de autenticación creando la parte más básica de la autenticación: una clase de usuario.

Leave a comment!

30
Login or Register to join the conversation
discipolat Avatar
discipolat Avatar discipolat | posted hace 3 meses

Hi. I've a problem with the security system. My app was working 100%, but after reinstalling my windows 10 and then php 8.1... i'm unable to pass the login form. I've this anwser from my local server : " Warning: session_regenerate_id(): Session object destruction failed. ID: user (path: C:\xampp\tmp)"". Any solution...orientation?

Reply

Hey discipolat!

Hm, sounds like something internal to your laptop, most probably some misconfiguration of the XAMP, especially if. you did not do any changes to the source code of your project. I'd recommend you to re-install XAMP, it might help I think. If not, it seems like you have problems with session - you can try to store session in a different place, e.g. in your DB (at least locally), it might be a good workaround, but not perfect storing session in different places locally and on prod :/ Another solution - try to use a different from XAMP web server. Actaully, I'd recommend you to use the built in Symfony web server that you can start with "symfony serve" command - all you need to have is Symfony CLI and PHP installed. You may still spin the XAMP for MySQL if you get used to it, but do not use the webserver that causes issues now.

So, those are some tips, I hope something will be helpful for you.

Cheers!

Reply
discipolat Avatar

Hi Victor, Thank's for all!
I've try the reinstallation solution but not working i don't know why....strange. I've even switch from Php 8.1 to 7.4 with xampp but same status.
So i've try to strore sessions elsewhere according to https://symfony.com/doc/4.4/session/database.html#store-sessions-in-a-relational-database-mariadb-mysql-postgresql and it working now.
Thank's.

1 Reply

Hey Discipolat,

Cool, I'm happy to hear you found a workaround for this! I understand it's not perfect (and not convenient probably) but sometimes things go weird on Windows, unfortunately. It might be a permissions issue (most probably). If you want to try to fix it correctly - probably google the error you see, it might be some tips on the internet.

Otherwise, I'd recommend you to take a look at the Windows WSL feature - some Windows guys in our team are using it and say that it's awesome :)

I hope this helps!

Cheers!

Reply
discipolat Avatar

Hi Victor,
the 'problem' was pretty simple in reality !
As you said, it was just a permissions issue. I've just act on permissions and things works fine.

Thank's!

Reply

Hey Discipolat,

Awesome! Glad you figured it out :) And thanks for posting the real issue after all, it might be helpful for others.

Cheers!

1 Reply
discipolat Avatar

Hi Victor,

Thank's very much.

Reply
Rufnex Avatar

On Symfony 6 the "enable_authenticator_manager" isn't longer in use? Right?

Reply

Hey, Rufnex

It is set to true by default, so you don't have to configure anything to use the new security system

Cheers!

1 Reply
Rufnex Avatar

Thank you.

Reply
davidmintz Avatar
davidmintz Avatar davidmintz | posted hace 1 año

I'm happy to report solutions to a problem some people may encounter. If you are running PHP 8.1, composer cannot install.

You can install php-fpm7.4 or 8.0 alongside php-fpm8.1 on the same machine and use update-alternatives (on Debian-ish systems) to switch php versions, and this seems a sane option. I have done this to roll back to 8.0 and it works fine.

Another alternative is to use Devilbox It's a little more involved, but it's kind of cool.

Reply

Hi davidmintz

Another workaround will be to update

laminas/laminas-code

package to unblock php 8.1
So you can install everything with

composer update laminas/laminas-code command

Cheers! and thanks again for the reporting
Reply

Hey David,

Thank you for reporting this! We will take a look at the course code and probably apply some fixes to make it possible to run the code on PHP 8.1

And thanks for the tips on how to workaround this problem!

Cheers!

Reply
Oliver-W Avatar
Oliver-W Avatar Oliver-W | posted hace 1 año

Hi,

any idea why I get "an error occured while loading the web debug toolbar" from the very beginning? The page itself is displayed but no debug toolbar.

I alreday cleared the diretory vendor\cache. No changes.
Ah, I even tried do download the code once again today. No changes.
Trying to open /answers/popular brings an 404.

Starting composer require annotations brings no changes.

What else can I look for?

By the way: I am working on a local XAMPP. But in other projects the debug toolbar works fine.

Thx
Oliver

Reply
Oliver-W Avatar

got it: it's that weird thing called .htaccess.

Reply

Hey Oliver,

Oh, yeah, it might be .htaccess. I'd recommend you to use Symfony's built-in server for developing purposes locally, but if you do want to use XAMPP that runs real Apache web server - I'd advice you to install "symfony/apache-pack" dependency that will bring the default Symfony .htaccess into your project, though you might still want to tweak it, depends on your local configuration.

I hope this helps!

Cheers!

1 Reply
chessserver Avatar
chessserver Avatar chessserver | posted hace 1 año

Is there a guide or howto or something similar which explains the migration from GuardAuthentication to the new system? It seems that it runs on Symfony 5.4, but won´t with Symfony 6 (that is my understanding). Can you add one or two lessons about the migration?

Reply
Oliver-W Avatar
Oliver-W Avatar Oliver-W | posted hace 1 año

Hi,

when trying to runsymfony console doctrine:migrations:migrate I keep getting this as error:

[notice] Migrating up to DoctrineMigrations\Version20210907192620

[error] Migration DoctrineMigrations\Version20210902182514 failed during Execution. Error: "An exception occurred while executing 'ALTER TABLE answer RENAME INDEX idx_9474526c1e27f6bf TO IDX_DADD4A251E27F6BF':

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INDEX idx_9474526c1e27f6bf TO IDX_DADD4A251E27F6BF' at line 1"

In AbstractMySQLDriver.php line 98:

An exception occurred while executing 'ALTER TABLE answer RENAME INDEX idx_9474526c1e27f6bf TO IDX_DADD4A251E27F6BF':

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INDEX idx_9474526c1e27f6bf TO IDX_

DADD4A251E27F6BF' at line 1

I am working with XAMPP with PHP 7.4.9 and MariaDB 10.4.14. In my .env i noted ...serverVerion=mariadb-10.4.14 which works fine for other Smyfony projects.

By the way: when submitting ALTER TABLE answer RENAME INDEX idx_..... directly on the server it tells me that a comma is missing just before start of a new alter operation (near "TO")!?!?!?

What goes wrong?

Thx
Oliver

Reply

To anyone having this issue, for me the easiest solution is to erase the files on the migrations folder, and run "symfony console make:migration" to generate a new one before executing "symfony console doctrine:migrations:migrate" .

Cheers!

Reply

Hey Miguel,

Thank you for this tip! Yeah, it sounds like a good workaround. Or, you can even simplify this by just running bin/console doctrine:schema:update --force - both ways are good for learning purposes when you do not afraid to lose data in your local database. But for production - probably neither of these options will fit.

Cheers!

Reply

Hey Oliver W.

Your version of MariaDB does not allow to rename an index, here's a related issue to your problem https://github.com/PomeloFo...

You can tweak the query to regenerate the index instead, or, you could upgrade your database version, I believe the "RENAME INDEX" operation is supported by the latest MariaDB version

Cheers!

Reply
Oliver-W Avatar

thx, I've been changing the name of the idex manually and manipulated the migrations table. So it finally worked.

Reply
Christopher S. Avatar
Christopher S. Avatar Christopher S. | posted hace 1 año

Hi, I've tried setting up the project like the readme describes. I'm able to start the docker, but when I want to create a database using the symfony console command I get "SQLSTATE[HY000] [2002] Connection refused" as a response in the console.

Reply

Hey Daniel,

Please, double check your DB credentials in .env and .env.local files. Looks like they are not valid for your specific MySQL server. Tweak them to the correct ones and try again :)

Cheers!

Reply
Tomáš K. Avatar
Tomáš K. Avatar Tomáš K. | Victor | posted hace 1 año

Hi Victor,

this could be an issue with the initial docker-compose.yaml file

I actually got the same error message as Daniel but I figured out that the issue might be about naming of the database service. In the pre-generated docker-compose.yaml the service name was secure_db, while on other projects I had database. By simply renaming the service, removing and restarting the docker container and clearing symfony cache i got it work.

Reply

Hey Tomik!

Thank you for the tips how to fix things!

Yeah, naming might be different on different courses, that's why we recommend to download a new course code and start coding with us from start/ directory. Except some naming things, we may add more changes between courses, like upgrading dependencies, slightly changing code to have better use cases that we will cover in the videos, etc. So, if you continue the course code from a past tutorial, you may have differences between your code after a past tutorial and the code we show in the new course.

Cheers!

2 Reply
Art A. Avatar

I'm using symfony 5.2 whit two type authentication using email & password and google oAuth. When I enable enable_authenticator_manager=true it comes out the error: 'you can not user enable_authenticator_manager with oAuth'. Not sure why enable_authenticator_manager does not work with oAuth

Reply

Hey Art A.!

What bundle are you using that gives you the OAuth support? Bundles need to add support for the new "authenticator" system. It's actually quite easy... but if the bundle hasn't done it yet, then it needs to :).

Cheers!

Reply
Jf senechal Avatar
Jf senechal Avatar Jf senechal | posted hace 1 año

There is a small typo : require and not requires ;-)

Reply

Hey Jf,

Thanks for reporting this! I fixed this misprint in https://github.com/SymfonyC...

Cheers!

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

¡Este tutorial también funciona muy bien para Symfony 6!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": "^7.4.1 || ^8.0.0",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "babdev/pagerfanta-bundle": "^3.3", // v3.3.0
        "composer/package-versions-deprecated": "^1.11", // 1.11.99.4
        "doctrine/annotations": "^1.0", // 1.13.2
        "doctrine/doctrine-bundle": "^2.1", // 2.6.3
        "doctrine/doctrine-migrations-bundle": "^3.0", // 3.1.1
        "doctrine/orm": "^2.7", // 2.10.1
        "knplabs/knp-markdown-bundle": "^1.8", // 1.9.0
        "knplabs/knp-time-bundle": "^1.11", // v1.16.1
        "pagerfanta/doctrine-orm-adapter": "^3.3", // v3.3.0
        "pagerfanta/twig": "^3.3", // v3.3.0
        "phpdocumentor/reflection-docblock": "^5.2", // 5.2.2
        "scheb/2fa-bundle": "^5.12", // v5.12.1
        "scheb/2fa-qr-code": "^5.12", // v5.12.1
        "scheb/2fa-totp": "^5.12", // v5.12.1
        "sensio/framework-extra-bundle": "^6.0", // v6.2.0
        "stof/doctrine-extensions-bundle": "^1.4", // v1.6.0
        "symfony/asset": "5.3.*", // v5.3.4
        "symfony/console": "5.3.*", // v5.3.7
        "symfony/dotenv": "5.3.*", // v5.3.8
        "symfony/flex": "^1.3.1", // v1.17.5
        "symfony/form": "5.3.*", // v5.3.8
        "symfony/framework-bundle": "5.3.*", // v5.3.8
        "symfony/monolog-bundle": "^3.0", // v3.7.0
        "symfony/property-access": "5.3.*", // v5.3.8
        "symfony/property-info": "5.3.*", // v5.3.8
        "symfony/rate-limiter": "5.3.*", // v5.3.4
        "symfony/runtime": "5.3.*", // v5.3.4
        "symfony/security-bundle": "5.3.*", // v5.3.8
        "symfony/serializer": "5.3.*", // v5.3.8
        "symfony/stopwatch": "5.3.*", // v5.3.4
        "symfony/twig-bundle": "5.3.*", // v5.3.4
        "symfony/ux-chartjs": "^1.3", // v1.3.0
        "symfony/validator": "5.3.*", // v5.3.8
        "symfony/webpack-encore-bundle": "^1.7", // v1.12.0
        "symfony/yaml": "5.3.*", // v5.3.6
        "symfonycasts/verify-email-bundle": "^1.5", // v1.5.0
        "twig/extra-bundle": "^2.12|^3.0", // v3.3.3
        "twig/string-extra": "^3.3", // v3.3.3
        "twig/twig": "^2.12|^3.0" // v3.3.3
    },
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.3", // 3.4.0
        "symfony/debug-bundle": "5.3.*", // v5.3.4
        "symfony/maker-bundle": "^1.15", // v1.34.0
        "symfony/var-dumper": "5.3.*", // v5.3.8
        "symfony/web-profiler-bundle": "5.3.*", // v5.3.8
        "zenstruck/foundry": "^1.1" // v1.13.3
    }
}