Symfony HTTP Basic authentication quick guide

2022-10-21
4.1 / 5 (12 votes)

It will be a short article on how to turn on HTTP Basic authentication in your Symfony project. The main task is to protect our API endpoint from outsiders and allow us to send requests only if you know the login/password. It should be only one client "in memory" without any external DB connections.

Of course, we could use an IP firewall, which would be a more secure solution, but not this time. The Symfony framework has good documentation, but in our case, you will only see a few lines in the config that will not help you at all.

Why wouldn't that help? Because these changes will enable HTTP Basic authentication for all your clients if you have them. You also need to understand what type of "password_hasher" and what "provider" you should use.

So if you want to make it as easy as possible, copy the config below, and everything will work. You only need to add one variable "BASIC_USER_PASSWORD" into your .env file with the password.

.env

###> symfony/security-bundle ###
BASIC_USER_PASSWORD=test
###< symfony/security-bundle ###
config/packages/security.yaml

security:
    password_hashers:
        Symfony\Component\Security\Core\User\InMemoryUser: plaintext

    providers:
        users_in_memory:
            memory:
                users:
                    api: {password: '%env(BASIC_USER_PASSWORD)%', roles: ['ROLE_API']}
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            lazy: true
            provider: users_in_memory
            http_basic:
                realm: Secured Area

    access_control:
         - { path: ^/api, roles: ROLE_API }

Useful links below

Hashers - https://symfony.com/doc/current/security/passwords.html#the-auto-hasher
Providers - https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
Access Control - https://symfony.com/doc/current/security/access_control.html
Firewalls - https://symfony.com/doc/current/security.html#http-basic

Example of curl request (api:test)
curl --location --request POST 'https://your_site.com/api/v1/notify' \
--header 'Authorization: Basic YXBpOnRlc3Q=' \
--header 'Content-Type: application/json' \
Read 852 times Last modified on 2022-10-21

Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.