Reputation: 509
TLDR: When I want to return a JSON response with my User (->getUser()), accessible in GET (I test with Postman) I have only an empty JSON or NULL. While the same method works inside Symfony.
I am on a project based on Symfony 4.4 and ReactJS. I created my User entity with the Security-bundle.
I made a controller to return a JSON response containing User's data.
<?php
namespace App\Controller\Api;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
class UserConnectedController extends TypedController
{
/**
* @var Security
*/
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @Route("/api/user", name="user_connected", methods={"GET"})
* @param Request $request
* @return JsonResponse|Response
*/
public function user(Request $request){
$user = $this->security->getUser();
return new JsonResponse($user);
}
}
When I try to fetch this url with Postman (GET), I only have "NULL". However, when I want to get this user inside Symfony (dumping it in a twig for example) it works perfectly.
Why is this $user accessible only in Symfony and not through a GET request ? Is there any security-related issue ?
So far I've tried :
None of these worked. If you have any hint, it will be much appreciated. Thanks in advance.
Upvotes: 1
Views: 4393
Reputation: 509
The problem was indeed security related and specifically from the credentials.
I should have shared the credentials in the request.
fetch("http://localhost:8000/api/user", {
credentials: 'include'
})
Then only CORS will block the request and with a symfony bundle (nelmio) I allowed to share credentials from cross-origin and bingo its working !
Upvotes: 0
Reputation: 2591
When you use new JsonResponse
you encode your object with json_encode function. In this case, you will get the empty JSON object. $this->json
it is a wrapper on new JsonResponse
, which firstly looking for the serializer in your container. So you have at least two options
Upvotes: 2