Integration Guide
JavaScript / HTML
Complete guide for frontend integration with CAS SSO
5 min
Easy
ES2020+
1. SSO Redirect Flow
For browser-based apps, redirect users to the CAS login page. After authentication, they are returned to your callback URL with a token.
auth.js
const CAS_URL = 'https://your-cas-server.com';
const CLIENT_ID = 'your_client_id';
// Redirect user to CAS login page
function loginWithSSO() {
window.location.href = `${CAS_URL}/sso/login?client_id=${CLIENT_ID}`;
}
2. Handle Callback
After login, the user is redirected to your callback URL with a token query parameter. Validate it on your backend.
callback.js
// On your callback page (e.g. /cas/callback)
const params = new URLSearchParams(window.location.search);
const token = params.get('token');
if (token) {
// Send token to YOUR backend for validation
const res = await fetch('/api/validate-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token })
});
const data = await res.json();
if (data.valid) {
// User authenticated — store session
localStorage.setItem('user', JSON.stringify(data.user));
window.location.href = '/dashboard';
}
}
Important: Token validation must happen on your backend server (not in the browser) because it requires your
client_secret. Your backend calls POST /api/sso/validate on the CAS server.
3. Token Management
api-client.js
async function fetchProtected(url) {
const res = await fetch(url, { credentials: 'include' });
if (res.status === 401) {
// Session expired — redirect to SSO login
loginWithSSO();
return;
}
return res.json();
}
4. SPA Integration
For React, Vue, or Angular apps, use a route guard:
React example
function ProtectedRoute({ children }) {
const user = localStorage.getItem('user');
if (!user) {
loginWithSSO();
return null;
}
return children;
}
// Usage
<Route path="/dashboard" element={
<ProtectedRoute><Dashboard /></ProtectedRoute>
} />
Done! Your SPA is now integrated with CAS SSO via the redirect flow.