I am developing a web application with a Symfony backend and a React frontend. I’m trying to share the session between Symfony and React so that i can later on dynamically render UI elements in the react pages based on the backend user’s role or permissions.
React Frontend URL: http://localhost:3000/
Symfony Backend URL: http://127.0.0.1:8000/
down below is what i tried and didn’t work, so i am open to different solutions hopefully easy to implement
Here are the steps of the solution that i have tried:
- I have set up CORS using NelmioCorsBundle to allow requests from my React frontend.
Symfony Backend (nelmio_cors.yaml):
nelmio_cors:
defaults:
allow_origin: ['http://localhost:3000']
allow_headers: ['Content-Type', 'Authorization']
allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
allow_credentials: true
max_age: 3600
paths:
'^/api/':
allow_origin: ['http://localhost:3000']
allow_headers: ['Content-Type', 'Authorization']
allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
allow_credentials: true
max_age: 3600
- Configured session settings in framework.yaml.
Symfony Session Configuration (framework.yaml):
framework:
secret: '%env(APP_SECRET)%'
http_method_override: true
handle_all_throwables: true
session:
handler_id: ~
cookie_secure: auto
cookie_samesite: lax
storage_factory_id: session.storage.factory.native
php_errors:
log: true
- Created an API endpoint /api/check-auth to check authentication status.
Symfony Controller (ApiController.php):
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentSerializerSerializerInterface;
use SymfonyComponentSerializerNormalizerObjectNormalizer;
use SymfonyComponentSecurityCoreSecurity;
class ApiController extends AbstractController
{
#[Route('/api/check-auth', name: 'api_check_auth', methods: ['GET'])]
public function checkAuth(Security $security): JsonResponse
{
$user = $security->getUser();
if ($user) {
return new JsonResponse([
'authenticated' => true,
'roles' => $user->getRoles(),
]);
}
return new JsonResponse([
'authenticated' => false,
'roles' => [],
]);
}
}
- Used a custom hook (useAuth) to fetch authentication status from the Symfony backend.
React Hook (useAuth.js):
import { useState, useEffect } from 'react';
const useAuth = () => {
const [auth, setAuth] = useState({ authenticated: false, roles: [] });
useEffect(() => {
const checkAuth = async () => {
try {
const response = await fetch('http://127.0.0.1:8000/api/check-auth', {
credentials: 'include', // Include cookies in the request
});
console.log('Response status:', response.status);
if (response.ok) {
const data = await response.json();
console.log('Response data:', data);
setAuth(data);
} else {
console.error('Failed to fetch authentication status:', response.statusText);
}
} catch (error) {
console.error('Error:', error);
}
};
checkAuth();
}, []);
useEffect(() => {
console.log('Auth state changed:', auth);
}, [auth]);
return auth;
};
export default useAuth;
Symfony Login Form (security.yaml):
security:
enable_authenticator_manager: true
providers:
in_memory:
memory: ~
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: in_memory
form_login:
login_path: login
check_path: login
logout:
path: logout
target: /
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api, roles: ROLE_USER }
this is my react Test page (AuthTest.js):
import React from 'react';
import useAuth from './useAuth';
const AuthTest = () => {
const auth = useAuth();
return (
<div>
<h1>Auth Test</h1>
<p>Authenticated: {auth.authenticated ? 'Yes' : 'No'}</p>
<p>Roles: {auth.roles.join(', ')}</p>
</div>
);
};
export default AuthTest;
Despite these efforts, the authentication state in the React frontend is not updating correctly. The fetch request to the Symfony backend is made, but the response always indicates the user is not authenticated.
the authentication state in React remains { authenticated: false, roles: [] }, while the result of going to ‘http://127.0.0.1:8000/api/check-auth’ is {“authenticated”:true,”roles”:[“ROLE_ADMIN”,”ROLE_USER”]}
i also tried using axios in the front end but it dident work properly.