use of com.sun.identity.saml2.protocol.LogoutResponse in project OpenAM by OpenRock.
the class IDPSingleLogout method processLogoutRequest.
/**
* Gets and processes the Single <code>LogoutRequest</code> from SP
* and return <code>LogoutResponse</code>.
*
* @param logoutReq <code>LogoutRequest</code> from SP
* @param request the HttpServletRequest.
* @param response the HttpServletResponse.
* @param binding name of binding will be used for request processing.
* @param relayState the relay state.
* @param idpEntityID name of host entity ID.
* @param realm name of host entity.
* @param isVerified true if the request is verified already.
* @return LogoutResponse the target URL on successful
* <code>LogoutRequest</code>.
* @throws SAML2Exception if error processing
* <code>LogoutRequest</code>.
*/
public static LogoutResponse processLogoutRequest(LogoutRequest logoutReq, HttpServletRequest request, HttpServletResponse response, String binding, String relayState, String idpEntityID, String realm, boolean isVerified) throws SAML2Exception {
Status status = null;
String spEntity = logoutReq.getIssuer().getValue();
Object session = null;
String tmpStr = request.getParameter("isLBReq");
boolean isLBReq = (tmpStr == null || !tmpStr.equals("false"));
try {
do {
String requestId = logoutReq.getID();
SAML2Utils.verifyRequestIssuer(realm, idpEntityID, logoutReq.getIssuer(), requestId);
List siList = logoutReq.getSessionIndex();
if (siList == null) {
debug.error("IDPSingleLogout.processLogoutRequest: " + "session index are null in logout request");
status = SAML2Utils.generateStatus(SAML2Constants.REQUESTER, "");
break;
}
int numSI = siList.size();
// TODO : handle list of session index
Iterator siIter = siList.iterator();
String sessionIndex = null;
if (siIter.hasNext()) {
sessionIndex = (String) siIter.next();
}
if (debug.messageEnabled()) {
debug.message("IDPLogoutUtil.processLogoutRequest: " + "idpEntityID=" + idpEntityID + ", sessionIndex=" + sessionIndex);
}
if (sessionIndex == null) {
// this case won't happen
// according to the spec: SP has to send at least
// one sessionIndex, could be multiple (TODO: need
// to handle that above; but when IDP sends out
// logout request, it could omit sessionIndex list,
// which means all sessions on SP side, so SP side
// needs to care about this case
debug.error("IDPLogoutUtil.processLogoutRequest: " + "No session index in logout request");
status = SAML2Utils.generateStatus(SAML2Constants.REQUESTER, "");
break;
}
String remoteServiceURL = null;
if (isLBReq) {
// server id is the last two digit of the session index
String serverId = sessionIndex.substring(sessionIndex.length() - 2);
if (debug.messageEnabled()) {
debug.message("IDPSingleLogout.processLogoutRequest: " + "sessionIndex=" + sessionIndex + ", id=" + serverId);
}
// find out remote serice URL based on server id
remoteServiceURL = SAML2Utils.getRemoteServiceURL(serverId);
}
IDPSession idpSession = IDPCache.idpSessionsByIndices.get(sessionIndex);
if (idpSession == null && SAML2FailoverUtils.isSAML2FailoverEnabled()) {
// Read from SAML2 Token Repository
IDPSessionCopy idpSessionCopy = null;
try {
idpSessionCopy = (IDPSessionCopy) SAML2FailoverUtils.retrieveSAML2Token(sessionIndex);
} catch (SAML2TokenRepositoryException se) {
debug.error("IDPSingleLogout.processLogoutRequest: Error while deleting token from " + "SAML2 Token Repository for sessionIndex:" + sessionIndex, se);
}
// Copy back to IDPSession
if (idpSessionCopy != null) {
idpSession = new IDPSession(idpSessionCopy);
} else {
SAML2Utils.debug.error("IDPSessionCopy is NULL!!!");
}
}
if (idpSession == null) {
// peer then we have to route the request.
if (remoteServiceURL != null) {
boolean peerError = false;
String remoteLogoutURL = remoteServiceURL + SAML2Utils.removeDeployUri(request.getRequestURI());
String queryString = request.getQueryString();
if (queryString == null) {
remoteLogoutURL = remoteLogoutURL + "?isLBReq=false";
} else {
remoteLogoutURL = remoteLogoutURL + "?" + queryString + "&isLBReq=false";
}
LogoutResponse logoutRes = LogoutUtil.forwardToRemoteServer(logoutReq, remoteLogoutURL);
if ((logoutRes != null) && !isNameNotFound(logoutRes)) {
if ((isSuccess(logoutRes)) && (numSI > 0)) {
siList = LogoutUtil.getSessionIndex(logoutRes);
if (siList == null || siList.isEmpty()) {
peerError = false;
break;
}
}
} else {
peerError = true;
}
if (peerError || (siList != null && siList.size() > 0)) {
status = PARTIAL_LOGOUT_STATUS;
break;
} else {
status = SUCCESS_STATUS;
break;
}
} else {
debug.error("IDPLogoutUtil.processLogoutRequest: " + "IDP no longer has this session index " + sessionIndex);
status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, SAML2Utils.bundle.getString("invalidSessionIndex"));
break;
}
} else {
// signature.
if (!isVerified && !LogoutUtil.verifySLORequest(logoutReq, realm, logoutReq.getIssuer().getValue(), idpEntityID, SAML2Constants.IDP_ROLE)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInRequest"));
}
}
session = idpSession.getSession();
// handle external application logout if configured
BaseConfigType idpConfig = SAML2Utils.getSAML2MetaManager().getIDPSSOConfig(realm, idpEntityID);
List appLogoutURL = (List) SAML2MetaUtils.getAttributes(idpConfig).get(SAML2Constants.APP_LOGOUT_URL);
if (debug.messageEnabled()) {
debug.message("IDPLogoutUtil.processLogoutRequest: " + "external app logout URL= " + appLogoutURL);
}
if ((appLogoutURL != null) && (appLogoutURL.size() != 0)) {
SAML2Utils.postToAppLogout(request, (String) appLogoutURL.get(0), session);
}
List<NameIDandSPpair> list = idpSession.getNameIDandSPpairs();
int n = list.size();
if (debug.messageEnabled()) {
debug.message("IDPLogoutUtil.processLogoutRequest: " + "NameIDandSPpair for " + sessionIndex + " is " + list + ", size=" + n);
}
NameIDandSPpair pair = null;
// remove sending SP from the list
String spIssuer = logoutReq.getIssuer().getValue();
for (int i = 0; i < n; i++) {
pair = list.get(i);
if (pair.getSPEntityID().equals(spIssuer)) {
list.remove(i);
removeTransientNameIDFromCache(pair.getNameID());
break;
}
}
List partners = idpSession.getSessionPartners();
boolean cleanUp = true;
if (partners != null && !partners.isEmpty()) {
cleanUp = false;
}
n = list.size();
if (n == 0) {
// this is the case where there is no other
// session participant
status = destroyTokenAndGenerateStatus(sessionIndex, idpSession.getSession(), request, response, cleanUp);
if (cleanUp) {
IDPCache.idpSessionsByIndices.remove(sessionIndex);
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setIdpSessionCount((long) IDPCache.idpSessionsByIndices.size());
}
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
try {
SAML2FailoverUtils.deleteSAML2Token(sessionIndex);
} catch (SAML2TokenRepositoryException se) {
debug.error("IDPSingleLogout.processLogoutRequest: Error while deleting token from " + "SAML2 Token Repository for sessionIndex:" + sessionIndex, se);
}
}
IDPCache.authnContextCache.remove(sessionIndex);
}
break;
}
//We should save the originally used request binding to make sure the response is sent back using the
//correct binding.
idpSession.setOriginatingLogoutRequestBinding(binding);
// there are other SPs to be logged out
if (binding.equals(SAML2Constants.HTTP_REDIRECT) || binding.equals(SAML2Constants.HTTP_POST)) {
idpSession.setOriginatingLogoutRequestID(logoutReq.getID());
idpSession.setOriginatingLogoutSPEntityID(logoutReq.getIssuer().getValue());
}
int soapFailCount = 0;
for (int i = 0; i < n; i++) {
pair = list.remove(0);
removeTransientNameIDFromCache(pair.getNameID());
String spEntityID = pair.getSPEntityID();
if (debug.messageEnabled()) {
debug.message("IDPSingleLogout.processLogoutRequest: SP for " + sessionIndex + " is " + spEntityID);
}
List<SingleLogoutServiceElement> slosList = getSPSLOServiceEndpoints(realm, spEntityID);
// get IDP entity config in case of SOAP,for basic auth info
SPSSOConfigElement spConfig = null;
spConfig = SAML2Utils.getSAML2MetaManager().getSPSSOConfig(realm, spEntityID);
String uri = request.getRequestURI();
String metaAlias = SAML2MetaUtils.getMetaAliasByUri(uri);
HashMap paramsMap = new HashMap();
paramsMap.put(SAML2Constants.ROLE, SAML2Constants.IDP_ROLE);
StringBuffer requestID = null;
SingleLogoutServiceElement logoutEndpoint = LogoutUtil.getMostAppropriateSLOServiceLocation(slosList, idpSession.getOriginatingLogoutRequestBinding());
if (logoutEndpoint == null) {
continue;
}
try {
requestID = LogoutUtil.doLogout(metaAlias, spEntityID, null, logoutEndpoint, relayState, sessionIndex, pair.getNameID(), request, response, paramsMap, spConfig);
} catch (SAML2Exception ex) {
if (logoutEndpoint.getBinding().equals(SAML2Constants.SOAP)) {
debug.error("IDPSingleLogout.initiateLogoutRequest:", ex);
soapFailCount++;
continue;
} else {
throw ex;
}
}
String bindingUsed = logoutEndpoint.getBinding();
if (bindingUsed.equals(SAML2Constants.HTTP_REDIRECT) || bindingUsed.equals(SAML2Constants.HTTP_POST)) {
String requestIDStr = requestID.toString();
if (requestIDStr != null && requestIDStr.length() != 0) {
idpSession.setPendingLogoutRequestID(requestIDStr);
}
return null;
}
}
if (soapFailCount == n) {
throw new SAML2Exception(SAML2Utils.bundle.getString("sloFailed"));
} else if (soapFailCount > 0) {
throw new SAML2Exception(SAML2Utils.bundle.getString("partialLogout"));
}
spEntity = idpSession.getOriginatingLogoutSPEntityID();
if (binding.equals(SAML2Constants.HTTP_REDIRECT) || binding.equals(SAML2Constants.HTTP_POST)) {
sendLastResponse(idpSession, null, request, response, sessionIndex, session, realm, idpEntityID, relayState);
return null;
} else {
// binding is SOAP, generate logout response
// and send to initiating SP
status = destroyTokenAndGenerateStatus(sessionIndex, idpSession.getSession(), request, response, true);
if (cleanUp) {
IDPCache.idpSessionsByIndices.remove(sessionIndex);
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setIdpSessionCount((long) IDPCache.idpSessionsByIndices.size());
}
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
try {
SAML2FailoverUtils.deleteSAML2Token(sessionIndex);
} catch (SAML2TokenRepositoryException se) {
debug.error("IDPSingleLogout.processLogoutRequest: Error while deleting token from " + "SAML2 Token Repository for sessionIndex:" + sessionIndex, se);
}
}
IDPCache.authnContextCache.remove(sessionIndex);
}
}
} while (false);
} catch (SessionException ssoe) {
debug.error("IDPSingleLogout.processLogoutRequest: unable to get meta for ", ssoe);
status = SAML2Utils.generateStatus(idpEntityID, ssoe.toString());
} catch (SAML2Exception e) {
// show throw exception
e.printStackTrace();
SAML2Utils.debug.error("DB ERROR!!!");
}
// process multi-federation protocol
boolean isMultiProtocol = false;
try {
SessionProvider provider = SessionManager.getProvider();
if ((session != null) && (provider.isValid(session)) && MultiProtocolUtils.isMultipleProtocolSession(session, SingleLogoutManager.SAML2)) {
isMultiProtocol = true;
}
} catch (SessionException ex) {
//ignore
}
//here we are providing null for remote entity, because it's an unused variable in the method...
LogoutResponse logRes = LogoutUtil.generateResponse(status, logoutReq.getID(), SAML2Utils.createIssuer(idpEntityID), realm, SAML2Constants.IDP_ROLE, null);
if (!isMultiProtocol) {
return logRes;
} else {
try {
Set set = new HashSet();
set.add(session);
String sessUser = SessionManager.getProvider().getPrincipalName(session);
boolean isSOAPInitiated = binding.equals(SAML2Constants.SOAP);
SingleLogoutServiceElement endpoint = getLogoutResponseEndpoint(realm, spEntity, binding);
String location = getResponseLocation(endpoint);
logRes.setDestination(XMLUtils.escapeSpecialCharacters(location));
debug.message("IDPSingleLogout.processLogReq : call MP");
int retStat = SingleLogoutManager.getInstance().doIDPSingleLogout(set, sessUser, request, response, isSOAPInitiated, false, SingleLogoutManager.SAML2, realm, idpEntityID, spEntity, relayState, logoutReq.toXMLString(true, true), logRes.toXMLString(true, true), SingleLogoutManager.LOGOUT_SUCCEEDED_STATUS);
if (retStat != SingleLogoutManager.LOGOUT_REDIRECTED_STATUS) {
logRes = updateLogoutResponse(logRes, retStat);
return logRes;
} else {
return null;
}
} catch (SessionException ex) {
debug.error("IDPSingleLogout.ProcessLogoutRequest: SP " + "initiated SOAP logout", ex);
throw new SAML2Exception(ex.getMessage());
} catch (Exception ex) {
debug.error("IDPSingleLogout.ProcessLogoutRequest: SP " + "initiated SOAP logout (MP)", ex);
throw new SAML2Exception(ex.getMessage());
}
}
}
use of com.sun.identity.saml2.protocol.LogoutResponse in project OpenAM by OpenRock.
the class IDPSingleLogout method processLogoutResponse.
/**
* Gets and processes the Single <code>LogoutResponse</code> from SP,
* destroys the local session, checks response's issuer
* and inResponseTo.
*
* @param request the HttpServletRequest.
* @param response the HttpServletResponse.
* @param samlResponse <code>LogoutResponse</code> in the
* XML string format.
* @param relayState the target URL on successful
* <code>LogoutResponse</code>.
* @return true if jsp has sendRedirect for relayState, false otherwise
* @throws SAML2Exception if error processing
* <code>LogoutResponse</code>.
* @throws SessionException if error processing
* <code>LogoutResponse</code>.
*/
public static boolean processLogoutResponse(HttpServletRequest request, HttpServletResponse response, String samlResponse, String relayState) throws SAML2Exception, SessionException {
String method = "processLogoutResponse : ";
if (debug.messageEnabled()) {
debug.message(method + "samlResponse : " + samlResponse);
debug.message(method + "relayState : " + relayState);
}
String rmethod = request.getMethod();
String binding = SAML2Constants.HTTP_REDIRECT;
if (rmethod.equals("POST")) {
binding = SAML2Constants.HTTP_POST;
}
String metaAlias = SAML2MetaUtils.getMetaAliasByUri(request.getRequestURI());
String realm = SAML2Utils.getRealm(SAML2MetaUtils.getRealmByMetaAlias(metaAlias));
String idpEntityID = sm.getEntityByMetaAlias(metaAlias);
if (!SAML2Utils.isIDPProfileBindingSupported(realm, idpEntityID, SAML2Constants.SLO_SERVICE, binding)) {
debug.error("SLO service binding " + binding + " is not supported:" + idpEntityID);
throw new SAML2Exception(SAML2Utils.bundle.getString("unsupportedBinding"));
}
LogoutResponse logoutRes = null;
if (rmethod.equals("POST")) {
logoutRes = LogoutUtil.getLogoutResponseFromPost(samlResponse, response);
} else if (rmethod.equals("GET")) {
String decodedStr = SAML2Utils.decodeFromRedirect(samlResponse);
if (decodedStr == null) {
throw new SAML2Exception(SAML2Utils.bundle.getString("nullDecodedStrFromSamlResponse"));
}
logoutRes = ProtocolFactory.getInstance().createLogoutResponse(decodedStr);
}
if (logoutRes == null) {
if (debug.messageEnabled()) {
debug.message("IDPSingleLogout:processLogoutResponse: logoutRes " + "is null");
}
return false;
}
String spEntityID = logoutRes.getIssuer().getValue();
Issuer resIssuer = logoutRes.getIssuer();
String requestId = logoutRes.getInResponseTo();
SAML2Utils.verifyResponseIssuer(realm, idpEntityID, resIssuer, requestId);
boolean needToVerify = SAML2Utils.getWantLogoutResponseSigned(realm, idpEntityID, SAML2Constants.IDP_ROLE);
if (debug.messageEnabled()) {
debug.message(method + "metaAlias : " + metaAlias);
debug.message(method + "realm : " + realm);
debug.message(method + "idpEntityID : " + idpEntityID);
debug.message(method + "spEntityID : " + spEntityID);
}
if (needToVerify) {
boolean valid = false;
if (rmethod.equals("POST")) {
valid = LogoutUtil.verifySLOResponse(logoutRes, realm, spEntityID, idpEntityID, SAML2Constants.IDP_ROLE);
} else {
String queryString = request.getQueryString();
valid = SAML2Utils.verifyQueryString(queryString, realm, SAML2Constants.IDP_ROLE, spEntityID);
}
if (!valid) {
debug.error("Invalid signature in SLO Response.");
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInResponse"));
}
IDPSSODescriptorElement idpsso = sm.getIDPSSODescriptor(realm, idpEntityID);
String loc = null;
if (idpsso != null) {
List sloList = idpsso.getSingleLogoutService();
if (sloList != null && !sloList.isEmpty()) {
loc = LogoutUtil.getSLOResponseServiceLocation(sloList, binding);
if (loc == null || (loc.length() == 0)) {
loc = LogoutUtil.getSLOServiceLocation(sloList, binding);
}
}
}
if (!SAML2Utils.verifyDestination(logoutRes.getDestination(), loc)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidDestination"));
}
}
boolean doRelayState = processLogoutResponse(request, response, logoutRes, relayState, metaAlias, idpEntityID, spEntityID, realm, binding);
// IDPProxy
Map logoutResponseMap = (Map) IDPCache.logoutResponseCache.get(requestId);
if ((logoutResponseMap != null) && (!logoutResponseMap.isEmpty())) {
LogoutResponse logoutResp = (LogoutResponse) logoutResponseMap.get("LogoutResponse");
String location = (String) logoutResponseMap.get("Location");
String spEntity = (String) logoutResponseMap.get("spEntityID");
String idpEntity = (String) logoutResponseMap.get("idpEntityID");
if (logoutResp != null && location != null && spEntity != null && idpEntity != null) {
LogoutUtil.sendSLOResponse(response, request, logoutResp, location, relayState, "/", spEntity, SAML2Constants.SP_ROLE, idpEntity, binding);
return true;
}
}
return doRelayState;
}
use of com.sun.identity.saml2.protocol.LogoutResponse in project OpenAM by OpenRock.
the class DefaultFedletAdapter method onFedletSLOSuccessOrFailure.
private void onFedletSLOSuccessOrFailure(HttpServletRequest request, HttpServletResponse response, LogoutRequest logoutReq, LogoutResponse logoutRes, String hostedEntityID, String idpEntityID, String binding, boolean isSuccess) throws SAML2Exception {
String method = "DefaultFedletAdapter:onFedletSLOSuccessOrFailure:";
try {
if (logoutUrl == null) {
BaseConfigType spConfig = SAML2Utils.getSAML2MetaManager().getSPSSOConfig("/", hostedEntityID);
List appLogoutURL = (List) SAML2MetaUtils.getAttributes(spConfig).get(SAML2Constants.APP_LOGOUT_URL);
if ((appLogoutURL != null) && !appLogoutURL.isEmpty()) {
logoutUrl = (String) appLogoutURL.get(0);
}
}
if (logoutUrl == null) {
String deployuri = request.getRequestURI();
int slashLoc = deployuri.indexOf("/", 1);
if (slashLoc != -1) {
deployuri = deployuri.substring(0, slashLoc);
}
if (deployuri != null) {
String url = request.getRequestURL().toString();
int loc = url.indexOf(deployuri + "/");
if (loc != -1) {
logoutUrl = url.substring(0, loc + deployuri.length()) + "/logout";
}
}
}
if (logoutUrl == null) {
return;
}
URL url = new URL(logoutUrl);
HttpURLConnection conn = HttpURLConnectionManager.getConnection(url);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setFollowRedirects(false);
conn.setInstanceFollowRedirects(false);
// replay cookies
String strCookies = SAML2Utils.getCookiesString(request);
if (strCookies != null) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(method + "Sending cookies : " + strCookies);
}
conn.setRequestProperty("Cookie", strCookies);
}
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("IDP", URLEncDec.encode(idpEntityID));
conn.setRequestProperty("SP", URLEncDec.encode(hostedEntityID));
if (logoutReq != null) {
NameID nameID = logoutReq.getNameID();
if (nameID != null) {
conn.setRequestProperty("NameIDValue", URLEncDec.encode(nameID.getValue()));
}
List siList = logoutReq.getSessionIndex();
if ((siList != null) && (!siList.isEmpty())) {
conn.setRequestProperty("SessionIndex", URLEncDec.encode((String) siList.get(0)));
}
}
conn.setRequestProperty("Binding", binding);
if (isSuccess) {
conn.setRequestProperty("SLOStatus", "Success");
} else {
conn.setRequestProperty("SLOStatus", "Failure");
}
OutputStream outputStream = conn.getOutputStream();
// Write the request to the HTTP server.
outputStream.write("".getBytes());
outputStream.flush();
outputStream.close();
// Check response code
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(method + "Response code OK");
}
} else {
SAML2Utils.debug.error(method + "Response code NOT OK: " + conn.getResponseCode());
}
} catch (Exception e) {
}
return;
}
use of com.sun.identity.saml2.protocol.LogoutResponse in project OpenAM by OpenRock.
the class SPSingleLogout method isNameNotFound.
static boolean isNameNotFound(LogoutResponse logoutRes) {
Status status = logoutRes.getStatus();
String statusMessage = status.getStatusMessage();
return (status.getStatusCode().getValue().equals(SAML2Constants.RESPONDER) && statusMessage != null && statusMessage.equals(SAML2Utils.bundle.getString("invalid_name_identifier")));
}
use of com.sun.identity.saml2.protocol.LogoutResponse in project OpenAM by OpenRock.
the class SPSingleLogout method processLogoutRequest.
/**
* Gets and processes the Single <code>LogoutRequest</code> from IDP
* and return <code>LogoutResponse</code>.
*
* @param logoutReq <code>LogoutRequest</code> from IDP
* @param spEntityID name of host entity ID.
* @param realm name of host entity.
* @param request HTTP servlet request.
* @param response HTTP servlet response.
* @param isLBReq true if the request is for load balancing.
* @param binding value of <code>SAML2Constants.HTTP_REDIRECT</code> or
* <code>SAML2Constants.SOAP</code>.
* @param isVerified true if the request is verified already.
* @return LogoutResponse the target URL on successful
* <code>LogoutRequest</code>.
*/
public static LogoutResponse processLogoutRequest(LogoutRequest logoutReq, String spEntityID, String realm, HttpServletRequest request, HttpServletResponse response, boolean isLBReq, boolean destroySession, String binding, boolean isVerified) {
final String method = "processLogoutRequest : ";
NameID nameID = null;
Status status = null;
Issuer issuer = null;
String idpEntity = logoutReq.getIssuer().getValue();
String userId = null;
try {
do {
// TODO: check the NotOnOrAfter attribute of LogoutRequest
issuer = logoutReq.getIssuer();
String requestId = logoutReq.getID();
SAML2Utils.verifyRequestIssuer(realm, spEntityID, issuer, requestId);
issuer = SAML2Utils.createIssuer(spEntityID);
// get SessionIndex and NameID form LogoutRequest
List siList = logoutReq.getSessionIndex();
int numSI = 0;
if (siList != null) {
numSI = siList.size();
if (debug.messageEnabled()) {
debug.message(method + "Number of session indices in the logout request is " + numSI);
}
}
nameID = LogoutUtil.getNameIDFromSLORequest(logoutReq, realm, spEntityID, SAML2Constants.SP_ROLE);
if (nameID == null) {
debug.error(method + "LogoutRequest does not contain Name ID");
status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, SAML2Utils.bundle.getString("missing_name_identifier"));
break;
}
String infoKeyString = null;
infoKeyString = (new NameIDInfoKey(nameID.getValue(), spEntityID, idpEntity)).toValueString();
if (debug.messageEnabled()) {
debug.message(method + "infokey=" + infoKeyString);
}
if (SPCache.isFedlet) {
// verify request
if (!isVerified && !LogoutUtil.verifySLORequest(logoutReq, realm, idpEntity, spEntityID, SAML2Constants.SP_ROLE)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInRequest"));
}
// obtain fedlet adapter
FedletAdapter fedletAdapter = SAML2Utils.getFedletAdapterClass(spEntityID, realm);
boolean result = false;
if (fedletAdapter != null) {
// call adapter to do real logout
result = fedletAdapter.doFedletSLO(request, response, logoutReq, spEntityID, idpEntity, siList, nameID.getValue(), binding);
}
if (result) {
status = SUCCESS_STATUS;
} else {
status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, SAML2Utils.bundle.getString("appLogoutFailed"));
}
break;
}
List list = (List) SPCache.fedSessionListsByNameIDInfoKey.get(infoKeyString);
if (debug.messageEnabled()) {
debug.message(method + "SPFedsessions=" + list);
}
if ((list == null) || list.isEmpty()) {
String spQ = nameID.getSPNameQualifier();
if ((spQ == null) || (spQ.length() == 0)) {
infoKeyString = (new NameIDInfoKey(nameID.getValue(), spEntityID, nameID.getNameQualifier())).toValueString();
list = (List) SPCache.fedSessionListsByNameIDInfoKey.get(infoKeyString);
}
}
boolean foundPeer = false;
List remoteServiceURLs = null;
if (isLBReq) {
remoteServiceURLs = FSUtils.getRemoteServiceURLs(request);
foundPeer = remoteServiceURLs != null && !remoteServiceURLs.isEmpty();
}
if (debug.messageEnabled()) {
debug.message(method + "isLBReq = " + isLBReq + ", foundPeer = " + foundPeer);
}
if (list == null || list.isEmpty()) {
if (foundPeer) {
boolean peerError = false;
for (Iterator iter = remoteServiceURLs.iterator(); iter.hasNext(); ) {
String remoteLogoutURL = getRemoteLogoutURL((String) iter.next(), request);
LogoutResponse logoutRes = LogoutUtil.forwardToRemoteServer(logoutReq, remoteLogoutURL);
if ((logoutRes != null) && !isNameNotFound(logoutRes)) {
if (isSuccess(logoutRes)) {
if (numSI > 0) {
siList = LogoutUtil.getSessionIndex(logoutRes);
if (siList == null || siList.isEmpty()) {
peerError = false;
break;
}
}
} else {
peerError = true;
}
}
}
if (peerError || (siList != null && siList.size() > 0)) {
status = PARTIAL_LOGOUT_STATUS;
} else {
status = SUCCESS_STATUS;
}
} else {
debug.error(method + "invalid Name ID received");
status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, SAML2Utils.bundle.getString("invalid_name_identifier"));
}
break;
} else {
// find the session, do signature validation
if (!isVerified && !LogoutUtil.verifySLORequest(logoutReq, realm, logoutReq.getIssuer().getValue(), spEntityID, SAML2Constants.SP_ROLE)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInRequest"));
}
// invoke SPAdapter for preSingleLogoutProcess
try {
String tokenId = ((SPFedSession) list.iterator().next()).spTokenID;
Object token = sessionProvider.getSession(tokenId);
userId = sessionProvider.getPrincipalName(token);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPSingleLogout." + "processLogoutRequest, user = " + userId);
}
} catch (SessionException ex) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPSingleLogout." + "processLogoutRequest", ex);
}
}
userId = preSingleLogoutProcess(spEntityID, realm, request, response, userId, logoutReq, null, binding);
}
// get application logout URL
BaseConfigType spConfig = SAML2Utils.getSAML2MetaManager().getSPSSOConfig(realm, spEntityID);
List appLogoutURL = (List) SAML2MetaUtils.getAttributes(spConfig).get(SAML2Constants.APP_LOGOUT_URL);
if (debug.messageEnabled()) {
debug.message("IDPLogoutUtil.processLogoutRequest: " + "external app logout URL= " + appLogoutURL);
}
if (numSI == 0) {
// logout all fed sessions for this user
// between this SP and the IDP
List tokenIDsToBeDestroyed = new ArrayList();
synchronized (list) {
Iterator iter = list.listIterator();
while (iter.hasNext()) {
SPFedSession fedSession = (SPFedSession) iter.next();
tokenIDsToBeDestroyed.add(fedSession.spTokenID);
iter.remove();
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
}
}
}
for (Iterator iter = tokenIDsToBeDestroyed.listIterator(); iter.hasNext(); ) {
String tokenID = (String) iter.next();
Object token = null;
try {
token = sessionProvider.getSession(tokenID);
} catch (SessionException se) {
debug.error(method + "Could not create session from token ID = " + tokenID);
continue;
}
if (debug.messageEnabled()) {
debug.message(method + "destroy token " + tokenID);
}
// handle external application logout if configured
if ((appLogoutURL != null) && (appLogoutURL.size() != 0)) {
SAML2Utils.postToAppLogout(request, (String) appLogoutURL.get(0), token);
}
if (destroySession) {
sessionProvider.invalidateSession(token, request, response);
}
}
if (foundPeer) {
boolean peerError = false;
for (Iterator iter = remoteServiceURLs.iterator(); iter.hasNext(); ) {
String remoteLogoutURL = getRemoteLogoutURL((String) iter.next(), request);
LogoutResponse logoutRes = LogoutUtil.forwardToRemoteServer(logoutReq, remoteLogoutURL);
if ((logoutRes == null) || !(isSuccess(logoutRes) || isNameNotFound(logoutRes))) {
peerError = true;
}
}
if (peerError) {
status = PARTIAL_LOGOUT_STATUS;
} else {
status = SUCCESS_STATUS;
}
}
} else {
// logout only those fed sessions specified
// in logout request session list
String sessionIndex = null;
List siNotFound = new ArrayList();
for (int i = 0; i < numSI; i++) {
sessionIndex = (String) siList.get(i);
String tokenIDToBeDestroyed = null;
synchronized (list) {
Iterator iter = list.listIterator();
while (iter.hasNext()) {
SPFedSession fedSession = (SPFedSession) iter.next();
if (sessionIndex.equals(fedSession.idpSessionIndex)) {
if (debug.messageEnabled()) {
debug.message(method + " found si + " + sessionIndex);
}
tokenIDToBeDestroyed = fedSession.spTokenID;
iter.remove();
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
}
break;
}
}
}
if (tokenIDToBeDestroyed != null) {
try {
Object token = sessionProvider.getSession(tokenIDToBeDestroyed);
if (debug.messageEnabled()) {
debug.message(method + "destroy token (2) " + tokenIDToBeDestroyed);
}
// handle external application logout
if ((appLogoutURL != null) && (appLogoutURL.size() != 0)) {
SAML2Utils.postToAppLogout(request, (String) appLogoutURL.get(0), token);
}
if (destroySession) {
sessionProvider.invalidateSession(token, request, response);
}
} catch (SessionException se) {
debug.error(method + "Could not create " + "session from token ID = " + tokenIDToBeDestroyed);
}
} else {
siNotFound.add(sessionIndex);
}
}
if (isLBReq) {
if (foundPeer && !siNotFound.isEmpty()) {
boolean peerError = false;
LogoutRequest lReq = copyAndMakeMutable(logoutReq);
for (Iterator iter = remoteServiceURLs.iterator(); iter.hasNext(); ) {
lReq.setSessionIndex(siNotFound);
String remoteLogoutURL = getRemoteLogoutURL((String) iter.next(), request);
LogoutResponse logoutRes = LogoutUtil.forwardToRemoteServer(lReq, remoteLogoutURL);
if ((logoutRes != null) && !isNameNotFound(logoutRes)) {
if (isSuccess(logoutRes)) {
siNotFound = LogoutUtil.getSessionIndex(logoutRes);
} else {
peerError = true;
}
}
if (debug.messageEnabled()) {
debug.message(method + "siNotFound = " + siNotFound);
}
if (siNotFound == null || siNotFound.isEmpty()) {
peerError = false;
break;
}
}
if (peerError || (siNotFound != null && !siNotFound.isEmpty())) {
status = PARTIAL_LOGOUT_STATUS;
} else {
status = SUCCESS_STATUS;
}
} else {
status = SUCCESS_STATUS;
}
} else {
if (siNotFound.isEmpty()) {
status = SUCCESS_STATUS;
} else {
status = SAML2Utils.generateStatus(SAML2Constants.SUCCESS, SAML2Utils.bundle.getString("requestSuccess"));
LogoutUtil.setSessionIndex(status, siNotFound);
}
}
}
} while (false);
} catch (SessionException se) {
debug.error("processLogoutRequest: ", se);
status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, se.toString());
} catch (SAML2Exception e) {
debug.error("processLogoutRequest: " + "failed to create response", e);
status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, e.toString());
}
// create LogoutResponse
if (spEntityID == null) {
spEntityID = nameID.getSPNameQualifier();
}
LogoutResponse logResponse = LogoutUtil.generateResponse(status, logoutReq.getID(), issuer, realm, SAML2Constants.SP_ROLE, idpEntity);
if (isSuccess(logResponse)) {
// invoke SPAdapter for postSingleLogoutSuccess
postSingleLogoutSuccess(spEntityID, realm, request, response, userId, logoutReq, logResponse, binding);
}
return logResponse;
}
Aggregations