use of com.sun.identity.saml2.profile.IDPSession in project OpenAM by OpenRock.
the class DoManageNameID method checkMNIResponse.
private static boolean checkMNIResponse(ManageNameIDResponse mniResponse, String realm, String hostEntityID, String hostRole, StringBuffer mniUserId) throws SAML2Exception, SessionException {
boolean success = false;
String remoteEntityID = mniResponse.getIssuer().getValue();
String requestID = mniResponse.getInResponseTo();
ManageNameIDRequestInfo reqInfo = getMNIRequestInfo(requestID, hostRole);
if (reqInfo == null) {
logError("invalidInResponseToInResponse", LogUtil.INVALID_MNI_RESPONSE, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidInResponseToInResponse"));
}
String retCode = mniResponse.getStatus().getStatusCode().getValue();
if (retCode.equalsIgnoreCase(SAML2Constants.SUCCESS)) {
Object session = reqInfo.getSession();
if (session == null) {
logError("nullSSOToken", LogUtil.INVALID_SSOTOKEN, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("nullSSOToken"));
}
String userID = sessionProvider.getPrincipalName(session);
mniUserId.append(userID);
ManageNameIDRequest origMniReq = reqInfo.getManageNameIDRequest();
NameID oldNameID = origMniReq.getNameID();
List spFedSessions = null;
NameIDInfo oldNameIDInfo = getNameIDInfo(userID, hostEntityID, remoteEntityID, hostRole, realm, oldNameID.getSPNameQualifier(), true);
if (oldNameIDInfo == null) {
debug.error("DoManageNameID.checkMNIResponse: NameIDInfo " + "not found.");
return false;
}
// Terminate
if (hostRole.equalsIgnoreCase(SAML2Constants.SP_ROLE)) {
String infoKeyStr = oldNameIDInfo.getNameIDInfoKey().toValueString();
spFedSessions = (List) SPCache.fedSessionListsByNameIDInfoKey.remove(infoKeyStr);
removeInfoKeyFromSession(session, infoKeyStr);
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
}
} else {
removeIDPFedSession(remoteEntityID, oldNameID.getValue());
}
if (!AccountUtils.removeAccountFederation(oldNameIDInfo, userID)) {
// log termination failure
logError("unableToTerminate", LogUtil.UNABLE_TO_TERMINATE, userID);
return false;
}
if (origMniReq.getTerminate()) {
// log termination success
logAccess("requestSuccess", LogUtil.SUCCESS_FED_TERMINATION, userID);
return true;
}
// newID case
String newIDValue = origMniReq.getNewID().getValue();
boolean isAffiliation = oldNameIDInfo.isAffiliation();
String spNameQualifier = oldNameID.getSPNameQualifier();
if (hostRole.equalsIgnoreCase(SAML2Constants.SP_ROLE)) {
NameID newNameID = AssertionFactory.getInstance().createNameID();
newNameID.setValue(oldNameID.getValue());
newNameID.setFormat(oldNameID.getFormat());
newNameID.setSPProvidedID(newIDValue);
newNameID.setSPNameQualifier(spNameQualifier);
newNameID.setNameQualifier(oldNameID.getNameQualifier());
NameIDInfo newNameIDInfo = new NameIDInfo((isAffiliation ? spNameQualifier : hostEntityID), remoteEntityID, newNameID, hostRole, isAffiliation);
String newInfoKeyStr = newNameIDInfo.getNameIDInfoKey().toValueString();
if (spFedSessions != null) {
SPCache.fedSessionListsByNameIDInfoKey.put(newInfoKeyStr, spFedSessions);
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
}
}
AccountUtils.setAccountFederation(newNameIDInfo, userID);
try {
String infoKeyAttribute = AccountUtils.getNameIDInfoKeyAttribute();
String[] fromToken = sessionProvider.getProperty(session, infoKeyAttribute);
if ((fromToken == null) || (fromToken.length == 0) || (fromToken[0] == null) || (fromToken[0].length() == 0)) {
String[] values = { newInfoKeyStr };
sessionProvider.setProperty(session, infoKeyAttribute, values);
} else {
if (fromToken[0].indexOf(newInfoKeyStr) == -1) {
String[] values = { fromToken[0] + SAML2Constants.SECOND_DELIM + newInfoKeyStr };
sessionProvider.setProperty(session, infoKeyAttribute, values);
}
}
} catch (Exception e) {
debug.message("DoManageNameID.checkMNIResponse:", e);
}
} else if (hostRole.equalsIgnoreCase(SAML2Constants.IDP_ROLE)) {
NameID newNameID = AssertionFactory.getInstance().createNameID();
newNameID.setValue(newIDValue);
newNameID.setFormat(oldNameID.getFormat());
newNameID.setSPProvidedID(oldNameID.getSPProvidedID());
newNameID.setSPNameQualifier(spNameQualifier);
newNameID.setNameQualifier(hostEntityID);
NameIDInfo newNameIDInfo = new NameIDInfo(hostEntityID, (isAffiliation ? spNameQualifier : remoteEntityID), newNameID, SAML2Constants.IDP_ROLE, isAffiliation);
AccountUtils.setAccountFederation(newNameIDInfo, userID);
NameIDandSPpair pair = new NameIDandSPpair(newNameID, remoteEntityID);
IDPSession idpSession = (IDPSession) IDPCache.idpSessionsBySessionID.get(sessionProvider.getSessionID(session));
if (idpSession != null) {
synchronized (IDPCache.idpSessionsByIndices) {
List list = (List) idpSession.getNameIDandSPpairs();
list.add(pair);
}
}
}
// log manage name id success
logAccess("newNameIDSuccess", LogUtil.SUCCESS_NEW_NAMEID, userID);
success = true;
} else {
logError("mniFailed", LogUtil.INVALID_MNI_RESPONSE, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("mniFailed"));
}
return success;
}
use of com.sun.identity.saml2.profile.IDPSession in project OpenAM by OpenRock.
the class IDPProxyUtil method initiateSPLogoutRequest.
/**
* Initiates the Single logout request by the IDP Proxy to the
* authenticating identity provider.
* @param request HttpServletRequest
* @param response HttpServletResponse
* @param out The print writer for writing out presentation.
* @param partner Authenticating identity provider
* @param spMetaAlias IDP proxy's meta alias acting as SP
* @param realm Realm
*/
public static void initiateSPLogoutRequest(HttpServletRequest request, HttpServletResponse response, PrintWriter out, String partner, String spMetaAlias, String realm, LogoutRequest logoutReq, SOAPMessage msg, IDPSession idpSession, String binding, String relayState) {
Object ssoToken = idpSession.getSession();
try {
if (ssoToken == null) {
SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "nullSSOToken", SAML2Utils.bundle.getString("nullSSOToken"));
return;
}
String[] values = SessionManager.getProvider().getProperty(ssoToken, SAML2Constants.SP_METAALIAS);
String metaAlias = null;
if (values != null && values.length > 0) {
metaAlias = values[0];
}
if (metaAlias == null) {
metaAlias = spMetaAlias;
}
HashMap paramsMap = new HashMap();
paramsMap.put("spMetaAlias", metaAlias);
paramsMap.put("idpEntityID", partner);
paramsMap.put(SAML2Constants.ROLE, SAML2Constants.SP_ROLE);
paramsMap.put(SAML2Constants.BINDING, binding);
String dest = getLocation(realm, partner, binding);
if (dest != null && !dest.equals("")) {
paramsMap.put("Destination", dest);
} else {
throw new SAML2Exception(SAML2Utils.bundle.getString("sloResponseServiceLocationNotfound"));
}
paramsMap.put("Consent", request.getParameter("Consent"));
paramsMap.put("Extension", request.getParameter("Extension"));
if (relayState != null) {
paramsMap.put(SAML2Constants.RELAY_STATE, relayState);
}
idpSession.removeSessionPartner(partner);
SPSingleLogout.initiateLogoutRequest(request, response, out, binding, paramsMap, logoutReq, msg, ssoToken, null);
} catch (SAML2Exception sse) {
SAML2Utils.debug.error("Error sending Logout Request ", sse);
try {
SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "LogoutRequestCreationError", SAML2Utils.bundle.getString("LogoutRequestCreationError"));
} catch (Exception se) {
SAML2Utils.debug.error("IDPProxyUtil." + "initiateSPLogoutRequest: ", se);
}
return;
} catch (Exception e) {
SAML2Utils.debug.error("Error initializing Request ", e);
try {
SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "LogoutRequestCreationError", SAML2Utils.bundle.getString("LogoutRequestCreationError"));
} catch (Exception mme) {
SAML2Utils.debug.error("IDPProxyUtil." + "initiateSPLogoutRequest: ", mme);
}
return;
}
}
use of com.sun.identity.saml2.profile.IDPSession in project OpenAM by OpenRock.
the class IDPProxyUtil method getSessionPartners.
public static Map getSessionPartners(SOAPMessage message) {
try {
Map sessMap = new HashMap();
Element reqElem = SOAPCommunicator.getInstance().getSamlpElement(message, "LogoutRequest");
LogoutRequest logoutReq = ProtocolFactory.getInstance().createLogoutRequest(reqElem);
List siList = logoutReq.getSessionIndex();
int numSI = 0;
if (siList != null) {
numSI = siList.size();
if (debug.messageEnabled()) {
debug.message("Number of session indices in the logout request is " + numSI);
}
String sessionIndex = (String) siList.get(0);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("getSessionPartners: " + "SessionIndex= " + sessionIndex);
}
IDPSession idpSession = (IDPSession) IDPCache.idpSessionsByIndices.get(sessionIndex);
if (idpSession == null) {
// session is in another server
return sessMap;
}
sessMap.put(SAML2Constants.SESSION_INDEX, sessionIndex);
sessMap.put(SAML2Constants.IDP_SESSION, idpSession);
Object session = idpSession.getSession();
String tokenId = sessionProvider.getSessionID(session);
IDPSession newIdpSession = (IDPSession) IDPCache.idpSessionsBySessionID.get(tokenId);
List partners = null;
if (newIdpSession != null) {
partners = newIdpSession.getSessionPartners();
}
if (SAML2Utils.debug.messageEnabled()) {
if (partners != null && !partners.isEmpty()) {
Iterator iter = partners.iterator();
while (iter.hasNext()) {
SAML2SessionPartner partner = (SAML2SessionPartner) iter.next();
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SESSION PARTNER's Provider ID: " + partner.getPartner());
}
}
}
}
sessMap.put(SAML2Constants.PARTNERS, partners);
return sessMap;
} else {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("getSessionPartners: Number of " + "session indices in the logout request is null");
}
return null;
}
} catch (SAML2Exception se) {
SAML2Utils.debug.error("getSessionPartners: ", se);
return null;
}
}
use of com.sun.identity.saml2.profile.IDPSession in project OpenAM by OpenRock.
the class UtilProxySAMLAuthenticatorLookup method retrieveAuthenticationFromCache.
@Override
public void retrieveAuthenticationFromCache() throws SessionException, ServerFaultException, ClientFaultException {
final String classMethod = "UtilProxySAMLAuthenticatorLookup.retrieveAuthenticationFromCache: ";
// the second visit, the user has already authenticated
// retrieve the cache authn request and relay state
// We need the session to pass it to the IDP Adapter preSendResponse
SessionProvider sessionProvider = SessionManager.getProvider();
try {
data.setSession(sessionProvider.getSession(request));
data.getEventAuditor().setSSOTokenId(data.getSession());
} catch (SessionException se) {
SAML2Utils.debug.error("An error occurred while retrieving the session: " + se.getMessage());
data.setSession(null);
}
// Get the cached Authentication Request and Relay State before
// invoking the IDP Adapter
CacheObject cacheObj;
synchronized (IDPCache.authnRequestCache) {
cacheObj = (CacheObject) IDPCache.authnRequestCache.get(data.getRequestID());
}
if (cacheObj != null) {
data.setAuthnRequest((AuthnRequest) cacheObj.getObject());
}
data.setRelayState((String) IDPCache.relayStateCache.get(data.getRequestID()));
if (!isSessionValid(sessionProvider)) {
return;
}
// Invoke the IDP Adapter after the user has been authenticated
if (preSendResponse(request, response, data)) {
return;
}
synchronized (IDPCache.authnRequestCache) {
cacheObj = (CacheObject) IDPCache.authnRequestCache.remove(data.getRequestID());
}
if (cacheObj != null) {
data.setAuthnRequest((AuthnRequest) cacheObj.getObject());
}
synchronized (IDPCache.idpAuthnContextCache) {
cacheObj = (CacheObject) IDPCache.idpAuthnContextCache.remove(data.getRequestID());
}
if (cacheObj != null) {
data.setMatchingAuthnContext((AuthnContext) cacheObj.getObject());
}
data.setRelayState((String) IDPCache.relayStateCache.remove(data.getRequestID()));
if (data.getAuthnRequest() == null) {
authNotAvailable();
return;
}
SAML2Utils.debug.message("{} RequestID= {}", classMethod, data.getRequestID());
boolean isSessionUpgrade = false;
if (CollectionUtils.isNotEmpty(IDPCache.isSessionUpgradeCache)) {
isSessionUpgrade = IDPCache.isSessionUpgradeCache.contains(data.getRequestID());
}
if (isSessionUpgrade) {
IDPSession oldSess = (IDPSession) IDPCache.oldIDPSessionCache.remove(data.getRequestID());
String sessionIndex = IDPSSOUtil.getSessionIndex(data.getSession());
if (StringUtils.isNotEmpty(sessionIndex)) {
IDPCache.idpSessionsByIndices.put(sessionIndex, oldSess);
final FedMonAgent agent = MonitorManager.getAgent();
if (agent != null && agent.isRunning()) {
final FedMonSAML2Svc saml2Svc = MonitorManager.getSAML2Svc();
if (saml2Svc != null) {
saml2Svc.setIdpSessionCount(IDPCache.idpSessionsByIndices.size());
}
}
}
}
if (data.getSession() != null) {
// call multi-federation protocol to set the protocol
MultiProtocolUtils.addFederationProtocol(data.getSession(), SingleLogoutManager.SAML2);
}
// generate assertion response
data.setSpEntityID(data.getAuthnRequest().getIssuer().getValue());
NameIDPolicy policy = data.getAuthnRequest().getNameIDPolicy();
String nameIDFormat = (policy == null) ? null : policy.getFormat();
try {
IDPSSOUtil.sendResponseToACS(request, response, out, data.getSession(), data.getAuthnRequest(), data.getSpEntityID(), data.getIdpEntityID(), data.getIdpMetaAlias(), data.getRealm(), nameIDFormat, data.getRelayState(), data.getMatchingAuthnContext());
} catch (SAML2Exception se) {
SAML2Utils.debug.error(classMethod + "Unable to do sso or federation.", se);
throw new ServerFaultException(data.getIdpAdapter(), SSO_OR_FEDERATION_ERROR, se.getMessage());
}
}
Aggregations