Symfony
sponsored by SensioLabs
Menu
  • About
  • Documentation
  • Screencasts
  • Cloud
  • Certification
  • Community
  • Businesses
  • News
  • Download
  1. Home
  2. Documentation
  3. Security
  4. How to Build a JSON Authentication Endpoint
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud
Search by Algolia

How to Build a JSON Authentication Endpoint

Edit this page

Warning: You are browsing the documentation for Symfony 4.4, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

How to Build a JSON Authentication Endpoint

In this entry, you'll build a JSON endpoint to log in your users. When the user logs in, you can load your users from anywhere - like the database. See Security for details.

First, enable the JSON login under your firewall:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
# config/packages/security.yaml
security:
    # ...

    firewalls:
        main:
            anonymous: lazy
            json_login:
                check_path: /login
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- config/packages/security.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<srv:container xmlns="http://symfony.com/schema/dic/security"
    xmlns:srv="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        https://symfony.com/schema/dic/services/services-1.0.xsd">

    <config>
        <firewall name="main">
            <anonymous lazy="true"/>
            <json-login check-path="/login"/>
        </firewall>
    </config>
</srv:container>
1
2
3
4
5
6
7
8
9
10
11
// config/packages/security.php
$container->loadFromExtension('security', [
    'firewalls' => [
        'main' => [
            'anonymous'  => 'lazy',
            'json_login' => [
                'check_path' => '/login',
            ],
        ],
    ],
]);

Tip

The check_path can also be a route name (but cannot have mandatory wildcards - e.g. /login/{foo} where foo has no default value).

The next step is to configure a route in your app matching this path:

  • Annotations
  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/Controller/SecurityController.php
namespace App\Controller;

// ...
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class SecurityController extends AbstractController
{
    /**
     * @Route("/login", name="login", methods={"POST"})
     */
    public function login(Request $request): Response
    {
        $user = $this->getUser();

        return $this->json([
            'username' => $user->getUsername(),
            'roles' => $user->getRoles(),
        ]);
    }
}
1
2
3
4
5
# config/routes.yaml
login:
    path:       /login
    controller: App\Controller\SecurityController::login
    methods: POST
1
2
3
4
5
6
7
8
9
<!-- config/routes.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing
        https://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="login" path="/login" controller="App\Controller\SecurityController::login" methods="POST"/>
</routes>
1
2
3
4
5
6
7
8
9
10
// config/routes.php
use App\Controller\SecurityController;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;

return function (RoutingConfigurator $routes) {
    $routes->add('login', '/login')
        ->controller([SecurityController::class, 'login'])
        ->methods(['POST'])
    ;
};

Now, when you make a POST request, with the header Content-Type: application/json, to the /login URL with the following JSON document as the body, the security system intercepts the request and initiates the authentication process:

1
2
3
4
{
    "username": "dunglas",
    "password": "MyPassword"
}

Symfony takes care of authenticating the user with the submitted username and password or triggers an error in case the authentication process fails. If the authentication is successful, the controller defined earlier will be called.

If the JSON document has a different structure, you can specify the path to access the username and password properties using the username_path and password_path keys (they default respectively to username and password). For example, if the JSON document has the following structure:

1
2
3
4
5
6
7
8
{
    "security": {
        "credentials": {
            "login": "dunglas",
            "password": "MyPassword"
        }
    }
}

The security configuration should be:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
# config/packages/security.yaml
security:
    # ...

    firewalls:
        main:
            anonymous: lazy
            json_login:
                check_path:    login
                username_path: security.credentials.login
                password_path: security.credentials.password
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- config/packages/security.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<srv:container xmlns="http://symfony.com/schema/dic/security"
    xmlns:srv="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        https://symfony.com/schema/dic/services/services-1.0.xsd">

    <config>
        <firewall name="main">
            <anonymous lazy="true"/>
            <json-login check-path="login"
                username-path="security.credentials.login"
                password-path="security.credentials.password"/>
        </firewall>
    </config>
</srv:container>
1
2
3
4
5
6
7
8
9
10
11
12
13
// config/packages/security.php
$container->loadFromExtension('security', [
    'firewalls' => [
        'main' => [
            'anonymous'  => 'lazy',
            'json_login' => [
                'check_path' => 'login',
                'username_path' => 'security.credentials.login',
                'password_path' => 'security.credentials.password',
            ],
        ],
    ],
]);
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
We stand with Ukraine.
Version:
Make sure your project is risk free

Make sure your project is risk free

Measure & Improve Symfony Code Performance

Measure & Improve Symfony Code Performance

↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

Avatar of Steven, a Symfony contributor

Thanks Steven for being a Symfony contributor

10 commits • 247 lines changed

View all contributors that help us make Symfony

Become a Symfony contributor

Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

Learn how to contribute

Symfony™ is a trademark of Symfony SAS. All rights reserved.

  • What is Symfony?
    • Symfony at a Glance
    • Symfony Components
    • Case Studies
    • Symfony Releases
    • Security Policy
    • Logo & Screenshots
    • Trademark & Licenses
    • symfony1 Legacy
  • Learn Symfony
    • Symfony Docs
    • Symfony Book
    • Reference
    • Bundles
    • Best Practices
    • Training
    • eLearning Platform
    • Certification
  • Screencasts
    • Learn Symfony
    • Learn PHP
    • Learn JavaScript
    • Learn Drupal
    • Learn RESTful APIs
  • Community
    • SymfonyConnect
    • Support
    • How to be Involved
    • Code of Conduct
    • Events & Meetups
    • Projects using Symfony
    • Downloads Stats
    • Contributors
    • Backers
  • Blog
    • Events & Meetups
    • A week of symfony
    • Case studies
    • Cloud
    • Community
    • Conferences
    • Diversity
    • Documentation
    • Living on the edge
    • Releases
    • Security Advisories
    • SymfonyInsight
    • Twig
    • SensioLabs
  • Services
    • SensioLabs services
    • Train developers
    • Manage your project quality
    • Improve your project performance
    • Host Symfony projects
    Deployed on
Follow Symfony
Search by Algolia