use of com.sun.identity.saml2.protocol.Extensions in project OpenAM by OpenRock.
the class IDPSingleLogout method initiateLogoutRequest.
/**
* Parses the request parameters and initiates the Logout
* Request to be sent to the SP.
*
* @param request the HttpServletRequest.
* @param response the HttpServletResponse.
* @param out the print writer for writing out presentation
* @param binding binding used for this request.
* @param paramsMap Map of all other parameters.
* Following parameters names with their respective
* String values are allowed in this paramsMap.
* "RelayState" - the target URL on successful Single Logout
* "Destination" - A URI Reference indicating the address to
* which the request has been sent.
* "Consent" - Specifies a URI a SAML defined identifier
* known as Consent Identifiers.
* "Extension" - Specifies a list of Extensions as list of
* String objects.
* @throws SAML2Exception if error initiating request to SP.
*/
public static void initiateLogoutRequest(HttpServletRequest request, HttpServletResponse response, PrintWriter out, String binding, Map paramsMap) throws SAML2Exception {
if (debug.messageEnabled()) {
debug.message("in initiateLogoutRequest");
debug.message("binding : " + binding);
debug.message("logoutAll : " + (String) paramsMap.get(SAML2Constants.LOGOUT_ALL));
debug.message("paramsMap : " + paramsMap);
}
boolean logoutall = false;
String logoutAllValue = (String) paramsMap.get(SAML2Constants.LOGOUT_ALL);
if ((logoutAllValue != null) && logoutAllValue.equalsIgnoreCase("true")) {
logoutall = true;
}
String metaAlias = (String) paramsMap.get(SAML2Constants.IDP_META_ALIAS);
try {
Object session = sessionProvider.getSession(request);
String sessUser = sessionProvider.getPrincipalName(session);
if (session == null) {
throw new SAML2Exception(SAML2Utils.bundle.getString("nullSSOToken"));
}
if (metaAlias == null) {
String[] values = sessionProvider.getProperty(session, SAML2Constants.IDP_META_ALIAS);
if (values != null && values.length != 0) {
metaAlias = values[0];
}
}
if (metaAlias == null) {
throw new SAML2Exception(SAML2Utils.bundle.getString("nullIDPMetaAlias"));
}
paramsMap.put(SAML2Constants.METAALIAS, metaAlias);
String realm = SAML2Utils.getRealm(SAML2MetaUtils.getRealmByMetaAlias(metaAlias));
String idpEntityID = sm.getEntityByMetaAlias(metaAlias);
if (idpEntityID == null) {
debug.error("Identity Provider ID is missing");
String[] data = { idpEntityID };
LogUtil.error(Level.INFO, LogUtil.INVALID_IDP, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("nullIDPEntityID"));
}
// clean up session index
String idpSessionIndex = IDPSSOUtil.getSessionIndex(session);
if (idpSessionIndex == null) {
if (debug.messageEnabled()) {
debug.message("No SP session participant(s)");
}
MultiProtocolUtils.invalidateSession(session, request, response, SingleLogoutManager.SAML2);
return;
}
// then send the request to the original server
if (!SAML2FailoverUtils.isSAML2FailoverEnabled() && isMisroutedRequest(request, response, out, session)) {
return;
} else {
if (debug.messageEnabled()) {
debug.message("IDPSingleLogout.initiateLogoutRequest: " + "SAML2 Failover will be attempted. Be sure SFO is " + "properly configured or the attempt will fail");
}
}
IDPSession idpSession = IDPCache.idpSessionsByIndices.get(idpSessionIndex);
if (idpSession == null) {
if (debug.messageEnabled()) {
debug.message("IDPSLO.initiateLogoutRequest: " + "IDP Session with session index " + idpSessionIndex + " already removed.");
}
try {
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
SAML2FailoverUtils.deleteSAML2Token(idpSessionIndex);
}
} catch (SAML2TokenRepositoryException se) {
debug.error("IDPSingleLogout.initiateLogoutReq: Error while deleting token from " + "SAML2 Token Repository for idpSessionIndex:" + idpSessionIndex, se);
}
IDPCache.authnContextCache.remove(idpSessionIndex);
MultiProtocolUtils.invalidateSession(session, request, response, SingleLogoutManager.SAML2);
return;
}
if (debug.messageEnabled()) {
debug.message("idpSessionIndex=" + idpSessionIndex);
}
List<NameIDandSPpair> list = idpSession.getNameIDandSPpairs();
int n = list.size();
if (debug.messageEnabled()) {
debug.message("IDPSingleLogout.initiateLogoutReq:" + " NameIDandSPpairs=" + list + ", size=" + n);
}
if (n == 0) {
if (debug.messageEnabled()) {
debug.message("No SP session participant(s)");
}
IDPCache.idpSessionsByIndices.remove(idpSessionIndex);
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setIdpSessionCount((long) IDPCache.idpSessionsByIndices.size());
}
try {
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
SAML2FailoverUtils.deleteSAML2Token(idpSessionIndex);
}
} catch (SAML2TokenRepositoryException se) {
debug.error("IDPSingleLogout.initiateLogoutReq: Error while deleting token from " + "SAML2 Token Repository for idpSessionIndex:" + idpSessionIndex, se);
}
IDPCache.authnContextCache.remove(idpSessionIndex);
MultiProtocolUtils.invalidateSession(session, request, response, SingleLogoutManager.SAML2);
return;
}
String relayState = (String) paramsMap.get(SAML2Constants.RELAY_STATE);
// Validate the RelayState URL.
SAML2Utils.validateRelayStateURL(realm, idpEntityID, relayState, SAML2Constants.IDP_ROLE);
int soapFailCount = 0;
idpSession.setOriginatingLogoutRequestBinding(binding);
for (int i = 0; i < n; i++) {
NameIDandSPpair pair = list.remove(0);
removeTransientNameIDFromCache(pair.getNameID());
String spEntityID = pair.getSPEntityID();
if (debug.messageEnabled()) {
debug.message("IDPSingleLogout.initLogoutReq: processing spEntityID " + spEntityID);
}
List extensionsList = LogoutUtil.getExtensionsList(paramsMap);
List<SingleLogoutServiceElement> slosList = getSPSLOServiceEndpoints(realm, spEntityID);
// get IDP entity config in case of SOAP, for basic auth info
SPSSOConfigElement spConfig = sm.getSPSSOConfig(realm, spEntityID);
if (logoutall == true) {
idpSessionIndex = null;
}
SingleLogoutServiceElement logoutEndpoint = LogoutUtil.getMostAppropriateSLOServiceLocation(slosList, idpSession.getOriginatingLogoutRequestBinding());
if (logoutEndpoint == null) {
continue;
}
StringBuffer requestID = null;
try {
requestID = LogoutUtil.doLogout(metaAlias, spEntityID, extensionsList, logoutEndpoint, relayState, idpSessionIndex, 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 requestIDStr = requestID.toString();
String bindingUsed = logoutEndpoint.getBinding();
if (debug.messageEnabled()) {
debug.message("\nIDPSLO.requestIDStr = " + requestIDStr + "\nbinding = " + bindingUsed);
}
if (!requestIDStr.isEmpty() && (bindingUsed.equals(SAML2Constants.HTTP_REDIRECT) || bindingUsed.equals(SAML2Constants.HTTP_POST))) {
idpSession.setPendingLogoutRequestID(requestIDStr);
idpSession.setLogoutAll(logoutall);
Map logoutMap = (Map) paramsMap.get("LogoutMap");
if (logoutMap != null && !logoutMap.isEmpty()) {
IDPCache.logoutResponseCache.put(requestIDStr, (Map) paramsMap.get("LogoutMap"));
}
return;
}
}
//requested binding, or SOAP was used for the logout (or the mixture of this two).
if (logoutall == true) {
String userID = sessionProvider.getPrincipalName(idpSession.getSession());
destroyAllTokenForUser(userID, request, response);
} else {
MultiProtocolUtils.invalidateSession(idpSession.getSession(), request, response, SingleLogoutManager.SAML2);
IDPCache.idpSessionsByIndices.remove(idpSessionIndex);
if (agent != null && agent.isRunning() && saml2Svc != null) {
saml2Svc.setIdpSessionCount((long) IDPCache.idpSessionsByIndices.size());
}
IDPCache.authnContextCache.remove(idpSessionIndex);
}
//handling the case when the auth was initiated with HTTP-Redirect, but only SOAP or no SLO endpoint was
//available, and also the case when the whole logout process was using SOAP binding from the beginning
int logoutStatus = SingleLogoutManager.LOGOUT_SUCCEEDED_STATUS;
boolean isMultiProtocol = MultiProtocolUtils.isMultipleProtocolSession(request, SingleLogoutManager.SAML2);
//TODO: would be nice to actually return the correct message in idpSingleLogoutInit.jsp
if (soapFailCount == n) {
if (isMultiProtocol) {
logoutStatus = SingleLogoutManager.LOGOUT_FAILED_STATUS;
}
} else if (soapFailCount > 0) {
if (isMultiProtocol) {
logoutStatus = SingleLogoutManager.LOGOUT_PARTIAL_STATUS;
}
}
// processing multi-federation protocol session
if (isMultiProtocol) {
Set set = new HashSet();
set.add(session);
boolean isSOAPInitiated = binding.equals(SAML2Constants.SOAP) ? true : false;
int retStat = SingleLogoutManager.LOGOUT_SUCCEEDED_STATUS;
try {
debug.message("IDPSingleLogout.initLogReq: MP");
retStat = SingleLogoutManager.getInstance().doIDPSingleLogout(set, sessUser, request, response, isSOAPInitiated, true, SingleLogoutManager.SAML2, realm, idpEntityID, null, relayState, null, null, logoutStatus);
} catch (Exception ex) {
debug.warning("IDPSingleLogout.initiateLoogutReq: MP", ex);
throw new SAML2Exception(ex.getMessage());
}
if (debug.messageEnabled()) {
debug.message("IDPSingleLogout.initLogoutRequest: " + "SLOManager return status = " + retStat);
}
switch(retStat) {
case SingleLogoutManager.LOGOUT_FAILED_STATUS:
throw new SAML2Exception(SAML2Utils.bundle.getString("sloFailed"));
case SingleLogoutManager.LOGOUT_PARTIAL_STATUS:
throw new SAML2Exception(SAML2Utils.bundle.getString("partialLogout"));
default:
break;
}
}
} catch (SAML2MetaException sme) {
debug.error("Error retreiving metadata", sme);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
} catch (SessionException ssoe) {
debug.error("SessionException: ", ssoe);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
}
use of com.sun.identity.saml2.protocol.Extensions in project OpenAM by OpenRock.
the class SPSSOFederate method createAuthnRequest.
/**
* Create an AuthnRequest.
*
* @param realmName the authentication realm for this request
* @param spEntityID the entity id for the service provider
* @param paramsMap the map of parameters for the authentication request
* @param spConfigMap the configuration map for the service provider
* @param extensionsList a list of extendsions for the authentication request
* @param spsso the SPSSODescriptorElement for theservcie provider
* @param idpsso the IDPSSODescriptorElement for the identity provider
* @param ssourl the url for the single sign on request
* @param isForECP boolean to indicatge if the request originated from an ECP
* @return a new AuthnRequest object
* @throws SAML2Exception
*/
public static AuthnRequest createAuthnRequest(final String realmName, final String spEntityID, final Map paramsMap, final Map spConfigMap, final List extensionsList, final SPSSODescriptorElement spsso, final IDPSSODescriptorElement idpsso, final String ssourl, final boolean isForECP) throws SAML2Exception {
// generate unique request ID
String requestID = SAML2Utils.generateID();
if ((requestID == null) || (requestID.length() == 0)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("cannotGenerateID"));
}
// retrieve data from the params map and if not found get
// default values from the SPConfig Attributes
// destinationURI required if message is signed.
String destinationURI = getParameter(paramsMap, SAML2Constants.DESTINATION);
Boolean isPassive = doPassive(paramsMap, spConfigMap);
Boolean isforceAuthn = isForceAuthN(paramsMap, spConfigMap);
boolean allowCreate = isAllowCreate(paramsMap, spConfigMap);
boolean includeRequestedAuthnContextFlag = includeRequestedAuthnContext(paramsMap, spConfigMap);
String consent = getParameter(paramsMap, SAML2Constants.CONSENT);
Extensions extensions = createExtensions(extensionsList);
String nameIDPolicyFormat = getParameter(paramsMap, SAML2Constants.NAMEID_POLICY_FORMAT);
// get NameIDPolicy Element
NameIDPolicy nameIDPolicy = createNameIDPolicy(spEntityID, nameIDPolicyFormat, allowCreate, spsso, idpsso, realmName, paramsMap);
Issuer issuer = createIssuer(spEntityID);
Integer acsIndex = getIndex(paramsMap, SAML2Constants.ACS_URL_INDEX);
Integer attrIndex = getIndex(paramsMap, SAML2Constants.ATTR_INDEX);
String protocolBinding = isForECP ? SAML2Constants.PAOS : getParameter(paramsMap, "binding");
OrderedSet acsSet = getACSUrl(spsso, protocolBinding);
String acsURL = (String) acsSet.get(0);
protocolBinding = (String) acsSet.get(1);
if (!SAML2Utils.isSPProfileBindingSupported(realmName, spEntityID, SAML2Constants.ACS_SERVICE, protocolBinding)) {
SAML2Utils.debug.error("SPSSOFederate.createAuthnRequest:" + protocolBinding + "is not supported for " + spEntityID);
String[] data = { spEntityID, protocolBinding };
LogUtil.error(Level.INFO, LogUtil.BINDING_NOT_SUPPORTED, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("unsupportedBinding"));
}
AuthnRequest authnReq = ProtocolFactory.getInstance().createAuthnRequest();
if (!isForECP) {
if ((destinationURI == null) || (destinationURI.length() == 0)) {
authnReq.setDestination(XMLUtils.escapeSpecialCharacters(ssourl));
} else {
authnReq.setDestination(XMLUtils.escapeSpecialCharacters(destinationURI));
}
}
authnReq.setConsent(consent);
authnReq.setIsPassive(isPassive);
authnReq.setForceAuthn(isforceAuthn);
authnReq.setAttributeConsumingServiceIndex(attrIndex);
authnReq.setAssertionConsumerServiceIndex(acsIndex);
authnReq.setAssertionConsumerServiceURL(XMLUtils.escapeSpecialCharacters(acsURL));
authnReq.setProtocolBinding(protocolBinding);
authnReq.setIssuer(issuer);
authnReq.setNameIDPolicy(nameIDPolicy);
if (includeRequestedAuthnContextFlag) {
authnReq.setRequestedAuthnContext(createReqAuthnContext(realmName, spEntityID, paramsMap, spConfigMap));
}
if (extensions != null) {
authnReq.setExtensions(extensions);
}
// Required attributes in authn request
authnReq.setID(requestID);
authnReq.setVersion(SAML2Constants.VERSION_2_0);
authnReq.setIssueInstant(new Date());
//IDP Proxy
Boolean enableIDPProxy = getAttrValueFromMap(spConfigMap, SAML2Constants.ENABLE_IDP_PROXY);
if ((enableIDPProxy != null) && enableIDPProxy.booleanValue()) {
Scoping scoping = ProtocolFactory.getInstance().createScoping();
String proxyCountParam = getParameter(spConfigMap, SAML2Constants.IDP_PROXY_COUNT);
if (proxyCountParam != null && (!proxyCountParam.equals(""))) {
scoping.setProxyCount(new Integer(proxyCountParam));
}
List proxyIDPs = (List) spConfigMap.get(SAML2Constants.IDP_PROXY_LIST);
if (proxyIDPs != null && !proxyIDPs.isEmpty()) {
Iterator iter = proxyIDPs.iterator();
ArrayList list = new ArrayList();
while (iter.hasNext()) {
IDPEntry entry = ProtocolFactory.getInstance().createIDPEntry();
entry.setProviderID((String) iter.next());
list.add(entry);
}
IDPList idpList = ProtocolFactory.getInstance().createIDPList();
idpList.setIDPEntries(list);
scoping.setIDPList(idpList);
}
authnReq.setScoping(scoping);
}
return authnReq;
}
use of com.sun.identity.saml2.protocol.Extensions in project OpenAM by OpenRock.
the class LogoutUtil method doLogout.
public static StringBuffer doLogout(String metaAlias, String recipientEntityID, List extensionsList, EndpointType logoutEndpoint, String relayState, String sessionIndex, NameID nameID, HttpServletRequest request, HttpServletResponse response, Map paramsMap, BaseConfigType config) throws SAML2Exception, SessionException {
StringBuffer logoutRequestID = new StringBuffer();
String classMethod = "LogoutUtil.doLogout: ";
String requesterEntityID = metaManager.getEntityByMetaAlias(metaAlias);
String realm = SAML2MetaUtils.getRealmByMetaAlias(metaAlias);
String hostEntityRole = SAML2Utils.getHostEntityRole(paramsMap);
String location = null;
String binding = null;
if (logoutEndpoint != null) {
location = logoutEndpoint.getLocation();
binding = logoutEndpoint.getBinding();
} else {
debug.error(classMethod + "Unable to find the recipient's single logout service with the binding " + binding);
throw new SAML2Exception(SAML2Utils.bundle.getString("sloServiceNotfound"));
}
if (debug.messageEnabled()) {
debug.message(classMethod + "Entering ..." + "\nrequesterEntityID=" + requesterEntityID + "\nrecipientEntityID=" + recipientEntityID + "\nbinding=" + binding + "\nrelayState=" + relayState + "\nsessionIndex=" + sessionIndex);
}
// generate unique request ID
String requestID = SAML2Utils.generateID();
if ((requestID == null) || (requestID.length() == 0)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("cannotGenerateID"));
}
// retrieve data from the params map
// destinationURI required if message is signed.
String destinationURI = SAML2Utils.getParameter(paramsMap, SAML2Constants.DESTINATION);
String consent = SAML2Utils.getParameter(paramsMap, SAML2Constants.CONSENT);
Extensions extensions = createExtensions(extensionsList);
Issuer issuer = SAML2Utils.createIssuer(requesterEntityID);
// construct LogoutRequest
LogoutRequest logoutReq = null;
try {
logoutReq = ProtocolFactory.getInstance().createLogoutRequest();
} catch (Exception e) {
debug.error(classMethod + "Unable to create LogoutRequest : ", e);
throw new SAML2Exception(SAML2Utils.bundle.getString("errorCreatingLogoutRequest"));
}
// set required attributes / elements
logoutReq.setID(requestID);
logoutReq.setVersion(SAML2Constants.VERSION_2_0);
logoutReq.setIssueInstant(new Date());
setNameIDForSLORequest(logoutReq, nameID, realm, requesterEntityID, hostEntityRole, recipientEntityID);
// set optional attributes / elements
logoutReq.setDestination(XMLUtils.escapeSpecialCharacters(destinationURI));
logoutReq.setConsent(consent);
logoutReq.setIssuer(issuer);
if (hostEntityRole.equals(SAML2Constants.IDP_ROLE)) {
// use the assertion effective time (in seconds)
int effectiveTime = SAML2Constants.ASSERTION_EFFECTIVE_TIME;
String effectiveTimeStr = SAML2Utils.getAttributeValueFromSSOConfig(realm, requesterEntityID, SAML2Constants.IDP_ROLE, SAML2Constants.ASSERTION_EFFECTIVE_TIME_ATTRIBUTE);
if (effectiveTimeStr != null) {
try {
effectiveTime = Integer.parseInt(effectiveTimeStr);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "got effective time from config:" + effectiveTime);
}
} catch (NumberFormatException nfe) {
SAML2Utils.debug.error(classMethod + "Failed to get assertion effective time from " + "IDP SSO config: ", nfe);
effectiveTime = SAML2Constants.ASSERTION_EFFECTIVE_TIME;
}
}
Date date = new Date();
date.setTime(date.getTime() + effectiveTime * 1000);
logoutReq.setNotOnOrAfter(date);
}
if (extensions != null) {
logoutReq.setExtensions(extensions);
}
if (sessionIndex != null) {
List list = new ArrayList();
list.add(sessionIndex);
logoutReq.setSessionIndex(list);
}
debug.message(classMethod + "Recipient's single logout service location = " + location);
if (destinationURI == null || destinationURI.isEmpty()) {
logoutReq.setDestination(XMLUtils.escapeSpecialCharacters(location));
}
if (debug.messageEnabled()) {
debug.message(classMethod + "SLO Request before signing : ");
debug.message(logoutReq.toXMLString(true, true));
}
if (binding.equals(SAML2Constants.HTTP_REDIRECT)) {
try {
doSLOByHttpRedirect(logoutReq.toXMLString(true, true), location, relayState, realm, requesterEntityID, hostEntityRole, recipientEntityID, response);
logoutRequestID.append(requestID);
String[] data = { location };
LogUtil.access(Level.INFO, LogUtil.REDIRECT_TO_IDP, data, null);
} catch (Exception e) {
debug.error("Exception :", e);
throw new SAML2Exception(SAML2Utils.bundle.getString("errorRedirectingLogoutRequest"));
}
} else if (binding.equals(SAML2Constants.SOAP)) {
logoutRequestID.append(requestID);
signSLORequest(logoutReq, realm, requesterEntityID, hostEntityRole, recipientEntityID);
if (debug.messageEnabled()) {
debug.message(classMethod + "SLO Request after signing : ");
debug.message(logoutReq.toXMLString(true, true));
}
location = SAML2Utils.fillInBasicAuthInfo(config, location);
doSLOBySOAP(requestID, logoutReq, location, realm, requesterEntityID, hostEntityRole, request, response);
} else if (binding.equals(SAML2Constants.HTTP_POST)) {
logoutRequestID.append(requestID);
signSLORequest(logoutReq, realm, requesterEntityID, hostEntityRole, recipientEntityID);
if (debug.messageEnabled()) {
debug.message(classMethod + "SLO Request after signing : ");
debug.message(logoutReq.toXMLString(true, true));
}
doSLOByPOST(requestID, logoutReq.toXMLString(true, true), location, relayState, realm, requesterEntityID, hostEntityRole, response, request);
}
SPCache.logoutRequestIDHash.put(logoutRequestID.toString(), logoutReq);
return logoutRequestID;
}
use of com.sun.identity.saml2.protocol.Extensions in project OpenAM by OpenRock.
the class LogoutUtil method createExtensions.
/* Creates Extensions */
private static com.sun.identity.saml2.protocol.Extensions createExtensions(List extensionsList) throws SAML2Exception {
Extensions extensions = null;
if (extensionsList != null && !extensionsList.isEmpty()) {
extensions = ProtocolFactory.getInstance().createExtensions();
extensions.setAny(extensionsList);
}
return extensions;
}
use of com.sun.identity.saml2.protocol.Extensions in project OpenAM by OpenRock.
the class RequestAbstractImpl method parseDOMChileElements.
/**
* Parses child elements of the Docuemnt Element for this object.
*
* @param iter the child elements iterator.
* @throws SAML2Exception if error parsing the Document Element.
*/
protected void parseDOMChileElements(ListIterator iter) throws SAML2Exception {
AssertionFactory assertionFactory = AssertionFactory.getInstance();
ProtocolFactory protoFactory = ProtocolFactory.getInstance();
while (iter.hasNext()) {
Element childElement = (Element) iter.next();
String localName = childElement.getLocalName();
if (SAML2Constants.ISSUER.equals(localName)) {
validateIssuer();
nameID = assertionFactory.createIssuer(childElement);
} else if (SAML2Constants.SIGNATURE.equals(localName)) {
validateSignature();
signatureString = XMLUtils.print(childElement);
isSigned = true;
} else if (SAML2Constants.EXTENSIONS.equals(localName)) {
validateExtensions();
extensions = protoFactory.createExtensions(childElement);
} else {
iter.previous();
break;
}
}
}
Aggregations