Search code examples
phpsymfonysymfony-security

How to authenticate/authorize anonymous user for a limited time?


Let's say I have an invoice entity. Invoice belongs to some user (invoices.user_id).

If the user enters myapp.com/invoices/1 he needs to sign in to gain access to his invoice. That's pretty normal.

Sometimes invoices.user_id is null (invoice owner doesn't have an account in our system), but we have an invoices.phone_number column.

The goal is to create an authentication system based on SMS code verification for users that don't have the account in our system. If the user confirms that he indeed owns phone number related to the invoice (code verification) I want to grant him temporary access (15 min) to this invoice details page (and only this page).

My first idea was to use a JWT token stored in the session.

My second idea was to use a custom firewall.

Is there any better approach?


Solution

  • Create a kernel.request listener. This way you can act, before anything is executed, and whole application is oblivious to the fact that the user can be logged out any minute.

    Call a "service" which will validate the token. If the token is not valid, clear authentication status and override the request. For instance, redirect the user to a "you need to pay again" page.

    This way you don't need to modify any code, execute any voters and so on, your whole application can be protected.

    As for the authentication itself, go for a custom guard, where you can fully control how the authentication process will work.