loreal-global-kickoff/auth.php
Vadym Samoilenko 0280b94154 Fix MSAL redirect_uri to match Azure AD registered URI
Change redirect_uri to app root (without /auth.php) to match what's
registered in Azure portal. Use relative URLs for auth fetch and reload
on success instead of computed absolute paths.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-02 20:39:12 +00:00

83 lines
2.6 KiB
PHP

<?php
/**
* OAuth Callback Handler
* Handles Azure AD MSAL authentication flow
*
* POST /auth.php?action=login — receives idToken, validates, sets cookie
* GET /auth.php?action=logout — clears cookie, redirects to index
* GET /auth.php — redirects to index (MSAL redirect_uri target)
*/
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/JWTValidator.php';
require_once __DIR__ . '/UserRoleManager.php';
$config = require __DIR__ . '/config.php';
$action = $_GET['action'] ?? '';
// POST login — validate idToken, set auth cookie
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'login') {
header('Content-Type: application/json');
$body = json_decode(file_get_contents('php://input'), true);
$token = $body['token'] ?? '';
if (empty($token)) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Token is required']);
exit;
}
$validator = new JWTValidator(
$config['sso']['tenant_id'],
$config['sso']['client_id']
);
$result = $validator->validate($token);
if (!$result['valid']) {
http_response_code(401);
echo json_encode(['success' => false, 'message' => $result['error'] ?? 'Invalid token']);
exit;
}
// Register user role on first login
$email = strtolower($result['claims']['preferred_username'] ?? $result['claims']['upn'] ?? '');
if ($email) {
$roleManager = new UserRoleManager();
$roleManager->getRole($email); // triggers auto-promotion for admin_emails
}
// Store the raw idToken in a secure HttpOnly cookie (24h)
$cookieOptions = [
'expires' => time() + (24 * 60 * 60),
'path' => '/',
'domain' => '',
'secure' => isset($_SERVER['HTTPS']),
'httponly' => true,
'samesite' => 'Lax'
];
setcookie('auth_token', $token, $cookieOptions);
echo json_encode(['success' => true]);
exit;
}
// GET logout — clear cookie, redirect
if ($_SERVER['REQUEST_METHOD'] === 'GET' && $action === 'logout') {
setcookie('auth_token', '', time() - 3600, '/');
unset($_COOKIE['auth_token']);
// Build Azure AD logout URL
$tenantId = $config['sso']['tenant_id'];
$postLogoutRedirect = urlencode('https://ai-sandbox.oliver.solutions/loreal-global-kickoff');
$logoutUrl = "https://login.microsoftonline.com/{$tenantId}/oauth2/v2.0/logout?post_logout_redirect_uri={$postLogoutRedirect}";
header('Location: ' . $logoutUrl);
exit;
}
// GET default — redirect to index (handles MSAL redirect_uri)
header('Location: index.php');
exit;