use of com.sun.identity.saml2.profile.IDPSession in project OpenAM by OpenRock.
the class IDPProxyUtil method getSessionPartners.
public static List getSessionPartners(HttpServletRequest request) {
try {
Object tmpsession = sessionProvider.getSession(request);
String tokenID = sessionProvider.getSessionID(tmpsession);
IDPSession idpSession = null;
if (tokenID != null && !tokenID.equals("")) {
idpSession = (IDPSession) IDPCache.idpSessionsBySessionID.get(tokenID);
}
List partners = null;
if (idpSession != null) {
partners = idpSession.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());
}
}
}
}
return partners;
} catch (SessionException se) {
return null;
}
}
use of com.sun.identity.saml2.profile.IDPSession in project OpenAM by OpenRock.
the class DefaultIDPAccountMapper method getNameID.
@Override
public NameID getNameID(Object session, String hostEntityID, String remoteEntityID, String realm, String nameIDFormat) throws SAML2Exception {
String userID;
try {
SessionProvider sessionProv = SessionManager.getProvider();
userID = sessionProv.getPrincipalName(session);
} catch (SessionException se) {
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
}
String nameIDValue = null;
if (nameIDFormat.equals(SAML2Constants.NAMEID_TRANSIENT_FORMAT)) {
String sessionIndex = IDPSSOUtil.getSessionIndex(session);
if (sessionIndex != null) {
IDPSession idpSession = IDPCache.idpSessionsByIndices.get(sessionIndex);
if (idpSession != null) {
List<NameIDandSPpair> list = idpSession.getNameIDandSPpairs();
if (list != null) {
for (NameIDandSPpair pair : list) {
if (pair.getSPEntityID().equals(remoteEntityID)) {
nameIDValue = pair.getNameID().getValue();
break;
}
}
}
}
}
if (nameIDValue == null) {
nameIDValue = getNameIDValueFromUserProfile(realm, hostEntityID, userID, nameIDFormat);
if (nameIDValue == null) {
nameIDValue = SAML2Utils.createNameIdentifier();
}
}
} else {
nameIDValue = getNameIDValueFromUserProfile(realm, hostEntityID, userID, nameIDFormat);
if (nameIDValue == null) {
if (nameIDFormat.equals(SAML2Constants.PERSISTENT)) {
nameIDValue = SAML2Utils.createNameIdentifier();
} else {
throw new SAML2Exception(bundle.getString("unableToGenerateNameIDValue"));
}
}
}
NameID nameID = AssertionFactory.getInstance().createNameID();
nameID.setValue(nameIDValue);
nameID.setFormat(nameIDFormat);
nameID.setNameQualifier(hostEntityID);
nameID.setSPNameQualifier(remoteEntityID);
nameID.setSPProvidedID(null);
return nameID;
}
use of com.sun.identity.saml2.profile.IDPSession in project OpenAM by OpenRock.
the class UtilProxySAMLAuthenticator method authenticate.
@Override
public void authenticate() throws FederatedSSOException, IOException {
final String classMethod = "UtilProxySAMLAuthenticator.authenticate: ";
SPSSODescriptorElement spSSODescriptor = null;
String preferredIDP;
// There is no reqID, this is the first time that we pass here.
String binding = SAML2Constants.HTTP_REDIRECT;
if (request.getMethod().equals("POST")) {
binding = SAML2Constants.HTTP_POST;
}
data.setAuthnRequest(getAuthnRequest(request, isFromECP, binding));
if (data.getAuthnRequest() == null) {
throw new ClientFaultException(data.getIdpAdapter(), INVALID_SAML_REQUEST);
}
data.getEventAuditor().setRequestId(data.getRequestID());
data.setSpEntityID(data.getAuthnRequest().getIssuer().getValue());
try {
logAccess(isFromECP ? LogUtil.RECEIVED_AUTHN_REQUEST_ECP : LogUtil.RECEIVED_AUTHN_REQUEST, Level.INFO, data.getSpEntityID(), data.getIdpMetaAlias(), data.getAuthnRequest().toXMLString());
} catch (SAML2Exception saml2ex) {
SAML2Utils.debug.error(classMethod, saml2ex);
throw new ClientFaultException(data.getIdpAdapter(), INVALID_SAML_REQUEST, saml2ex.getMessage());
}
if (!SAML2Utils.isSourceSiteValid(data.getAuthnRequest().getIssuer(), data.getRealm(), data.getIdpEntityID())) {
SAML2Utils.debug.warning("{} Issuer in Request is not valid.", classMethod);
throw new ClientFaultException(data.getIdpAdapter(), INVALID_SAML_REQUEST);
}
// verify the signature of the query string if applicable
IDPSSODescriptorElement idpSSODescriptor;
try {
idpSSODescriptor = IDPSSOUtil.metaManager.getIDPSSODescriptor(data.getRealm(), data.getIdpEntityID());
} catch (SAML2MetaException sme) {
SAML2Utils.debug.error(classMethod + "Unable to get IDP SSO Descriptor from meta.");
throw new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
}
try {
spSSODescriptor = IDPSSOUtil.metaManager.getSPSSODescriptor(data.getRealm(), data.getSpEntityID());
} catch (SAML2MetaException sme) {
SAML2Utils.debug.error(classMethod + "Unable to get SP SSO Descriptor from meta.");
SAML2Utils.debug.error(classMethod, sme);
}
if (isFromECP || idpSSODescriptor.isWantAuthnRequestsSigned() || (spSSODescriptor != null && spSSODescriptor.isAuthnRequestsSigned())) {
// need to verify the query string containing authnRequest
if (StringUtils.isBlank(data.getSpEntityID())) {
throw new ClientFaultException(data.getIdpAdapter(), INVALID_SAML_REQUEST);
}
if (spSSODescriptor == null) {
SAML2Utils.debug.error(classMethod + "Unable to get SP SSO Descriptor from meta.");
throw new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
}
Set<X509Certificate> certificates = KeyUtil.getVerificationCerts(spSSODescriptor, data.getSpEntityID(), SAML2Constants.SP_ROLE);
try {
boolean isSignatureOK;
if (isFromECP) {
isSignatureOK = data.getAuthnRequest().isSignatureValid(certificates);
} else {
if ("POST".equals(request.getMethod())) {
isSignatureOK = data.getAuthnRequest().isSignatureValid(certificates);
} else {
isSignatureOK = QuerySignatureUtil.verify(request.getQueryString(), certificates);
}
}
if (!isSignatureOK) {
SAML2Utils.debug.error(classMethod + "authn request verification failed.");
throw new ClientFaultException(data.getIdpAdapter(), "invalidSignInRequest");
}
// In ECP profile, sp doesn't know idp.
if (!isFromECP) {
// verify Destination
List ssoServiceList = idpSSODescriptor.getSingleSignOnService();
String ssoURL = SPSSOFederate.getSSOURL(ssoServiceList, binding);
if (!SAML2Utils.verifyDestination(data.getAuthnRequest().getDestination(), ssoURL)) {
SAML2Utils.debug.error(classMethod + "authn request destination verification failed.");
throw new ClientFaultException(data.getIdpAdapter(), "invalidDestination");
}
}
} catch (SAML2Exception se) {
SAML2Utils.debug.error(classMethod + "authn request verification failed.", se);
throw new ClientFaultException(data.getIdpAdapter(), "invalidSignInRequest");
}
SAML2Utils.debug.message("{} authn request signature verification is successful.", classMethod);
}
SAML2Utils.debug.message("{} request id= {}", classMethod, data.getRequestID());
if (data.getRequestID() == null) {
SAML2Utils.debug.error(classMethod + "Request id is null");
throw new ClientFaultException(data.getIdpAdapter(), "InvalidSAMLRequestID");
}
if (isFromECP) {
try {
IDPECPSessionMapper idpECPSessonMapper = IDPSSOUtil.getIDPECPSessionMapper(data.getRealm(), data.getIdpEntityID());
data.setSession(idpECPSessonMapper.getSession(request, response));
} catch (SAML2Exception se) {
SAML2Utils.debug.message("Unable to retrieve user session.", classMethod);
}
} else {
// get the user sso session from the request
try {
data.setSession(SessionManager.getProvider().getSession(request));
} catch (SessionException se) {
SAML2Utils.debug.message("{} Unable to retrieve user session.", classMethod);
}
}
if (null != data.getSession()) {
data.getEventAuditor().setAuthTokenId(data.getSession());
}
// will not trigger this adapter call
if (preSingleSignOn(request, response, data)) {
return;
}
// End of adapter invocation
IDPAuthnContextMapper idpAuthnContextMapper = null;
try {
idpAuthnContextMapper = IDPSSOUtil.getIDPAuthnContextMapper(data.getRealm(), data.getIdpEntityID());
} catch (SAML2Exception sme) {
SAML2Utils.debug.error(classMethod, sme);
}
if (idpAuthnContextMapper == null) {
SAML2Utils.debug.error(classMethod + "Unable to get IDPAuthnContextMapper from meta.");
throw new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
}
IDPAuthnContextInfo idpAuthnContextInfo = null;
try {
idpAuthnContextInfo = idpAuthnContextMapper.getIDPAuthnContextInfo(data.getAuthnRequest(), data.getIdpEntityID(), data.getRealm());
} catch (SAML2Exception sme) {
SAML2Utils.debug.error(classMethod, sme);
}
if (idpAuthnContextInfo == null) {
SAML2Utils.debug.message("{} Unable to find valid AuthnContext. Sending error Response.", classMethod);
try {
Response res = SAML2Utils.getErrorResponse(data.getAuthnRequest(), SAML2Constants.REQUESTER, SAML2Constants.NO_AUTHN_CONTEXT, null, data.getIdpEntityID());
StringBuffer returnedBinding = new StringBuffer();
String acsURL = IDPSSOUtil.getACSurl(data.getSpEntityID(), data.getRealm(), data.getAuthnRequest(), request, returnedBinding);
String acsBinding = returnedBinding.toString();
IDPSSOUtil.sendResponse(request, response, out, acsBinding, data.getSpEntityID(), data.getIdpEntityID(), data.getIdpMetaAlias(), data.getRealm(), data.getRelayState(), acsURL, res, data.getSession());
} catch (SAML2Exception sme) {
SAML2Utils.debug.error(classMethod, sme);
throw new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
}
return;
}
// get the relay state query parameter from the request
data.setRelayState(request.getParameter(SAML2Constants.RELAY_STATE));
data.setMatchingAuthnContext(idpAuthnContextInfo.getAuthnContext());
if (data.getSession() == null) {
// the user has not logged in yet, redirect to auth
redirectToAuth(spSSODescriptor, binding, idpAuthnContextInfo, data);
} else {
SAML2Utils.debug.message("{} There is an existing session", classMethod);
// Let's verify that the realm is the same for the user and the IdP
boolean isValidSessionInRealm = IDPSSOUtil.isValidSessionInRealm(data.getRealm(), data.getSession());
String sessionIndex = IDPSSOUtil.getSessionIndex(data.getSession());
boolean sessionUpgrade = false;
if (isValidSessionInRealm) {
sessionUpgrade = isSessionUpgrade(idpAuthnContextInfo, data.getSession());
SAML2Utils.debug.message("{} IDP Session Upgrade is : {}", classMethod, sessionUpgrade);
}
// Holder for any exception encountered while redirecting for authentication:
FederatedSSOException redirectException = null;
if (sessionUpgrade || !isValidSessionInRealm || ((Boolean.TRUE.equals(data.getAuthnRequest().isForceAuthn())) && (!Boolean.TRUE.equals(data.getAuthnRequest().isPassive())))) {
// sessionIndex
if (sessionIndex != null && sessionIndex.length() != 0) {
// Save the original IDP Session
IDPSession oldIDPSession = IDPCache.idpSessionsByIndices.get(sessionIndex);
if (oldIDPSession != null) {
IDPCache.oldIDPSessionCache.put(data.getRequestID(), oldIDPSession);
} else {
SAML2Utils.debug.error(classMethod + "The old SAML2 session was not found in the idp session " + "by indices cache");
}
}
// Save the new requestId and AuthnRequest
IDPCache.authnRequestCache.put(data.getRequestID(), new CacheObject(data.getAuthnRequest()));
// Save the new requestId and AuthnContext
IDPCache.idpAuthnContextCache.put(data.getRequestID(), new CacheObject(data.getMatchingAuthnContext()));
// save if the request was an Session Upgrade case.
IDPCache.isSessionUpgradeCache.add(data.getRequestID());
// authenticates
if (StringUtils.isNotBlank(data.getRelayState())) {
IDPCache.relayStateCache.put(data.getRequestID(), data.getRelayState());
}
// Session upgrade could be requested by asking a greater AuthnContext
if (isValidSessionInRealm) {
try {
boolean isProxy = IDPProxyUtil.isIDPProxyEnabled(data.getAuthnRequest(), data.getRealm());
if (isProxy) {
preferredIDP = IDPProxyUtil.getPreferredIDP(data.getAuthnRequest(), data.getIdpEntityID(), data.getRealm(), request, response);
if (preferredIDP != null) {
if ((SPCache.reqParamHash != null) && (!(SPCache.reqParamHash.containsKey(preferredIDP)))) {
// IDP Proxy with configured proxy list
SAML2Utils.debug.message("{} IDP to be proxied {}", classMethod, preferredIDP);
IDPProxyUtil.sendProxyAuthnRequest(data.getAuthnRequest(), preferredIDP, spSSODescriptor, data.getIdpEntityID(), request, response, data.getRealm(), data.getRelayState(), binding);
return;
} else {
// IDP proxy with introduction cookie
Map paramsMap = (Map) SPCache.reqParamHash.get(preferredIDP);
paramsMap.put("authnReq", data.getAuthnRequest());
paramsMap.put("spSSODescriptor", spSSODescriptor);
paramsMap.put("idpEntityID", data.getIdpEntityID());
paramsMap.put("realm", data.getRealm());
paramsMap.put("relayState", data.getRelayState());
paramsMap.put("binding", binding);
SPCache.reqParamHash.put(preferredIDP, paramsMap);
return;
}
}
}
//else continue for the local authentication.
} catch (SAML2Exception re) {
SAML2Utils.debug.message("{} Redirecting for the proxy handling error: {}", classMethod, re.getMessage());
redirectException = new ServerFaultException(data.getIdpAdapter(), "UnableToRedirectToPreferredIDP", re.getMessage());
}
// End of IDP Proxy: Initiate proxying when session upgrade is requested
}
// Invoke the IDP Adapter before redirecting to authn
if (preAuthenticationAdapter(request, response, data)) {
return;
}
//we don't have a session
try {
//and they want to authenticate
if (!Boolean.TRUE.equals(data.getAuthnRequest().isPassive())) {
redirectAuthentication(request, response, idpAuthnContextInfo, data, true);
return;
} else {
try {
//and they want to get into the system with passive auth - response no passive
IDPSSOUtil.sendNoPassiveResponse(request, response, out, data.getIdpMetaAlias(), data.getIdpEntityID(), data.getRealm(), data.getAuthnRequest(), data.getRelayState(), data.getSpEntityID());
} catch (SAML2Exception sme) {
SAML2Utils.debug.error(classMethod, sme);
redirectException = new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
}
}
} catch (IOException | SAML2Exception e) {
SAML2Utils.debug.error(classMethod + "Unable to redirect to authentication.", e);
sessionUpgrade = false;
cleanUpCache(data.getRequestID());
redirectException = new ServerFaultException(data.getIdpAdapter(), "UnableToRedirectToAuth", e.getMessage());
}
}
// generate assertion response
if (!sessionUpgrade && isValidSessionInRealm) {
generateAssertionResponse(data);
}
if (redirectException != null) {
throw redirectException;
}
}
}
use of com.sun.identity.saml2.profile.IDPSession in project OpenAM by OpenRock.
the class SPACSUtils method saveInfoInMemory.
public static void saveInfoInMemory(SessionProvider sessionProvider, Object session, String sessionIndex, String metaAlias, NameIDInfo info, boolean isIDPProxy, boolean isTransient) throws SAML2Exception {
String infoKeyString = (new NameIDInfoKey(info.getNameIDValue(), info.getHostEntityID(), info.getRemoteEntityID())).toValueString();
String infoKeyAttribute = AccountUtils.getNameIDInfoKeyAttribute();
String[] fromToken = null;
try {
fromToken = sessionProvider.getProperty(session, infoKeyAttribute);
if (fromToken == null || fromToken.length == 0 || fromToken[0] == null || fromToken[0].length() == 0) {
String[] values = { infoKeyString };
sessionProvider.setProperty(session, infoKeyAttribute, values);
} else {
if (fromToken[0].indexOf(infoKeyString) == -1) {
String[] values = { fromToken[0] + SAML2Constants.SECOND_DELIM + infoKeyString };
sessionProvider.setProperty(session, infoKeyAttribute, values);
}
}
if (isTransient) {
String nameIDInfoStr = info.toValueString();
String infoAttribute = AccountUtils.getNameIDInfoAttribute();
String[] nameIDInfoStrs = sessionProvider.getProperty(session, infoAttribute);
if (nameIDInfoStrs == null) {
nameIDInfoStrs = new String[1];
nameIDInfoStrs[0] = nameIDInfoStr;
} else {
Set nameIDInfoStrSet = new HashSet();
for (int i = 0; i < nameIDInfoStrs.length; i++) {
nameIDInfoStrSet.add(nameIDInfoStrs[i]);
}
nameIDInfoStrSet.add(nameIDInfoStr);
nameIDInfoStrs = (String[]) nameIDInfoStrSet.toArray(new String[nameIDInfoStrSet.size()]);
}
sessionProvider.setProperty(session, infoAttribute, nameIDInfoStrs);
}
} catch (SessionException sessE) {
throw new SAML2Exception(sessE);
}
String tokenID = sessionProvider.getSessionID(session);
if (!SPCache.isFedlet) {
List fedSessions = (List) SPCache.fedSessionListsByNameIDInfoKey.get(infoKeyString);
if (fedSessions == null) {
synchronized (SPCache.fedSessionListsByNameIDInfoKey) {
fedSessions = (List) SPCache.fedSessionListsByNameIDInfoKey.get(infoKeyString);
if (fedSessions == null) {
fedSessions = new ArrayList();
}
}
synchronized (fedSessions) {
fedSessions.add(new SPFedSession(sessionIndex, tokenID, info, metaAlias));
SPCache.fedSessionListsByNameIDInfoKey.put(infoKeyString, fedSessions);
}
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
}
if (isIDPProxy) {
//IDP Proxy
IDPSession idpSess = (IDPSession) IDPCache.idpSessionsBySessionID.get(tokenID);
if (idpSess == null) {
idpSess = new IDPSession(session);
IDPCache.idpSessionsBySessionID.put(tokenID, idpSess);
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("Add Session Partner: " + info.getRemoteEntityID());
}
idpSess.addSessionPartner(new SAML2SessionPartner(info.getRemoteEntityID(), true));
// end of IDP Proxy
}
} else {
synchronized (fedSessions) {
Iterator iter = fedSessions.iterator();
boolean found = false;
while (iter.hasNext()) {
SPFedSession temp = (SPFedSession) iter.next();
String idpSessionIndex = null;
if (temp != null) {
idpSessionIndex = temp.idpSessionIndex;
}
if ((idpSessionIndex != null) && (idpSessionIndex.equals(sessionIndex))) {
temp.spTokenID = tokenID;
temp.info = info;
found = true;
break;
}
}
if (!found) {
fedSessions.add(new SPFedSession(sessionIndex, tokenID, info, metaAlias));
SPCache.fedSessionListsByNameIDInfoKey.put(infoKeyString, fedSessions);
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
}
}
}
}
SPCache.fedSessionListsByNameIDInfoKey.put(infoKeyString, fedSessions);
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
}
}
try {
sessionProvider.addListener(session, new SPSessionListener(infoKeyString, tokenID));
} catch (SessionException e) {
SAML2Utils.debug.error("SPACSUtils.saveInfoInMemory: " + "Unable to add session listener.");
}
}
use of com.sun.identity.saml2.profile.IDPSession in project OpenAM by OpenRock.
the class IDPSingleLogoutServiceSOAP method doPost.
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
// handle DOS attack
SAMLUtils.checkHTTPContentLength(req);
// Get IDP entity ID
String idpMetaAlias = SAML2MetaUtils.getMetaAliasByUri(req.getRequestURI());
String idpEntityID = SAML2Utils.getSAML2MetaManager().getEntityByMetaAlias(idpMetaAlias);
String realm = SAML2MetaUtils.getRealmByMetaAlias(idpMetaAlias);
if (!SAML2Utils.isIDPProfileBindingSupported(realm, idpEntityID, SAML2Constants.SLO_SERVICE, SAML2Constants.SOAP)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("unsupportedBinding"));
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("IDPSLOSOAP.doPost : uri =" + req.getRequestURI() + ", idpMetaAlias=" + idpMetaAlias + ", idpEntityID=" + idpEntityID);
}
SOAPMessage msg = SOAPCommunicator.getInstance().getSOAPMessage(req);
Map aMap = IDPProxyUtil.getSessionPartners(msg);
List partners = (List) aMap.get(SAML2Constants.PARTNERS);
SOAPMessage reply = null;
reply = onMessage(msg, req, resp, idpEntityID, realm);
if (reply != null) {
// IDP Proxy case
if (partners != null && (!partners.isEmpty())) {
Element reqElem = SOAPCommunicator.getInstance().getSamlpElement(msg, "LogoutRequest");
LogoutRequest logoutReq = ProtocolFactory.getInstance().createLogoutRequest(reqElem);
IDPCache.SOAPMessageByLogoutRequestID.put(logoutReq.getID(), reply);
IDPProxyUtil.sendProxyLogoutRequestSOAP(req, resp, resp.getWriter(), reply, partners, (IDPSession) aMap.get(SAML2Constants.IDP_SESSION));
} else {
if (reply.saveRequired()) {
reply.saveChanges();
}
resp.setStatus(HttpServletResponse.SC_OK);
SAML2Utils.putHeaders(reply.getMimeHeaders(), resp);
// Write out the message on the response stream
OutputStream os = resp.getOutputStream();
reply.writeTo(os);
os.flush();
}
} else {
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
} catch (SAML2Exception ex) {
SAML2Utils.debug.error("IDPSingleLogoutServiceSOAP", ex);
SAMLUtils.sendError(req, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "singleLogoutFailed", ex.getMessage());
return;
} catch (SOAPException soap) {
SAML2Utils.debug.error("IDPSingleLogoutServiceSOAP", soap);
SAMLUtils.sendError(req, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "singleLogoutFailed", soap.getMessage());
return;
}
}
Aggregations