* code is set on the response. In cases where no existing CAS session exists,
* a 302 redirect is set on the response to redirect to the CAS server for
* authentication.
*/
public final Principal authenticate(final HttpServletRequest request, final HttpServletResponse response) {
Assertion assertion = null;
HttpSession session = request.getSession();
if (session != null) {
assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
}
if (assertion == null) {
logger.debug("CAS assertion not found in session -- authentication required.");
final String token = request.getParameter(this.artifactParameterName);
final String service = CommonUtils.constructServiceUrl(request, response, this.serviceUrl, this.serverName,
this.artifactParameterName, true);
if (CommonUtils.isBlank(token)) {
final String redirectUrl = CommonUtils.constructRedirectUrl(this.casServerLoginUrl,
this.serviceParameterName, service, false, false);
logger.debug("Redirecting to {}", redirectUrl);
CommonUtils.sendRedirect(response, redirectUrl);
return null;
}
try {
logger.debug("Attempting to validate {} for {}", token, service);
assertion = this.ticketValidator.validate(token, service);
logger.debug("CAS authentication succeeded.");
if (session == null) {
session = request.getSession(true);
}
session.setAttribute(AbstractCasFilter.CONST_CAS_ASSERTION, assertion);
} catch (final TicketValidationException e) {
setUnauthorized(response, e.getMessage());
return null;
}
}
Principal p = realm.authenticate(assertion.getPrincipal());
if (p == null) {
logger.debug("{} failed to authenticate to {}", assertion.getPrincipal().getName(), realm);
setUnauthorized(response, null);
}
return p;
}