Home > Blockchain >  Symfony 6.2 and json_login not save authenticated state
Symfony 6.2 and json_login not save authenticated state

Time:01-07

I have config (security.yaml):

    firewalls:
        login:
            pattern: ^/api/login
            json_login:
                username_path: email
                password_path: password
                check_path: api_login
        
        main:
            login_throttling:
                max_attempts: 3
            lazy: true
            provider: app_user_provider
            custom_authenticator: App\Security\CustomAuthenticator
<?php

namespace App\Controller;

use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

#[Route('/api', name: 'api_')]

class ApiController extends AbstractController
{
    #[Route('/login', name: 'login', methods: ['POST'])]
    public function login(#[CurrentUser] ?User $user): Response
    {
        if (null === $user) {
            return $this->json([
                'message' => 'missing credentials',
            ], Response::HTTP_UNAUTHORIZED);
        }

        return $this->json(['user' => $user->getUserIdentifier()]);
    }
}

In debug-panel I see Authenticated and i see real getUserIdentifier(). But if I reload the page, then I'm not logged in again. If you move json_login to the main block, then everything works. What is missing?

I tried different custom authorizers, but it didn't help. I also looked at the open repositories in the github but all examples are the same

CodePudding user response:

You don't have to create separate firewall only for login path - add entries in your main firewall.

I cannot find it now, but I can bet that somewhere in Symfony Security docs there is information that login should not have separate firewall. But from docs:

Each firewall is like a separate security system, being authenticated in one firewall doesn't make you authenticated in another one.

So, you are authenticating in login firewall, but then navigating to any endpoint protected by main will not work.

  • Related