Skip to content

#[CurrentUser]: Cannot autowire argument $user of "App\Controller\FooController::method()": it references class "App\Entity\User" but no such service exists if user isn't logged in #45257

Closed
@fluffycondor

Description

@fluffycondor

Symfony version(s) affected

5.4, 6.0

Description

If I try to autowire \App\Entity\User to a non-nullable variable using #[CurrentUser] attribute in a controller method and I'm not logged in, Symfony crashes with a RuntimeException $user references class "App\Entity\User" but no such service exists.
It works like a charm if I logged in or the variable is nullable.

I'd expect it throws \Symfony\Component\Security\Core\Exception\AccessDeniedException instead, because if a programmer requests a non-null $user for a method then I think there's is an implication this method is accessible only if a user is logged in (as if there's a $this->denyAccessUnlessGranted('IS_AUTHENTICATED_REMEMBERED'); line in the beginning).

How to reproduce

<?php

declare(strict_types=1);

namespace App\Controller;

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

class FooController extends AbstractController
{
    #[Route('/foo', name: 'foo')]
    public function foo(#[CurrentUser] User $user): Response
    {
        return new Response('', Response::HTTP_NO_CONTENT);
    }
}

Possible Solution

No response

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions