btg-sandbox-markdown-formatter/AuthMiddleware.php
DJP 5e4d4d0115 Initial commit: Secure Markdown to HTML converter with Azure AD authentication
- Web-based Markdown formatter with real-time conversion
- Microsoft Azure AD authentication with PKCE flow
- Server-side JWT validation with httpOnly cookies
- Clipboard functionality for HTML/text output
- PHP backend with Composer dependency management
- Comprehensive README with installation instructions

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-17 17:33:35 -04:00

205 lines
No EOL
7.3 KiB
PHP

<?php
require_once 'JWTValidator.php';
class AuthMiddleware {
private $validator;
private $tenantId = '01d33c7c-5640-4986-b4db-06af63a7d285';
private $clientId = '9079054c-9620-4757-a256-23413042f1ef';
public function __construct() {
$this->validator = new JWTValidator($this->tenantId, $this->clientId);
}
/**
* Check if user is authenticated
*/
public function isAuthenticated() {
$token = $this->getTokenFromCookie();
if (!$token) {
return ['authenticated' => false, 'error' => 'No authentication token found'];
}
$validation = $this->validator->validateToken($token);
if (!$validation['valid']) {
return ['authenticated' => false, 'error' => $validation['error']];
}
return ['authenticated' => true, 'user' => $validation['payload']];
}
/**
* Require authentication for current request
*/
public function requireAuth() {
$auth = $this->isAuthenticated();
if (!$auth['authenticated']) {
$this->handleUnauthorized($auth['error']);
exit;
}
return $auth['user'];
}
/**
* Set authentication token in httpOnly cookie
*/
public function setAuthToken($token) {
$validation = $this->validator->validateToken($token);
if (!$validation['valid']) {
return ['success' => false, 'error' => $validation['error']];
}
// Set httpOnly cookie with security options
$cookieOptions = [
'expires' => time() + (24 * 60 * 60), // 24 hours
'path' => '/',
'domain' => '',
'secure' => isset($_SERVER['HTTPS']), // Only over HTTPS in production
'httponly' => true,
'samesite' => 'Lax'
];
setcookie('auth_token', $token, $cookieOptions);
return ['success' => true, 'user' => $validation['payload']];
}
/**
* Clear authentication token
*/
public function clearAuthToken() {
setcookie('auth_token', '', [
'expires' => time() - 3600,
'path' => '/',
'httponly' => true
]);
}
/**
* Get token from httpOnly cookie
*/
private function getTokenFromCookie() {
return isset($_COOKIE['auth_token']) ? $_COOKIE['auth_token'] : null;
}
/**
* Handle unauthorized access
*/
private function handleUnauthorized($error) {
if ($this->isAjaxRequest()) {
header('Content-Type: application/json');
http_response_code(401);
echo json_encode([
'error' => 'Authentication required',
'message' => $error,
'requiresAuth' => true
]);
} else {
// For page requests, show login interface
$this->showLoginPage($error);
}
}
/**
* Check if request is AJAX
*/
private function isAjaxRequest() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}
/**
* Show login page for unauthenticated users
*/
private function showLoginPage($error = null) {
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Required - Markdown to HTML Converter</title>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
<script src="https://alcdn.msauth.net/browser/2.15.0/js/msal-browser.min.js" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="logo-container">
<img src="MD.svg" alt="MD Logo" class="logo">
</div>
<div style="text-align: center; padding: 40px;">
<h2>Authentication Required</h2>
<?php if ($error): ?>
<p style="color: #d32f2f; margin-bottom: 20px;">
<?php echo htmlspecialchars($error); ?>
</p>
<?php endif; ?>
<p>Please sign in with your Microsoft account to access the Markdown converter.</p>
<button id="login-button" onclick="signIn()" style="padding: 10px 20px; font-size: 16px; margin-top: 20px;">
Sign In with Microsoft
</button>
</div>
</div>
<script>
const msalConfig = {
auth: {
clientId: "<?php echo $this->clientId; ?>",
authority: "https://login.microsoftonline.com/<?php echo $this->tenantId; ?>",
redirectUri: window.location.origin + window.location.pathname.replace(/\/$/, '')
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: true,
}
};
const loginRequest = {
scopes: ["openid", "profile", "email"],
prompt: "select_account"
};
const myMSALObj = new msal.PublicClientApplication(msalConfig);
function signIn() {
myMSALObj.loginPopup(loginRequest)
.then(loginResponse => {
// Send token to server for validation and cookie setting
fetch('auth.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: 'login',
idToken: loginResponse.idToken,
accessToken: loginResponse.accessToken
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
window.location.reload();
} else {
alert('Authentication failed: ' + data.error);
}
})
.catch(error => {
console.error('Authentication error:', error);
alert('Authentication failed. Please try again.');
});
})
.catch(error => {
console.error("Login failed:", error);
alert('Login failed: ' + error.message);
});
}
</script>
</body>
</html>
<?php
}
}