use of org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException in project OpenAM by OpenRock.
the class SAML2CTSPersistentStore method retrieveSAML2TokensWithSecondaryKey.
/**
*{@inheritDoc}
*/
@Override
public List<Object> retrieveSAML2TokensWithSecondaryKey(String secondaryKey) throws SAML2TokenRepositoryException {
secondaryKey = tokenIdFactory.toSAMLSecondaryTokenId(secondaryKey);
try {
TokenFilter filter = new TokenFilterBuilder().withAttribute(SAMLTokenField.SECONDARY_KEY.getField(), secondaryKey).build();
Collection<Token> tokens = persistentStore.query(filter);
List<Object> results = new ArrayList<Object>(tokens.size());
for (Token token : tokens) {
SAMLToken samlToken = tokenAdapter.fromToken(token);
results.add(samlToken.getToken());
}
return results;
} catch (CoreTokenException e) {
debug.error("SAML2CTSPersistentStore.retrieveSAML2TokensWithSecondaryKey(): failed to retrieve SAML2 " + "tokens using secondary key:" + secondaryKey, e);
throw new SAML2TokenRepositoryException(e.getMessage(), e);
}
}
use of org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException in project OpenAM by OpenRock.
the class SPACSUtils method processResponse.
/**
* Authenticates user with <code>Response</code>.
* Auth session upgrade will be called if input session is
* not null.
* Otherwise, saml2 auth module is called. The name of the auth module
* is retrieved from <code>SPSSOConfig</code>. If not found, "SAML2" will
* be used.
*
* @param request HTTP Servlet request
* @param response HTTP Servlet response.
* @param out the print writer for writing out presentation
* @param metaAlias metaAlias for the service provider
* @param session input session object. It could be null.
* @param respInfo <code>ResponseInfo</code> to be verified.
* @param realm realm or organization name of the service provider.
* @param hostEntityId hosted service provider Entity ID.
* @param metaManager <code>SAML2MetaManager</code> instance for meta operation.
* @param auditor a <code>SAML2EventLogger</code> auditor object to hook into
* tracking information for the saml request
* @return <code>Object</code> which holds result of the session.
* @throws SAML2Exception if the processing failed.
*/
public static Object processResponse(HttpServletRequest request, HttpServletResponse response, PrintWriter out, String metaAlias, Object session, ResponseInfo respInfo, String realm, String hostEntityId, SAML2MetaManager metaManager, SAML2EventLogger auditor) throws SAML2Exception {
String classMethod = "SPACSUtils.processResponse: ";
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "Response : " + respInfo.getResponse());
}
Map smap = null;
try {
// check Response/Assertion and get back a Map of relevant data
smap = SAML2Utils.verifyResponse(request, response, respInfo.getResponse(), realm, hostEntityId, respInfo.getProfileBinding());
} catch (SAML2Exception se) {
// invoke SPAdapter for failure
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.INVALID_RESPONSE, se);
throw se;
}
com.sun.identity.saml2.assertion.Subject assertionSubject = (com.sun.identity.saml2.assertion.Subject) smap.get(SAML2Constants.SUBJECT);
NameID nameId = assertionSubject.getNameID();
EncryptedID encId = assertionSubject.getEncryptedID();
Assertion authnAssertion = (Assertion) smap.get(SAML2Constants.POST_ASSERTION);
String sessionIndex = (String) smap.get(SAML2Constants.SESSION_INDEX);
respInfo.setSessionIndex(sessionIndex);
Integer authLevel = (Integer) smap.get(SAML2Constants.AUTH_LEVEL);
Long maxSessionTime = (Long) smap.get(SAML2Constants.MAX_SESSION_TIME);
String inRespToResp = (String) smap.get(SAML2Constants.IN_RESPONSE_TO);
List assertions = (List) smap.get(SAML2Constants.ASSERTIONS);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "Assertions : " + assertions);
}
SPSSOConfigElement spssoconfig = metaManager.getSPSSOConfig(realm, hostEntityId);
// get mappers
SPAccountMapper acctMapper = SAML2Utils.getSPAccountMapper(realm, hostEntityId);
SPAttributeMapper attrMapper = SAML2Utils.getSPAttributeMapper(realm, hostEntityId);
String assertionEncryptedAttr = SAML2Utils.getAttributeValueFromSPSSOConfig(spssoconfig, SAML2Constants.WANT_ASSERTION_ENCRYPTED);
boolean needAttributeEncrypted = getNeedAttributeEncrypted(assertionEncryptedAttr, spssoconfig);
boolean needNameIDEncrypted = getNeedNameIDEncrypted(assertionEncryptedAttr, spssoconfig);
Set<PrivateKey> decryptionKeys = KeyUtil.getDecryptionKeys(spssoconfig);
if (needNameIDEncrypted && encId == null) {
SAML2Utils.debug.error(classMethod + "process: NameID was not encrypted.");
SAML2Exception se = new SAML2Exception(SAML2Utils.bundle.getString("nameIDNotEncrypted"));
// invoke SPAdapter for failure
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.INVALID_RESPONSE, se);
throw se;
}
if (encId != null) {
try {
nameId = encId.decrypt(decryptionKeys);
} catch (SAML2Exception se) {
// invoke SPAdapter for failure
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.INVALID_RESPONSE, se);
throw se;
}
}
respInfo.setNameId(nameId);
SPSSODescriptorElement spDesc = null;
try {
spDesc = metaManager.getSPSSODescriptor(realm, hostEntityId);
} catch (SAML2MetaException ex) {
SAML2Utils.debug.error(classMethod, ex);
}
if (spDesc == null) {
SAML2Exception se = new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_META_DATA_ERROR, se);
throw se;
}
String nameIDFormat = nameId.getFormat();
if (nameIDFormat != null) {
List spNameIDFormatList = spDesc.getNameIDFormat();
if ((spNameIDFormatList != null) && (!spNameIDFormatList.isEmpty()) && (!spNameIDFormatList.contains(nameIDFormat))) {
Object[] args = { nameIDFormat };
SAML2Exception se = new SAML2Exception(SAML2Utils.BUNDLE_NAME, "unsupportedNameIDFormatSP", args);
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.INVALID_RESPONSE, se);
throw se;
}
}
boolean isTransient = SAML2Constants.NAMEID_TRANSIENT_FORMAT.equals(nameIDFormat);
boolean isPersistent = SAML2Constants.PERSISTENT.equals(nameIDFormat);
boolean ignoreProfile = SAML2PluginsUtils.isIgnoredProfile(realm);
String existUserName = null;
SessionProvider sessionProvider = null;
try {
sessionProvider = SessionManager.getProvider();
} catch (SessionException se) {
// invoke SPAdapter for failure
SAML2Exception se2 = new SAML2Exception(se);
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_SESSION_ERROR, se2);
throw se2;
}
if (session != null) {
try {
existUserName = sessionProvider.getPrincipalName(session);
} catch (SessionException se) {
// invoke SPAdapter for failure
SAML2Exception se2 = new SAML2Exception(se);
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_SESSION_ERROR, se2);
throw se2;
}
}
String remoteHostId = authnAssertion.getIssuer().getValue();
String userName = null;
boolean isNewAccountLink = false;
boolean shouldPersistNameID = isPersistent || (!isTransient && !ignoreProfile && acctMapper.shouldPersistNameIDFormat(realm, hostEntityId, remoteHostId, nameIDFormat));
try {
if (shouldPersistNameID) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "querying data store for existing federation links: realm = " + realm + " hostEntityID = " + hostEntityId + " remoteEntityID = " + remoteHostId);
}
try {
userName = SAML2Utils.getDataStoreProvider().getUserID(realm, SAML2Utils.getNameIDKeyMap(nameId, hostEntityId, remoteHostId, realm, SAML2Constants.SP_ROLE));
} catch (DataStoreProviderException dse) {
SAML2Utils.debug.error(classMethod + "DataStoreProviderException whilst retrieving NameID " + "information", dse);
throw new SAML2Exception(dse.getMessage());
}
}
if (userName == null) {
userName = acctMapper.getIdentity(authnAssertion, hostEntityId, realm);
isNewAccountLink = true;
}
} catch (SAML2Exception se) {
// invoke SPAdapter for failure
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_NO_USER_MAPPING, se);
throw se;
}
if (userName == null && respInfo.isLocalLogin()) {
// In case we just got authenticated locally, we should accept the freshly authenticated session's principal
// as the username corresponding to the received assertion.
userName = existUserName;
}
if (null != auditor) {
auditor.setUserId(userName);
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "process: userName =[" + userName + "]");
}
List attrs = null;
for (Iterator it = assertions.iterator(); it.hasNext(); ) {
Assertion assertion = (Assertion) it.next();
List origAttrs = getSAMLAttributes(assertion, needAttributeEncrypted, decryptionKeys);
if (origAttrs != null && !origAttrs.isEmpty()) {
if (attrs == null) {
attrs = new ArrayList();
}
attrs.addAll(origAttrs);
}
}
Map attrMap = null;
if (attrs != null) {
try {
attrMap = attrMapper.getAttributes(attrs, userName, hostEntityId, remoteHostId, realm);
} catch (SAML2Exception se) {
// invoke SPAdapter for failure
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_ATTRIBUTE_MAPPING, se);
throw se;
}
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "process: remoteHostId = " + remoteHostId);
SAML2Utils.debug.message(classMethod + "process: attrMap = " + attrMap);
}
respInfo.setAttributeMap(attrMap);
// return error code for local user login
if (StringUtils.isEmpty(userName)) {
// map the user to the existing session.
if (session != null) {
try {
sessionProvider.invalidateSession(session, request, response);
} catch (SessionException se) {
SAML2Utils.debug.error("An error occurred while trying to invalidate session", se);
}
}
throw new SAML2Exception(SAML2Utils.bundle.getString("noUserMapping"));
}
boolean writeFedInfo = isNewAccountLink && shouldPersistNameID;
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "userName : " + userName);
SAML2Utils.debug.message(classMethod + "writeFedInfo : " + writeFedInfo);
}
AuthnRequest authnRequest = null;
if (smap != null) {
authnRequest = (AuthnRequest) smap.get(SAML2Constants.AUTHN_REQUEST);
}
if (inRespToResp != null && inRespToResp.length() != 0) {
SPCache.requestHash.remove(inRespToResp);
}
Map sessionInfoMap = new HashMap();
sessionInfoMap.put(SessionProvider.REALM, realm);
sessionInfoMap.put(SessionProvider.PRINCIPAL_NAME, userName);
// set client info. always use client IP address to prevent
// reverse host lookup
String clientAddr = ClientUtils.getClientIPAddress(request);
sessionInfoMap.put(SessionProvider.HOST, clientAddr);
sessionInfoMap.put(SessionProvider.HOST_NAME, clientAddr);
sessionInfoMap.put(SessionProvider.AUTH_LEVEL, String.valueOf(authLevel));
request.setAttribute(SessionProvider.ATTR_MAP, attrMap);
try {
session = sessionProvider.createSession(sessionInfoMap, request, response, null);
} catch (SessionException se) {
// invoke SPAdapter for failure
int failureCode = SAML2ServiceProviderAdapter.SSO_FAILED_SESSION_GENERATION;
int sessCode = se.getErrCode();
if (sessCode == SessionException.AUTH_USER_INACTIVE) {
failureCode = SAML2ServiceProviderAdapter.SSO_FAILED_AUTH_USER_INACTIVE;
} else if (sessCode == SessionException.AUTH_USER_LOCKED) {
failureCode = SAML2ServiceProviderAdapter.SSO_FAILED_AUTH_USER_LOCKED;
} else if (sessCode == SessionException.AUTH_ACCOUNT_EXPIRED) {
failureCode = SAML2ServiceProviderAdapter.SSO_FAILED_AUTH_ACCOUNT_EXPIRED;
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPACSUtils.processResponse : error code=" + sessCode, se);
}
SAML2Exception se2 = new SAML2Exception(se);
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, failureCode, se2);
throw se2;
}
// set metaAlias
String[] values = { metaAlias };
try {
setAttrMapInSession(sessionProvider, attrMap, session);
setDiscoBootstrapCredsInSSOToken(sessionProvider, authnAssertion, session);
sessionProvider.setProperty(session, SAML2Constants.SP_METAALIAS, values);
} catch (SessionException se) {
// invoke SPAdapter for failure
SAML2Exception se2 = new SAML2Exception(se);
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_SESSION_ERROR, se2);
throw se2;
}
NameIDInfo info = null;
String affiID = nameId.getSPNameQualifier();
boolean isDualRole = SAML2Utils.isDualRole(hostEntityId, realm);
AffiliationDescriptorType affiDesc = null;
if (affiID != null && !affiID.isEmpty()) {
affiDesc = metaManager.getAffiliationDescriptor(realm, affiID);
}
if (affiDesc != null) {
if (!affiDesc.getAffiliateMember().contains(hostEntityId)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("spNotAffiliationMember"));
}
if (isDualRole) {
info = new NameIDInfo(affiID, remoteHostId, nameId, SAML2Constants.DUAL_ROLE, true);
} else {
info = new NameIDInfo(affiID, remoteHostId, nameId, SAML2Constants.SP_ROLE, true);
}
} else {
if (isDualRole) {
info = new NameIDInfo(hostEntityId, remoteHostId, nameId, SAML2Constants.DUAL_ROLE, false);
} else {
info = new NameIDInfo(hostEntityId, remoteHostId, nameId, SAML2Constants.SP_ROLE, false);
}
}
Map props = new HashMap();
String nameIDValueString = info.getNameIDValue();
props.put(LogUtil.NAME_ID, info.getNameIDValue());
try {
userName = sessionProvider.getPrincipalName(session);
} catch (SessionException se) {
// invoke SPAdapter for failure
SAML2Exception se2 = new SAML2Exception(se);
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_SESSION_ERROR, se2);
throw se2;
}
String[] data1 = { userName, nameIDValueString };
LogUtil.access(Level.INFO, LogUtil.SUCCESS_FED_SSO, data1, session, props);
// write fed info into data store
if (writeFedInfo) {
try {
AccountUtils.setAccountFederation(info, userName);
} catch (SAML2Exception se) {
// invoke SPAdapter for failure
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.FEDERATION_FAILED_WRITING_ACCOUNT_INFO, se);
throw se;
}
String[] data = { userName, "" };
if (LogUtil.isAccessLoggable(Level.FINE)) {
data[1] = info.toValueString();
}
LogUtil.access(Level.INFO, LogUtil.FED_INFO_WRITTEN, data, session, props);
}
String requestID = respInfo.getResponse().getInResponseTo();
// save info in memory for logout
saveInfoInMemory(sessionProvider, session, sessionIndex, metaAlias, info, IDPProxyUtil.isIDPProxyEnabled(requestID), isTransient);
// invoke SP Adapter
SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(hostEntityId, realm);
if (spAdapter != null) {
boolean redirected = spAdapter.postSingleSignOnSuccess(hostEntityId, realm, request, response, out, session, authnRequest, respInfo.getResponse(), respInfo.getProfileBinding(), writeFedInfo);
String[] value = null;
if (redirected) {
value = new String[] { "true" };
} else {
value = new String[] { "false" };
}
try {
sessionProvider.setProperty(session, SAML2Constants.RESPONSE_REDIRECTED, value);
} catch (SessionException ex) {
SAML2Utils.debug.warning("SPSingleLogout.processResp", ex);
} catch (UnsupportedOperationException ex) {
SAML2Utils.debug.warning("SPSingleLogout.processResp", ex);
}
}
String assertionID = authnAssertion.getID();
if (respInfo.getProfileBinding().equals(SAML2Constants.HTTP_POST)) {
SPCache.assertionByIDCache.put(assertionID, SAML2Constants.ONETIME);
try {
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(assertionID, SAML2Constants.ONETIME, ((Long) smap.get(SAML2Constants.NOTONORAFTER)).longValue() / 1000);
}
} catch (SAML2TokenRepositoryException se) {
SAML2Utils.debug.error(classMethod + "There was a problem saving the assertionID to the SAML2 Token Repository for assertionID:" + assertionID, se);
}
}
respInfo.setAssertion(authnAssertion);
return session;
}
use of org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException in project OpenAM by OpenRock.
the class SPSSOFederate method initiateECPRequest.
/**
* Parses the request parameters and builds ECP Request to sent to the IDP.
*
* @param request the HttpServletRequest.
* @param response the HttpServletResponse.
*
* @throws SAML2Exception if error creating AuthnRequest.
* @throws IOException if error sending AuthnRequest to ECP.
*/
public static void initiateECPRequest(HttpServletRequest request, HttpServletResponse response) throws SAML2Exception, IOException {
if (!isFromECP(request)) {
SAML2Utils.debug.error("SPSSOFederate.initiateECPRequest: " + "invalid HTTP request from ECP.");
SAMLUtils.sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, "invalidHttpRequestFromECP", SAML2Utils.bundle.getString("invalidHttpRequestFromECP"));
return;
}
String metaAlias = request.getParameter("metaAlias");
Map paramsMap = SAML2Utils.getParamsMap(request);
// get the sp entity ID from the metaAlias
String spEntityID = sm.getEntityByMetaAlias(metaAlias);
String realm = getRealm(SAML2MetaUtils.getRealmByMetaAlias(metaAlias));
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPSSOFederate.initiateECPRequest: " + "spEntityID is " + spEntityID + ", realm is " + realm);
}
try {
// Retreive MetaData
if (sm == null) {
throw new SAML2Exception(SAML2Utils.bundle.getString("errorMetaManager"));
}
SPSSOConfigElement spEntityCfg = sm.getSPSSOConfig(realm, spEntityID);
Map spConfigAttrsMap = null;
if (spEntityCfg != null) {
spConfigAttrsMap = SAML2MetaUtils.getAttributes(spEntityCfg);
}
// get SPSSODescriptor
SPSSODescriptorElement spsso = sm.getSPSSODescriptor(realm, spEntityID);
if (spsso == null) {
String[] data = { spEntityID };
LogUtil.error(Level.INFO, LogUtil.SP_METADATA_ERROR, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
String[] data = { spEntityID, realm };
LogUtil.access(Level.INFO, LogUtil.RECEIVED_HTTP_REQUEST_ECP, data, null);
List extensionsList = getExtensionsList(spEntityID, realm);
// create AuthnRequest
AuthnRequest authnRequest = createAuthnRequest(realm, spEntityID, paramsMap, spConfigAttrsMap, extensionsList, spsso, null, null, true);
// invoke SP Adapter class if registered
SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(spEntityID, realm);
if (spAdapter != null) {
spAdapter.preSingleSignOnRequest(spEntityID, realm, null, request, response, authnRequest);
}
String alias = SAML2Utils.getSigningCertAlias(realm, spEntityID, SAML2Constants.SP_ROLE);
PrivateKey signingKey = KeyUtil.getKeyProviderInstance().getPrivateKey(alias);
if (signingKey != null) {
authnRequest.sign(signingKey, null);
} else {
SAML2Utils.debug.error("SPSSOFederate.initiateECPRequest: " + "Unable to find signing key.");
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
ECPFactory ecpFactory = ECPFactory.getInstance();
// Default URL if relayState not present? in providerConfig?
// TODO get Default URL from metadata
String relayState = getParameter(paramsMap, SAML2Constants.RELAY_STATE);
String ecpRelayStateXmlStr = "";
if (relayState != null && relayState.length() > 0) {
String relayStateID = getRelayStateID(relayState, authnRequest.getID());
ECPRelayState ecpRelayState = ecpFactory.createECPRelayState();
ecpRelayState.setValue(relayStateID);
ecpRelayState.setMustUnderstand(Boolean.TRUE);
ecpRelayState.setActor(SAML2Constants.SOAP_ACTOR_NEXT);
ecpRelayStateXmlStr = ecpRelayState.toXMLString(true, true);
}
ECPRequest ecpRequest = ecpFactory.createECPRequest();
ecpRequest.setIssuer(createIssuer(spEntityID));
ecpRequest.setMustUnderstand(Boolean.TRUE);
ecpRequest.setActor(SAML2Constants.SOAP_ACTOR_NEXT);
ecpRequest.setIsPassive(authnRequest.isPassive());
SAML2IDPFinder ecpIDPFinder = SAML2Utils.getECPIDPFinder(realm, spEntityID);
if (ecpIDPFinder != null) {
List idps = ecpIDPFinder.getPreferredIDP(authnRequest, spEntityID, realm, request, response);
if ((idps != null) && (!idps.isEmpty())) {
SAML2MetaManager saml2MetaManager = SAML2Utils.getSAML2MetaManager();
List idpEntries = null;
for (Iterator iter = idps.iterator(); iter.hasNext(); ) {
String idpEntityID = (String) iter.next();
IDPSSODescriptorElement idpDesc = saml2MetaManager.getIDPSSODescriptor(realm, idpEntityID);
if (idpDesc != null) {
IDPEntry idpEntry = ProtocolFactory.getInstance().createIDPEntry();
idpEntry.setProviderID(idpEntityID);
String description = SAML2Utils.getAttributeValueFromSSOConfig(realm, idpEntityID, SAML2Constants.IDP_ROLE, SAML2Constants.ENTITY_DESCRIPTION);
idpEntry.setName(description);
List ssoServiceList = idpDesc.getSingleSignOnService();
String ssoURL = getSSOURL(ssoServiceList, SAML2Constants.SOAP);
idpEntry.setLoc(ssoURL);
if (idpEntries == null) {
idpEntries = new ArrayList();
}
idpEntries.add(idpEntry);
}
}
if (idpEntries != null) {
IDPList idpList = ProtocolFactory.getInstance().createIDPList();
idpList.setIDPEntries(idpEntries);
ecpRequest.setIDPList(idpList);
Map attrs = SAML2MetaUtils.getAttributes(spEntityCfg);
List values = (List) attrs.get(SAML2Constants.ECP_REQUEST_IDP_LIST_GET_COMPLETE);
if ((values != null) && (!values.isEmpty())) {
GetComplete getComplete = ProtocolFactory.getInstance().createGetComplete();
getComplete.setValue((String) values.get(0));
idpList.setGetComplete(getComplete);
}
}
}
}
String paosRequestXmlStr = "";
try {
PAOSRequest paosRequest = new PAOSRequest(authnRequest.getAssertionConsumerServiceURL(), SAML2Constants.PAOS_ECP_SERVICE, null, Boolean.TRUE, SAML2Constants.SOAP_ACTOR_NEXT);
paosRequestXmlStr = paosRequest.toXMLString(true, true);
} catch (PAOSException paosex) {
SAML2Utils.debug.error("SPSSOFederate.initiateECPRequest:", paosex);
throw new SAML2Exception(paosex.getMessage());
}
String header = paosRequestXmlStr + ecpRequest.toXMLString(true, true) + ecpRelayStateXmlStr;
String body = authnRequest.toXMLString(true, true);
try {
SOAPMessage reply = SOAPCommunicator.getInstance().createSOAPMessage(header, body, false);
String[] data2 = { spEntityID, realm, "" };
if (LogUtil.isAccessLoggable(Level.FINE)) {
data2[2] = SOAPCommunicator.getInstance().soapMessageToString(reply);
}
LogUtil.access(Level.INFO, LogUtil.SEND_ECP_PAOS_REQUEST, data2, null);
// are generated as part of the save.
if (reply.saveRequired()) {
reply.saveChanges();
}
response.setStatus(HttpServletResponse.SC_OK);
SAML2Utils.putHeaders(reply.getMimeHeaders(), response);
response.setContentType(PAOSConstants.PAOS_MIME_TYPE);
// Write out the message on the response stream
OutputStream os = response.getOutputStream();
reply.writeTo(os);
os.flush();
} catch (SOAPException soapex) {
SAML2Utils.debug.error("SPSSOFederate.initiateECPRequest", soapex);
String[] data3 = { spEntityID, realm };
LogUtil.error(Level.INFO, LogUtil.SEND_ECP_PAOS_REQUEST_FAILED, data3, null);
SAMLUtils.sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "soapError", soapex.getMessage());
return;
}
AuthnRequestInfo reqInfo = new AuthnRequestInfo(request, response, realm, spEntityID, null, authnRequest, relayState, paramsMap);
synchronized (SPCache.requestHash) {
SPCache.requestHash.put(authnRequest.getID(), reqInfo);
}
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
// sessionExpireTime is counted in seconds
long sessionExpireTime = System.currentTimeMillis() / 1000 + SPCache.interval;
String key = authnRequest.getID();
try {
SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(key, new AuthnRequestInfoCopy(reqInfo), sessionExpireTime);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPSSOFederate.initiateECPRequest:" + " SAVE AuthnRequestInfoCopy for requestID " + key);
}
} catch (SAML2TokenRepositoryException e) {
SAML2Utils.debug.error("SPSSOFederate.initiateECPRequest: There was a problem saving the " + "AuthnRequestInfoCopy in the SAML2 Token Repository for requestID " + key, e);
}
}
} catch (SAML2MetaException sme) {
SAML2Utils.debug.error("SPSSOFederate:Error retrieving metadata", sme);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
}
use of org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException in project OpenAM by OpenRock.
the class IDPSingleLogout method destroyAllTokenForUser.
private static void destroyAllTokenForUser(String userToLogout, HttpServletRequest request, HttpServletResponse response) {
Enumeration keys = IDPCache.idpSessionsByIndices.keys();
String idpSessionIndex = null;
IDPSession idpSession = null;
Object idpToken = null;
if (debug.messageEnabled()) {
debug.message("IDPSingleLogout.destroyAllTokenForUser: " + "User to logoutAll : " + userToLogout);
}
while (keys.hasMoreElements()) {
idpSessionIndex = (String) keys.nextElement();
idpSession = IDPCache.idpSessionsByIndices.get(idpSessionIndex);
if (idpSession != null) {
idpToken = idpSession.getSession();
if (idpToken != null) {
try {
String userID = sessionProvider.getPrincipalName(idpToken);
if (userToLogout.equalsIgnoreCase(userID)) {
MultiProtocolUtils.invalidateSession(idpToken, request, response, SingleLogoutManager.SAML2);
IDPCache.idpSessionsByIndices.remove(idpSessionIndex);
IDPCache.authnContextCache.remove(idpSessionIndex);
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setIdpSessionCount((long) IDPCache.idpSessionsByIndices.size());
}
}
} catch (SessionException e) {
debug.error(SAML2Utils.bundle.getString("invalidSSOToken"), e);
continue;
}
}
} else {
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.destroyAllTokenForUser: Error while deleting token from " + "SAML2 Token Repository for idpSessionIndex:" + idpSessionIndex, se);
}
IDPCache.authnContextCache.remove(idpSessionIndex);
}
}
}
use of org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException in project OpenAM by OpenRock.
the class SPSingleLogout method processLogoutResponse.
/**
* Gets and processes the Single <code>LogoutResponse</code> from IDP,
* 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>.
* @throws SAML2Exception if error processing
* <code>LogoutResponse</code>.
* @throws SessionException if error processing
* <code>LogoutResponse</code>.
*/
public static Map<String, String> processLogoutResponse(HttpServletRequest request, HttpServletResponse response, String samlResponse, String relayState) throws SAML2Exception, SessionException {
String method = "SPSingleLogout: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());
if ((SPCache.isFedlet) && ((metaAlias == null) || (metaAlias.length() == 0))) {
List spMetaAliases = sm.getAllHostedServiceProviderMetaAliases("/");
if ((spMetaAliases != null) && !spMetaAliases.isEmpty()) {
// get first one
metaAlias = (String) spMetaAliases.get(0);
}
}
if ((metaAlias == null) || (metaAlias.length() == 0)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("nullSPEntityID"));
}
String realm = SAML2Utils.getRealm(SAML2MetaUtils.getRealmByMetaAlias(metaAlias));
String spEntityID = sm.getEntityByMetaAlias(metaAlias);
if (!SAML2Utils.isSPProfileBindingSupported(realm, spEntityID, SAML2Constants.SLO_SERVICE, binding)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("unsupportedBinding"));
}
// Validate the RelayState URL.
SAML2Utils.validateRelayStateURL(realm, spEntityID, relayState, SAML2Constants.SP_ROLE);
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("SSingleLogout:processLogoutResponse: logoutRes " + "is null");
}
return null;
}
String idpEntityID = logoutRes.getIssuer().getValue();
Issuer resIssuer = logoutRes.getIssuer();
String inResponseTo = logoutRes.getInResponseTo();
LogoutRequest logoutReq = (LogoutRequest) SPCache.logoutRequestIDHash.remove(inResponseTo);
if (logoutReq == null) {
logoutReq = (LogoutRequest) SAML2Store.getTokenFromStore(inResponseTo);
}
if (logoutReq == null && SAML2FailoverUtils.isSAML2FailoverEnabled()) {
//check the samlFailover cache instead
try {
logoutReq = (LogoutRequest) SAML2FailoverUtils.retrieveSAML2Token(inResponseTo);
} catch (SAML2TokenRepositoryException e) {
throw new SAML2Exception(SAML2Utils.bundle.getString("LogoutRequestIDandInResponseToDoNotMatch"));
}
}
// invoke SPAdapter preSingleLogoutProcess
String userId = null;
if (!SPCache.isFedlet) {
userId = preSingleLogoutProcess(spEntityID, realm, request, response, null, logoutReq, logoutRes, binding);
}
SAML2Utils.verifyResponseIssuer(realm, spEntityID, resIssuer, inResponseTo);
boolean needToVerify = SAML2Utils.getWantLogoutResponseSigned(realm, spEntityID, SAML2Constants.SP_ROLE);
if (debug.messageEnabled()) {
debug.message(method + "metaAlias : " + metaAlias);
debug.message(method + "realm : " + realm);
debug.message(method + "idpEntityID : " + idpEntityID);
debug.message(method + "spEntityID : " + spEntityID);
}
Map<String, String> infoMap = new HashMap<String, String>();
infoMap.put("entityid", spEntityID);
infoMap.put(SAML2Constants.REALM, realm);
if (needToVerify) {
boolean valid = false;
if (rmethod.equals("GET")) {
String queryString = request.getQueryString();
valid = SAML2Utils.verifyQueryString(queryString, realm, SAML2Constants.SP_ROLE, idpEntityID);
} else {
valid = LogoutUtil.verifySLOResponse(logoutRes, realm, idpEntityID, spEntityID, SAML2Constants.SP_ROLE);
}
if (!valid) {
debug.error("SPSingleLogout.processLogoutResponse: " + "Invalid signature in SLO Response.");
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInResponse"));
}
SPSSODescriptorElement spsso = sm.getSPSSODescriptor(realm, spEntityID);
String loc = getSLOResponseLocationOrLocation(spsso, binding);
if (!SAML2Utils.verifyDestination(logoutRes.getDestination(), loc)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidDestination"));
}
}
if (inResponseTo == null || inResponseTo.length() == 0) {
if (debug.messageEnabled()) {
debug.message("LogoutResponse inResponseTo is null");
}
throw new SAML2Exception(SAML2Utils.bundle.getString("nullInResponseToFromSamlResponse"));
}
if (logoutReq != null) {
if (debug.messageEnabled()) {
debug.message("LogoutResponse inResponseTo matches " + "LogoutRequest ID.");
}
} else {
if (debug.messageEnabled()) {
debug.message("LogoutResponse inResponseTo does not match " + "LogoutRequest ID.");
}
throw new SAML2Exception(SAML2Utils.bundle.getString("LogoutRequestIDandInResponseToDoNotMatch"));
}
infoMap.put("inResponseTo", inResponseTo);
infoMap.put(SAML2Constants.RELAY_STATE, relayState);
// destroy session
try {
Object session = sessionProvider.getSession(request);
if ((session != null) && sessionProvider.isValid(session)) {
sessionProvider.invalidateSession(session, request, response);
}
} catch (SessionException se) {
debug.message("SPSingleLogout.processLogoutResponse() : Unable to invalidate session: " + se.getMessage());
}
if (!SPCache.isFedlet) {
if (isSuccess(logoutRes)) {
// invoke SPAdapter postSingleLogoutSucces
postSingleLogoutSuccess(spEntityID, realm, request, response, userId, logoutReq, logoutRes, binding);
} else {
throw new SAML2Exception(SAML2Utils.BUNDLE_NAME, "sloFailed", null);
}
} else {
// obtain fedlet adapter
FedletAdapter fedletAdapter = SAML2Utils.getFedletAdapterClass(spEntityID, realm);
if (fedletAdapter != null) {
if (isSuccess(logoutRes)) {
fedletAdapter.onFedletSLOSuccess(request, response, logoutReq, logoutRes, spEntityID, idpEntityID, binding);
} else {
fedletAdapter.onFedletSLOFailure(request, response, logoutReq, logoutRes, spEntityID, idpEntityID, binding);
throw new SAML2Exception(SAML2Utils.BUNDLE_NAME, "sloFailed", null);
}
}
}
return infoMap;
}
Aggregations