Implementation Guide
Complete code examples for integrating CAS authentication with Wicket
This guide shows how to implement CAS (Central Authentication Service) authentication in your application. These examples work for both standard CAS and delegated CAS scenarios — your code is identical.
Works for Both: Whether using standard CAS (Wicket users) or delegated CAS (external providers like B2C/Auth0), your application code is the same. CAS handles delegation transparently.
CAS Authentication Flow
Redirect to CAS Login
Your application redirects unauthenticated users to the CAS login page:
// Redirect user to CAS
const casLoginUrl =
'https://your-org-login.wicketcloud.com/login?' +
`service=${encodeURIComponent('https://your-app.com/auth/callback')}`;
window.location.href = casLoginUrl;User Authenticates
User enters credentials on the CAS login page. CAS verifies against Wicket person/user records (or external provider if using delegation).
CAS Returns with Ticket
CAS redirects back to your callback URL with a service ticket:
https://your-app.com/auth/callback?ticket=ST-12345-abcdefgVerify Ticket & Extract Person UUID
Your application validates the ticket with CAS and extracts the person UUID from attributes:
async function validateCASTicket(ticket, service) {
const validateUrl =
'https://your-org-login.wicketcloud.com/serviceValidate?' +
`ticket=${ticket}&service=${encodeURIComponent(service)}`;
const response = await fetch(validateUrl);
const xml = response.data;
// Parse CAS XML response
// Extract person UUID from cas:attributes
const personUuid = extractAttributeFromXML(xml, 'personUuid');
return personUuid;
}
// In your callback handler
app.get('/auth/callback', async (req, res) => {
const { ticket } = req.query;
const service = 'https://your-app.com/auth/callback';
try {
// Validate ticket and get person UUID
const personUuid = await validateCASTicket(ticket, service);
// Generate Wicket MDP API JWT
const wicketToken = generateWicketJWT(personUuid);
// Store in session
req.session.wicketToken = wicketToken;
req.session.personUuid = personUuid;
res.redirect('/dashboard');
} catch (error) {
res.redirect('/login?error=auth_failed');
}
});Sign Wicket MDP API JWT
Generate a JWT for Wicket MDP API access using the person UUID:
const jwt = require('jsonwebtoken');
function generateWicketJWT(personUuid) {
return jwt.sign(
{
user_uuid: personUuid,
exp: Math.floor(Date.now() / 1000) + (60 * 60) // 1 hour
},
process.env.WICKET_API_SECRET,
{ algorithm: 'HS256' }
);
}Access Wicket MDP API
Use the JWT for all Wicket MDP API requests:
const response = await fetch(
`https://your-org-api.wicketcloud.com/people/${personUuid}`,
{
headers: {
'Authorization': `Bearer ${wicketToken}`
}
}
);Complete Implementation Examples
const express = require('express');
const jwt = require('jsonwebtoken');
const xml2js = require('xml2js');
const session = require('express-session');
const app = express();
// Session middleware
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: true, // HTTPS only in production
httpOnly: true,
sameSite: 'lax',
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}
}));
// CAS configuration
const CAS_BASE_URL = 'https://your-org-login.wicketcloud.com';
const SERVICE_URL = 'https://your-app.com/auth/callback';
const WICKET_API_URL = 'https://your-org-api.wicketcloud.com';
// Initiate CAS login
app.get('/login', (req, res) => {
const casLoginUrl = `${CAS_BASE_URL}/login?service=${encodeURIComponent(SERVICE_URL)}`;
res.redirect(casLoginUrl);
});
// Handle CAS callback
app.get('/auth/callback', async (req, res) => {
const { ticket } = req.query;
if (!ticket) {
return res.redirect('/login?error=no_ticket');
}
try {
// Validate ticket
const validateUrl = `${CAS_BASE_URL}/serviceValidate?` +
`ticket=${ticket}&service=${encodeURIComponent(SERVICE_URL)}`;
const response = await fetch(validateUrl);
// Parse XML response
const parser = new xml2js.Parser();
const result = await parser.parseStringPromise(response.data);
// Check if validation succeeded
const authSuccess = result['cas:serviceResponse']['cas:authenticationSuccess'];
if (!authSuccess) {
throw new Error('CAS validation failed');
}
// Extract person UUID from attributes
const attributes = authSuccess[0]['cas:attributes'][0];
const personUuid = attributes['cas:personUuid'][0];
const email = attributes['cas:email']?.[0];
const givenName = attributes['cas:givenName']?.[0];
const familyName = attributes['cas:familyName']?.[0];
const username = attributes['cas:username']?.[0];
// Generate Wicket MDP API JWT
const wicketToken = jwt.sign(
{
user_uuid: personUuid,
exp: Math.floor(Date.now() / 1000) + (60 * 60) // 1 hour
},
process.env.WICKET_API_SECRET,
{ algorithm: 'HS256' }
);
// Store in session
req.session.wicketToken = wicketToken;
req.session.personUuid = personUuid;
req.session.user = {
email,
givenName,
familyName
};
res.redirect('/dashboard');
} catch (error) {
console.error('CAS authentication error:', error);
res.redirect('/login?error=auth_failed');
}
});
// Logout
app.get('/logout', (req, res) => {
req.session.destroy();
const casLogoutUrl = `${CAS_BASE_URL}/logout?` +
`service=${encodeURIComponent('https://your-app.com')}`;
res.redirect(casLogoutUrl);
});
// Middleware to require authentication
function requireAuth(req, res, next) {
if (!req.session.wicketToken) {
return res.redirect('/login');
}
next();
}
// Protected route example
app.get('/dashboard', requireAuth, async (req, res) => {
try {
// Fetch user data from Wicket MDP API
const response = await fetch(
`${WICKET_API_URL}/people/${req.session.personUuid}`,
{
headers: {
'Authorization': `Bearer ${req.session.wicketToken}`
}
}
);
res.render('dashboard', { person: response.data.data });
} catch (error) {
console.error('API error:', error);
res.status(500).send('Error loading dashboard');
}
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3020');
});# config/routes.rb
Rails.application.routes.draw do
get '/login', to: 'sessions#new'
get '/auth/callback', to: 'sessions#create'
get '/logout', to: 'sessions#destroy'
get '/dashboard', to: 'dashboard#index'
end
# app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
CAS_BASE_URL = 'https://your-org-login.wicketcloud.com'
SERVICE_URL = 'https://your-app.com/auth/callback'
WICKET_API_URL = 'https://your-org-api.wicketcloud.com'
def new
# Redirect to CAS login
cas_login_url = "#{CAS_BASE_URL}/login?service=#{CGI.escape(SERVICE_URL)}"
redirect_to cas_login_url
end
def create
ticket = params[:ticket]
unless ticket
redirect_to login_path(error: 'no_ticket')
return
end
begin
# Validate ticket
validate_url = "#{CAS_BASE_URL}/serviceValidate?ticket=#{ticket}&service=#{CGI.escape(SERVICE_URL)}"
response = HTTParty.get(validate_url)
# Parse XML
doc = Nokogiri::XML(response.body)
doc.remove_namespaces!
# Check authentication success
auth_success = doc.at_xpath('//authenticationSuccess')
raise 'CAS validation failed' unless auth_success
# Extract person UUID
person_uuid = doc.at_xpath('//personUuid')&.text
raise 'Person UUID not found' unless person_uuid
# Extract other attributes
email = doc.at_xpath('//email')&.text
given_name = doc.at_xpath('//givenName')&.text
family_name = doc.at_xpath('//familyName')&.text
username = doc.at_xpath('//username')&.text
# Generate Wicket MDP API JWT
wicket_token = JWT.encode(
{
user_uuid: person_uuid,
exp: Time.now.to_i + 3600 # 1 hour
},
ENV['WICKET_API_SECRET'],
'HS256'
)
# Store in session
session[:wicket_token] = wicket_token
session[:person_uuid] = person_uuid
session[:user] = {
email: email,
given_name: given_name,
family_name: family_name
}
redirect_to dashboard_path
rescue => error
Rails.logger.error "CAS authentication error: #{error}"
redirect_to login_path(error: 'auth_failed')
end
end
def destroy
reset_session
cas_logout_url = "#{CAS_BASE_URL}/logout?service=https://your-app.com"
redirect_to cas_logout_url
end
end
# app/controllers/dashboard_controller.rb
class DashboardController < ApplicationController
before_action :require_authentication
def index
begin
# Fetch user data from Wicket MDP API
response = HTTParty.get(
"#{SessionsController::WICKET_API_URL}/people/#{session[:person_uuid]}",
headers: { 'Authorization' => "Bearer #{session[:wicket_token]}" }
)
@person = JSON.parse(response.body)['data']
rescue => error
Rails.logger.error "API error: #{error}"
render plain: 'Error loading dashboard', status: 500
end
end
private
def require_authentication
redirect_to login_path unless session[:wicket_token]
end
endCAS XML Response Structure
When you validate a CAS ticket, you receive an XML response:
<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
<cas:authenticationSuccess>
<cas:user>john.doe</cas:user>
<cas:attributes>
<cas:personUuid>a1b2c3d4-e5f6-7890-abcd-ef1234567890</cas:personUuid>
<cas:email>john@example.com</cas:email>
<cas:givenName>John</cas:givenName>
<cas:familyName>Doe</cas:familyName>
<cas:username>john.doe</cas:username>
<cas:isMember>true</cas:isMember>
</cas:attributes>
</cas:authenticationSuccess>
</cas:serviceResponse>Default Attributes:
personUuid— The Wicket person UUID to use for API JWT signing (required)email— User's email addressusername— CAS usernamegivenName— First namefamilyName— Last nameisMember— Whether user has member role
Security Best Practices
1. Validate CAS Tickets Server-Side
Always validate tickets on your server, never trust client-provided data:
// ✅ Good: Server-side ticket validation
app.get('/auth/callback', async (req, res) => {
const { ticket } = req.query;
const personUuid = await validateCASTicket(ticket, SERVICE_URL);
// ...
});
// ❌ Dangerous: Never trust client-provided person UUIDs
app.post('/login', (req, res) => {
const { personUuid } = req.body; // NEVER DO THIS
const token = generateWicketJWT(personUuid); // INSECURE!
});2. Secure JWT Signing
Keep API secrets secure:
// ✅ Good: Environment variable
const secret = process.env.WICKET_API_SECRET;
// ❌ Dangerous: Hardcoded secret
const secret = 'my-secret-key'; // DON'T DO THIS3. Use Short-Lived JWTs
Use reasonable expiration times:
// ✅ Good: 1 hour expiration
exp: Math.floor(Date.now() / 1000) + (60 * 60)
// ⚠️ Acceptable: 24 hours for long-lived sessions
exp: Math.floor(Date.now() / 1000) + (24 * 60 * 60)
// ❌ Risky: Very long expiration
exp: Math.floor(Date.now() / 1000) + (30 * 24 * 60 * 60) // 30 days4. Use HTTPS in Production
// ✅ Good: HTTPS URLs
const CAS_BASE_URL = 'https://your-org-login.wicketcloud.com';
// ❌ Insecure: HTTP in production
const CAS_BASE_URL = 'http://your-org-login.wicketcloud.com';5. Secure Session Configuration
app.use(session({
secret: process.env.SESSION_SECRET, // Strong random secret
resave: false,
saveUninitialized: false,
cookie: {
secure: true, // HTTPS only in production
httpOnly: true, // Prevent client-side access
sameSite: 'lax', // CSRF protection
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}
}));6. Handle Token Expiration
Refresh or re-authenticate when tokens expire:
async function callWicketAPI(endpoint) {
const response = await fetch(endpoint, {
headers: { 'Authorization': `Bearer ${session.wicketToken}` }
});
if (response.status === 401) {
// Token expired - redirect to login
window.location.href = '/login';
return;
}
return response.json();
}Testing Your Integration
1. Test Login Flow
# 1. Visit your app's login page
curl -i http://localhost:3020/login
# Should redirect to CAS login (302)
Location: https://your-org-login.wicketcloud.com/login?service=...
# 2. After CAS login, callback receives ticket
http://localhost:3020/auth/callback?ticket=ST-12345-abcdefg
# 3. Verify session is established
# Check cookies or session storage2. Verify Ticket Validation
// Test ticket validation directly
async function testTicketValidation() {
const validateUrl =
`${CAS_BASE_URL}/serviceValidate?ticket=ST-TEST-123&service=${SERVICE_URL}`;
const response = await fetch(validateUrl);
console.log('CAS Response:', response.data);
// Should see XML with authenticationSuccess or authenticationFailure
}3. Test API Access
// Verify JWT works with Wicket MDP API
async function testAPIAccess(personUuid, wicketToken) {
const response = await fetch(
`${WICKET_API_URL}/people/${personUuid}`,
{ headers: { 'Authorization': `Bearer ${wicketToken}` } }
);
console.log('API Status:', response.status);
console.log('Person Data:', await response.json());
}Troubleshooting
Ticket Validation Fails
Error: <cas:authenticationFailure>Ticket ST-... not recognized</cas:authenticationFailure>
Solutions:
- Ensure ticket is used only once (CAS tickets are single-use)
- Check ticket hasn't expired (typically 10-30 seconds)
- Verify
serviceparameter matches exactly between/loginand/serviceValidate
Person UUID Not in Response
Error: personUuid attribute missing from CAS response
Solutions:
- Check CAS is configured to return
personUuidin attributes - Verify default attributes configuration includes
personUuid - Contact Wicket support to verify CAS attribute configuration
- Ensure user exists in Wicket system
JWT Signature Invalid
Error: Wicket MDP API returns 401 with "Invalid signature"
Solutions:
- Verify
WICKET_API_SECRETmatches the secret provided by Wicket - Check JWT is signed with HS256 algorithm
- Ensure
user_uuidfield name is correct (notperson_uuid)
Session Not Persisting
Error: User logged out after every request
Solutions:
- Verify session middleware is configured
- Check session secret is set
- Ensure cookies are enabled
- Verify cookie
secureflag matches HTTPS usage