I have a very weird behavior on symfony 6 with json login. Json login is configured like in their example.
I added the most simple Cors-handling
class CorsSubscriber implements EventSubscriberInterface
{
public function onKernelResponse(ResponseEvent $event)
{
$response = $event->getResponse();
$response->headers->add([
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Headers' => 'Content-Type'
]);
}
public static function getSubscribedEvents()
{
return [
KernelEvents::RESPONSE => 'onKernelResponse',
];
}
}
Login Controller
class LoginController extends AbstractController
{
#[Route('/login', name: 'api_login')]
public function login(#[CurrentUser] ?User $user): JsonResponse
{
if ($user === null) {
$this->json([
'message' => 'Not found',
], JsonResponse::HTTP_UNAUTHORIZED);
}
$token = "token"; // some token logik follows
$response = new JsonResponse([
'user' => $user->getUserIdentifier(),
'token' => $token,
]);
return $response;
}
}
Again, basically straight out of their tutorial.
DB is also set up and a user was added beforehand. If I now want to login via a Rest App (I use Insomnia) everything works as expected. I get the user identifier (email) and token back.
But when I want to do the exact same thing via an Angular web app, I get the following message in the log: [critical] Uncaught Error: Call to a member function getUserIdentifier() on null
let data = {username: "test@test.de", password: "test123"};
this.http
.post('http://localhost:8000/login', data)
.subscribe({
next: (value) => {
console.log(value);
},
});
Funny thing since I check if $user is null...
But the most funny thing is, if I change the $user->getUserIdentifier() call to just "$user" - it works and I get the whole User object returned (everything I defined in json_serializable)
Again, getUserIdentifier is from symfony itself
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->email;
}
What am I missing?