Using HTTP Basic Authentication in Symfony 7

Using HTTP Basic Authentication in Symfony 7

HTTP Basic authentication is a simple authentication technique for restricting access to web pages. User should provide username and password using a dialog in the web browser.

This tutorial provides example how to use HTTP Basic authentication in Symfony 7 application.

In Symfony application, HTTP basic authenticator is responsible to verify provided credentials. It can be configured in services.yaml file using http_basic parameter in the firewalls section.

config/packages/security.yaml

security:
  password_hashers:
    Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: plaintext
  providers:
    in_memory_users:
      memory:
        users:
          - identifier: '%env(HTTP_BASIC_AUTH_USERNAME)%'
            password: '%env(HTTP_BASIC_AUTH_PASSWORD)%'
            roles: [ ROLE_USER ]
  firewalls:
    main:
      pattern: ^/
      http_basic: ~
  access_control:
    - { path: ^/, roles: [ ROLE_USER ] }

For simplicity, we use memory user provider with plain text password. Username and password can be provided in the .env file.

.env

HTTP_BASIC_AUTH_USERNAME=admin
HTTP_BASIC_AUTH_PASSWORD=pwd123

We configured that authentication should be required for all URLs. The following controller can be used for testing:

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController extends AbstractController
{
    #[Route('/')]
    public function index(): Response
    {
        return new Response('Hi '.$this->getUser()?->getUserIdentifier());
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.