use of com.sun.identity.saml2.profile.ResponseInfo in project OpenAM by OpenRock.
the class SAML2Proxy method getUrl.
private static String getUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
if (request == null || response == null) {
DEBUG.error("SAML2Proxy: Null request or response");
return getUrlWithError(request, BAD_REQUEST);
}
try {
SAMLUtils.checkHTTPContentLength(request);
} catch (ServletException se) {
DEBUG.error("SAML2Proxy: content length too large");
return getUrlWithError(request, BAD_REQUEST);
}
if (FSUtils.needSetLBCookieAndRedirect(request, response, false)) {
return getUrlWithError(request, MISSING_COOKIE);
}
// get entity id and orgName
String requestURL = request.getRequestURL().toString();
String metaAlias = SAML2MetaUtils.getMetaAliasByUri(requestURL);
SAML2MetaManager metaManager = SAML2Utils.getSAML2MetaManager();
String hostEntityId;
if (metaManager == null) {
DEBUG.error("SAML2Proxy: Unable to obtain metaManager");
return getUrlWithError(request, MISSING_META_MANAGER);
}
try {
hostEntityId = metaManager.getEntityByMetaAlias(metaAlias);
if (hostEntityId == null) {
throw new SAML2MetaException("Caught Instantly");
}
} catch (SAML2MetaException sme) {
DEBUG.warning("SAML2Proxy: unable to find hosted entity with metaAlias: {} Exception: {}", metaAlias, sme.toString());
return getUrlWithError(request, META_DATA_ERROR);
}
String realm = SAML2MetaUtils.getRealmByMetaAlias(metaAlias);
if (StringUtils.isEmpty(realm)) {
realm = "/";
}
ResponseInfo respInfo;
try {
respInfo = SPACSUtils.getResponse(request, response, realm, hostEntityId, metaManager);
} catch (SAML2Exception se) {
DEBUG.error("SAML2Proxy: Unable to obtain SAML response", se);
return getUrlWithError(request, SAML_GET_RESPONSE_ERROR, se.getL10NMessage(request.getLocale()));
}
Map smap;
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) {
DEBUG.error("SAML2Proxy: An error occurred while verifying the SAML response", se);
return getUrlWithError(request, SAML_VERIFY_RESPONSE_ERROR, se.getL10NMessage(request.getLocale()));
}
String key = generateKey();
//survival time is one hour
SAML2ResponseData data = new SAML2ResponseData((String) smap.get(SAML2Constants.SESSION_INDEX), (Subject) smap.get(SAML2Constants.SUBJECT), (Assertion) smap.get(SAML2Constants.POST_ASSERTION), respInfo);
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
try {
//counted in seconds
long sessionExpireTime = System.currentTimeMillis() / 1000 + SPCache.interval;
SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(key, data, sessionExpireTime);
} catch (SAML2TokenRepositoryException e) {
DEBUG.error("An error occurred while persisting the SAML token", e);
return getUrlWithError(request, SAML_FAILOVER_DISABLED_ERROR);
}
} else {
SAML2Store.saveTokenWithKey(key, data);
}
return getUrlWithKey(request, key);
}
use of com.sun.identity.saml2.profile.ResponseInfo in project OpenAM by OpenRock.
the class SPACSUtils method getResponse.
/**
* Retrieves <code>SAML</code> <code>Response</code> from http request.
* It handles three cases:
* <pre>
* 1. using http method get using request parameter "resID".
* This is the case after local login is done.
* 2. using http method get using request parameter "SAMLart".
* This is the case for artifact profile.
* 3. using http method post. This is the case for post profile.
* </pre>
*
* @param request http servlet request
* @param response http servlet response
* @param orgName realm or organization name the service provider resides in
* @param hostEntityId Entity ID of the hosted service provider
* @param metaManager <code>SAML2MetaManager</code> instance.
* @return <code>ResponseInfo</code> instance.
* @throws SAML2Exception,IOException if it fails in the process.
*/
public static ResponseInfo getResponse(HttpServletRequest request, HttpServletResponse response, String orgName, String hostEntityId, SAML2MetaManager metaManager) throws SAML2Exception, IOException {
ResponseInfo respInfo = null;
String method = request.getMethod();
if (method.equals("GET")) {
if (!SAML2Utils.isSPProfileBindingSupported(orgName, hostEntityId, SAML2Constants.ACS_SERVICE, SAML2Constants.HTTP_ARTIFACT)) {
SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "unsupportedBinding", SAML2Utils.bundle.getString("unsupportedBinding"));
throw new SAML2Exception(SAML2Utils.bundle.getString("unsupportedBinding"));
}
respInfo = getResponseFromGet(request, response, orgName, hostEntityId, metaManager);
} else if (method.equals("POST")) {
String pathInfo = request.getPathInfo();
if ((pathInfo != null) && (pathInfo.startsWith("/ECP"))) {
if (!SAML2Utils.isSPProfileBindingSupported(orgName, hostEntityId, SAML2Constants.ACS_SERVICE, SAML2Constants.PAOS)) {
SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "unsupportedBinding", SAML2Utils.bundle.getString("unsupportedBinding"));
throw new SAML2Exception(SAML2Utils.bundle.getString("unsupportedBinding"));
}
respInfo = getResponseFromPostECP(request, response, orgName, hostEntityId, metaManager);
} else {
if (!SAML2Utils.isSPProfileBindingSupported(orgName, hostEntityId, SAML2Constants.ACS_SERVICE, SAML2Constants.HTTP_POST)) {
SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "unsupportedBinding", SAML2Utils.bundle.getString("unsupportedBinding"));
throw new SAML2Exception(SAML2Utils.bundle.getString("unsupportedBinding"));
}
respInfo = getResponseFromPost(request, response, orgName, hostEntityId, metaManager);
}
} else {
// not supported
SAMLUtils.sendError(request, response, response.SC_METHOD_NOT_ALLOWED, "notSupportedHTTPMethod", SAML2Utils.bundle.getString("notSupportedHTTPMethod"));
throw new SAML2Exception(SAML2Utils.bundle.getString("notSupportedHTTPMethod"));
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPACSUtils.getResponse: got response=" + respInfo.getResponse().toXMLString(true, true));
}
return respInfo;
}
use of com.sun.identity.saml2.profile.ResponseInfo in project OpenAM by OpenRock.
the class SPACSUtils method processResponseForFedlet.
/**
* Processes response from Identity Provider to Fedlet (SP).
* This will do all required protocol processing, include signature,
* issuer and audience validation etc. A map containing processing
* result will be returned. <br>
* Here is a list of keys and values for the returned map: <br>
* SAML2Constants.ATTRIBUTE_MAP -- Attribute map containing all attributes
* passed down from IDP inside the
* Assertion. The value is a
* <code>java.util.Map</code> whose keys
* are attribute names and values are
* <code>java.util.Set</code> of string
* values for the attributes. <br>
* SAML2Constants.RELAY_STATE -- Relay state, value is a string <br>
* SAML2Constants.IDPENTITYID -- IDP entity ID, value is a string<br>
* SAML2Constants.RESPONSE -- Response object, value is an instance of
* com.sun.identity.saml2.protocol.Response
* SAML2Constants.ASSERTION -- Assertion object, value is an instance of
* com.sun.identity.saml2.assertion.Assertion
* SAML2Constants.SUBJECT -- Subject object, value is an instance of
* com.sun.identity.saml2.assertion.Subject
* SAML2Constants.NAMEID -- NameID object, value is an instance of
* com.sun.identity.saml2.assertion.NameID
*
* @param request HTTP Servlet request
* @param response HTTP Servlet response.
* @param out the print writer for writing out presentation
*
* @return <code>Map</code> which holds result of the processing.
* @throws SAML2Exception if the processing failed due to server error.
* @throws IOException if the processing failed due to IO error.
* @throws SessionException if the processing failed due to session error.
* @throws ServletException if the processing failed due to request error.
*
* @supported.api
*/
public static Map processResponseForFedlet(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws SAML2Exception, IOException, SessionException, ServletException {
if ((request == null) || (response == null)) {
throw new ServletException(SAML2SDKUtils.bundle.getString("nullInput"));
}
String requestURL = request.getRequestURL().toString();
SAML2MetaManager metaManager = new SAML2MetaManager();
if (metaManager == null) {
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorMetaManager"));
}
String metaAlias = SAML2MetaUtils.getMetaAliasByUri(requestURL);
if ((metaAlias == null) || (metaAlias.length() == 0)) {
// Check in case metaAlias has been supplied as a parameter
metaAlias = request.getParameter(SAML2MetaManager.NAME_META_ALIAS_IN_URI);
if (metaAlias == null || metaAlias.length() == 0) {
// pick the first available one
List spMetaAliases = metaManager.getAllHostedServiceProviderMetaAliases("/");
if ((spMetaAliases != null) && !spMetaAliases.isEmpty()) {
// get first one
metaAlias = (String) spMetaAliases.get(0);
}
if ((metaAlias == null) || (metaAlias.length() == 0)) {
throw new ServletException(SAML2SDKUtils.bundle.getString("nullSPEntityID"));
}
}
}
String hostEntityId = null;
try {
hostEntityId = metaManager.getEntityByMetaAlias(metaAlias);
} catch (SAML2MetaException sme) {
SAML2SDKUtils.debug.error("SPACSUtils.processResponseForFedlet", sme);
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("metaDataError"));
}
if (hostEntityId == null) {
// logging?
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("metaDataError"));
}
// organization is always root org
String orgName = "/";
String relayState = request.getParameter(SAML2Constants.RELAY_STATE);
SessionProvider sessionProvider = null;
ResponseInfo respInfo = null;
try {
sessionProvider = SessionManager.getProvider();
} catch (SessionException se) {
SAML2SDKUtils.debug.error("SPACSUtils.processResponseForFedlet", se);
throw new SAML2Exception(se);
}
respInfo = SPACSUtils.getResponse(request, response, orgName, hostEntityId, metaManager);
Object newSession = null;
// Throws a SAML2Exception if the response cannot be validated
// or contains a non-Success StatusCode, invoking the SPAdapter SPI
// for taking action on the failed validation.
// The resulting exception has its redirectionDone flag set if
// the SPAdapter issued a HTTP redirect.
newSession = SPACSUtils.processResponse(request, response, out, metaAlias, null, respInfo, orgName, hostEntityId, metaManager, null);
SAML2SDKUtils.debug.message("SSO SUCCESS");
String[] redirected = sessionProvider.getProperty(newSession, SAML2Constants.RESPONSE_REDIRECTED);
if ((redirected != null) && (redirected.length != 0) && redirected[0].equals("true")) {
SAML2SDKUtils.debug.message("Already redirected in SPAdapter.");
// response redirected already in SPAdapter
return createMapForFedlet(respInfo, null, hostEntityId);
}
// redirect to relay state
String finalUrl = SPACSUtils.getRelayState(relayState, orgName, hostEntityId, metaManager);
String realFinalUrl = finalUrl;
if (finalUrl != null && finalUrl.length() != 0) {
try {
realFinalUrl = sessionProvider.rewriteURL(newSession, finalUrl);
} catch (SessionException se) {
SAML2SDKUtils.debug.message("SPACSUtils.processRespForFedlet", se);
realFinalUrl = finalUrl;
}
}
String redirectUrl = SPACSUtils.getIntermediateURL(orgName, hostEntityId, metaManager);
String realRedirectUrl = null;
if (redirectUrl != null && redirectUrl.length() != 0) {
if (realFinalUrl != null && realFinalUrl.length() != 0) {
if (redirectUrl.indexOf("?") != -1) {
redirectUrl += "&goto=";
} else {
redirectUrl += "?goto=";
}
redirectUrl += URLEncDec.encode(realFinalUrl);
try {
realRedirectUrl = sessionProvider.rewriteURL(newSession, redirectUrl);
} catch (SessionException se) {
SAML2SDKUtils.debug.message("SPACSUtils.processRespForFedlet: rewriting failed.", se);
realRedirectUrl = redirectUrl;
}
} else {
realRedirectUrl = redirectUrl;
}
} else {
realRedirectUrl = finalUrl;
}
return createMapForFedlet(respInfo, realRedirectUrl, hostEntityId);
}
use of com.sun.identity.saml2.profile.ResponseInfo in project OpenAM by OpenRock.
the class SPACSUtils method createMapForFedlet.
private static Map createMapForFedlet(ResponseInfo respInfo, String relayUrl, String hostedEntityId) {
Map map = new HashMap();
if (relayUrl != null) {
map.put(SAML2Constants.RELAY_STATE, relayUrl);
}
Response samlResp = respInfo.getResponse();
map.put(SAML2Constants.RESPONSE, samlResp);
Assertion assertion = respInfo.getAssertion();
map.put(SAML2Constants.ASSERTION, assertion);
map.put(SAML2Constants.SUBJECT, assertion.getSubject());
map.put(SAML2Constants.IDPENTITYID, assertion.getIssuer().getValue());
map.put(SAML2Constants.SPENTITYID, hostedEntityId);
map.put(SAML2Constants.NAMEID, respInfo.getNameId());
map.put(SAML2Constants.ATTRIBUTE_MAP, respInfo.getAttributeMap());
map.put(SAML2Constants.SESSION_INDEX, respInfo.getSessionIndex());
return map;
}
use of com.sun.identity.saml2.profile.ResponseInfo in project OpenAM by OpenRock.
the class SPACSUtils method getResponseFromPostECP.
/**
* Obtains <code>SAML Response</code> from <code>SOAPBody</code>.
* Used by ECP profile.
*/
private static ResponseInfo getResponseFromPostECP(HttpServletRequest request, HttpServletResponse response, String orgName, String hostEntityId, SAML2MetaManager metaManager) throws SAML2Exception, IOException {
Message message = null;
try {
message = new Message(SOAPCommunicator.getInstance().getSOAPMessage(request));
} catch (SOAPException soapex) {
String[] data = { hostEntityId };
LogUtil.error(Level.INFO, LogUtil.CANNOT_INSTANTIATE_SOAP_MESSAGE_ECP, data, null);
SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToCreateSOAPMessage", soapex.getMessage());
throw new SAML2Exception(soapex.getMessage());
} catch (SOAPBindingException soapex) {
String[] data = { hostEntityId };
LogUtil.error(Level.INFO, LogUtil.CANNOT_INSTANTIATE_SOAP_MESSAGE_ECP, data, null);
SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToCreateSOAPMessage", soapex.getMessage());
throw new SAML2Exception(soapex.getMessage());
} catch (SOAPFaultException sfex) {
String[] data = { hostEntityId };
LogUtil.error(Level.INFO, LogUtil.RECEIVE_SOAP_FAULT_ECP, data, null);
String faultString = sfex.getSOAPFaultMessage().getSOAPFault().getFaultString();
SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToCreateSOAPMessage", faultString);
throw new SAML2Exception(faultString);
}
List soapHeaders = message.getOtherSOAPHeaders();
ECPRelayState ecpRelayState = null;
if ((soapHeaders != null) && (!soapHeaders.isEmpty())) {
for (Iterator iter = soapHeaders.iterator(); iter.hasNext(); ) {
Element headerEle = (Element) iter.next();
try {
ecpRelayState = ECPFactory.getInstance().createECPRelayState(headerEle);
break;
} catch (SAML2Exception saml2ex) {
// not ECP RelayState
}
}
}
String relayState = null;
if (ecpRelayState != null) {
relayState = ecpRelayState.getValue();
}
List soapBodies = message.getBodies();
if ((soapBodies == null) || (soapBodies.isEmpty())) {
String[] data = { hostEntityId };
LogUtil.error(Level.INFO, LogUtil.CANNOT_INSTANTIATE_SAML_RESPONSE_FROM_ECP, data, null);
SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "missingSAMLResponse", SAML2Utils.bundle.getString("missingSAMLResponse"));
throw new SAML2Exception(SAML2Utils.bundle.getString("missingSAMLResponse"));
}
Element resElem = (Element) soapBodies.get(0);
Response resp = null;
try {
resp = ProtocolFactory.getInstance().createResponse(resElem);
} catch (SAML2Exception se) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPACSUtils.getResponseFromPostECP:" + "Couldn't create Response:", se);
}
String[] data = { hostEntityId };
LogUtil.error(Level.INFO, LogUtil.CANNOT_INSTANTIATE_SAML_RESPONSE_FROM_ECP, data, null);
SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToCreateResponse", se.getMessage());
throw se;
}
String idpEntityID = resp.getIssuer().getValue();
IDPSSODescriptorElement idpDesc = null;
try {
idpDesc = metaManager.getIDPSSODescriptor(orgName, idpEntityID);
} catch (SAML2MetaException se) {
String[] data = { orgName, idpEntityID };
LogUtil.error(Level.INFO, LogUtil.IDP_META_NOT_FOUND, data, null);
SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToGetIDPSSODescriptor", se.getMessage());
throw se;
}
Set<X509Certificate> certificates = KeyUtil.getVerificationCerts(idpDesc, idpEntityID, SAML2Constants.IDP_ROLE);
List assertions = resp.getAssertion();
if ((assertions != null) && (!assertions.isEmpty())) {
for (Iterator iter = assertions.iterator(); iter.hasNext(); ) {
Assertion assertion = (Assertion) iter.next();
if (!assertion.isSigned()) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPACSUtils.getResponseFromPostECP: " + " Assertion is not signed.");
}
String[] data = { idpEntityID };
LogUtil.error(Level.INFO, LogUtil.ECP_ASSERTION_NOT_SIGNED, data, null);
SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "assertionNotSigned", SAML2Utils.bundle.getString("assertionNotSigned"));
throw new SAML2Exception(SAML2Utils.bundle.getString("assertionNotSigned"));
} else if (!assertion.isSignatureValid(certificates)) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPACSUtils.getResponseFromPostECP: " + " Assertion signature is invalid.");
}
String[] data = { idpEntityID };
LogUtil.error(Level.INFO, LogUtil.ECP_ASSERTION_INVALID_SIGNATURE, data, null);
SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "invalidSignature", SAML2Utils.bundle.getString("invalidSignature"));
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignature"));
}
}
}
return new ResponseInfo(resp, SAML2Constants.PAOS, relayState);
}
Aggregations