I’m developing a web application with a Symfony backend and a React frontend. My goal is to share the session between Symfony and React so I can dynamically render UI elements based on the user’s role or permissions in the React pages.
Despite my 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 that the user is not authenticated in the React app, while the Symfony backend correctly recognizes the user as authenticated.
The API response from http://127.0.0.1:8000/api/check-auth returns {“authenticated”:true,”roles”:[“ROLE_ADMIN”,”ROLE_USER”]}
The React frontend remains { authenticated: false, roles: [] }
Steps I’ve Taken:
1.Set Up CORS Using NelmioCorsBundle:
nelmio_cors.yaml configuration:
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
2.Configured Session Settings:
framework.yaml configuration:
framework:
secret: '%env(APP_SECRET)%'
session:
handler_id: ~
cookie_secure: auto
cookie_samesite: lax
storage_factory_id: session.storage.factory.native
-
Created API Endpoint to Check Authentication Status:
ApiController.php:
namespace AppController;
use PsrLogLoggerInterface;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentSecurityCoreSecurity;
class ApiController extends AbstractController
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
#[Route('/api/check-auth', name: 'api_check_auth', methods: ['GET'])]
public function checkAuth(Security $security): JsonResponse
{
$user = $security->getUser();
if ($user) {
$this->logger->info('User roles: ' . implode(', ', $user->getRoles()));
return new JsonResponse([
'authenticated' => true,
'roles' => $user->getRoles(),
]);
}
$this->logger->info('Unauthenticated access');
return new JsonResponse([
'authenticated' => false,
'roles' => [],
]);
}
#[Route('/api/test-session', name: 'api_test_session', methods: ['GET'])]
public function testSession(Request $request): JsonResponse
{
$session = $request->getSession();
if (!$session->has('test')) {
$session->set('test', 'value');
return new JsonResponse(['message' => 'Session set']);
}
return new JsonResponse(['message' => 'Session value: ' . $session->get('test')]);
}
}
4.React Hook to Fetch Authentication Status:
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
});
const data = await response.json();
setAuth(data);
} catch (error) {
console.error('Error:', error);
}
};
checkAuth();
}, []);
useEffect(() => {
console.log('Auth state changed:', auth);
}, [auth]);
return auth;
};
export default useAuth;
5.React Component Utilizing Authentication Hook:
about.jsx:
import React from 'react';
import useTextContent from '../hooks/useTextContent';
import useImageContent from '../hooks/useImageContent';
import useHeadingContent from '../hooks/useHeadingContent';
import useAuth from '../hooks/useAuth';
function About() {
const { authenticated, roles } = useAuth();
useTextContent();
useImageContent();
useHeadingContent();
const isAdmin = roles.includes('ROLE_ADMIN');
return (
<div className="about-page-wrapper">
{/* about-Page-Header start */}
<div className="about-header about-header-s">
<h1 className="header-text" data-page="about" data-tag="header">
</h1>
<h1 className="header-text" data-page="about" data-tag="testttt">
</h1>
<p data-page="about" data-tag="header"></p>
<p data-page="about" data-tag="arrow"></p>
</div>
{/* about-Page-Header end */}
</div>
);
}
export default About;
-
Symfony Security Configuration:
security.yaml:
security:
password_hashers:
SymfonyComponentSecurityCoreUserPasswordAuthenticatedUserInterface: 'auto'
providers:
app_user_provider:
entity:
class: AppEntityUser
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: app_user_provider
form_login:
login_path: app_login
check_path: app_login
default_target_path: /frequentQuestion/
logout:
path: app_logout
access_control:
- { path: ^/question, roles: ROLE_ADMIN }
- { path: ^/frequentQuestion, roles: ROLE_ADMIN }
Despite these configurations, the authentication state in the React frontend remains { authenticated: false, roles: [] }, while the API response correctly indicates the user is authenticated.
Additional Information:
React Frontend URL: http://localhost:3000/
Symfony Backend URL: http://127.0.0.1:8000/
What I Need Help With:
Ensuring the session is correctly shared between the Symfony backend and React frontend.
Diagnosing why the authentication state is not updating correctly in the React frontend.
Additional Debugging Steps Taken:
Verified that the session cookie is set and sent with each request using browser developer tools.
Checked network requests to ensure that the session cookie is included.
tree rex is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.