i’m working with symfony 6 and react js , im trying to access the cart of the user and it works correctly when I test it with postman but it throws this error when I test it in my frontend interface
401 Unauthorized : A security token is required but the token storage is empty.
this is my api function :
class PanierController extends AbstractController
public function __construct(TokenStorageInterface $tokenStorage) {
$this->tokenStorage = $tokenStorage;
}
#[Route('/api/get_panier', name: 'get-panier', methods: ['GET','POST'])]
public function getPanierContents( TokenInterface $token , Request $request ): Response
{
$token = $this->tokenStorage->getToken();
if (!$token) {
return $this->json(['message' => 'Token not found'], Response::HTTP_UNAUTHORIZED);
}
$user = $token->getUser();
if (!$user || !$user instanceof UserInterface) {
$this->logger->error("User not found");
return $this->json(['message' => 'User not found'], Response::HTTP_NOT_FOUND);
}
error_log("User found: " . $user->getUserIdentifier());
$panier = $user->getPanier();
if (!$panier) {
return $this->json(['message' => 'Panier not found'], Response::HTTP_NOT_FOUND);
}
$billets = $panier->getBillets();
// Convert billets collection to array
$billetsArray = [];
foreach ($billets as $billet) {
$billetsArray[] = [
'id' => $billet->getId(),
'date_debut_evenementt'=>$billet->getDateDebutEvenement(),
// Add other properties you want to include
];
}
// $serializedContents = $serializer->serialize($contents, 'json', ['groups' => 'billet']);
return $this->json($billetsArray);
}
and this is my security.yaml config :
app_user_provider:
entity:
class: AppEntityUsers
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: app_user_provider
custom_authenticator: AppSecurityUsersAuthenticator
logout:
path: app_logout
target: connexion_page
login:
stateless: true
json_login:
check_path: /api/login
username_path: email
password_path: password
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
api:
pattern: ^/api
stateless: true
jwt: ~
and this is how i am consuming it in react js :
export const fetchPanierData = (userId) => {
return async (dispatch) => {
try {
const token = getToken();
if (!token) {
throw new Error("No token found");
}
const response = await axios.get(`${BASE_URL}/api/get_panier`, {
headers: {
'Authorization': `Bearer ${token}`,
},
});
dispatch({ type: "FETCH_PANIER_SUCCESS", payload: response.data });
} catch (error) {
dispatch({
type: "FETCH_PANIER_FAILURE",
payload: error.response ? error.response.data : error.message,
});
}
};
};
I think the problem is in my security.yaml config so if you can help me that be great
before using TokenInterface $token in my api function I tried with #[currentUser] but it gave me a similar problem where it worked fine in postman but kept throwing a user not found error in my frontend