Search in sources :

Example 1 with NameID

use of com.sun.identity.saml2.assertion.NameID in project OpenAM by OpenRock.

the class DefaultFedletAdapter method onFedletSLOSuccessOrFailure.

private void onFedletSLOSuccessOrFailure(HttpServletRequest request, HttpServletResponse response, LogoutRequest logoutReq, LogoutResponse logoutRes, String hostedEntityID, String idpEntityID, String binding, boolean isSuccess) throws SAML2Exception {
    String method = "DefaultFedletAdapter:onFedletSLOSuccessOrFailure:";
    try {
        if (logoutUrl == null) {
            BaseConfigType spConfig = SAML2Utils.getSAML2MetaManager().getSPSSOConfig("/", hostedEntityID);
            List appLogoutURL = (List) SAML2MetaUtils.getAttributes(spConfig).get(SAML2Constants.APP_LOGOUT_URL);
            if ((appLogoutURL != null) && !appLogoutURL.isEmpty()) {
                logoutUrl = (String) appLogoutURL.get(0);
            }
        }
        if (logoutUrl == null) {
            String deployuri = request.getRequestURI();
            int slashLoc = deployuri.indexOf("/", 1);
            if (slashLoc != -1) {
                deployuri = deployuri.substring(0, slashLoc);
            }
            if (deployuri != null) {
                String url = request.getRequestURL().toString();
                int loc = url.indexOf(deployuri + "/");
                if (loc != -1) {
                    logoutUrl = url.substring(0, loc + deployuri.length()) + "/logout";
                }
            }
        }
        if (logoutUrl == null) {
            return;
        }
        URL url = new URL(logoutUrl);
        HttpURLConnection conn = HttpURLConnectionManager.getConnection(url);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setFollowRedirects(false);
        conn.setInstanceFollowRedirects(false);
        // replay cookies
        String strCookies = SAML2Utils.getCookiesString(request);
        if (strCookies != null) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(method + "Sending cookies : " + strCookies);
            }
            conn.setRequestProperty("Cookie", strCookies);
        }
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("IDP", URLEncDec.encode(idpEntityID));
        conn.setRequestProperty("SP", URLEncDec.encode(hostedEntityID));
        if (logoutReq != null) {
            NameID nameID = logoutReq.getNameID();
            if (nameID != null) {
                conn.setRequestProperty("NameIDValue", URLEncDec.encode(nameID.getValue()));
            }
            List siList = logoutReq.getSessionIndex();
            if ((siList != null) && (!siList.isEmpty())) {
                conn.setRequestProperty("SessionIndex", URLEncDec.encode((String) siList.get(0)));
            }
        }
        conn.setRequestProperty("Binding", binding);
        if (isSuccess) {
            conn.setRequestProperty("SLOStatus", "Success");
        } else {
            conn.setRequestProperty("SLOStatus", "Failure");
        }
        OutputStream outputStream = conn.getOutputStream();
        // Write the request to the HTTP server.
        outputStream.write("".getBytes());
        outputStream.flush();
        outputStream.close();
        // Check response code
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(method + "Response code OK");
            }
        } else {
            SAML2Utils.debug.error(method + "Response code NOT OK: " + conn.getResponseCode());
        }
    } catch (Exception e) {
    }
    return;
}
Also used : BaseConfigType(com.sun.identity.saml2.jaxb.entityconfig.BaseConfigType) HttpURLConnection(java.net.HttpURLConnection) NameID(com.sun.identity.saml2.assertion.NameID) OutputStream(java.io.OutputStream) List(java.util.List) URL(java.net.URL) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception)

Example 2 with NameID

use of com.sun.identity.saml2.assertion.NameID 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;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) NameIDandSPpair(com.sun.identity.saml2.profile.NameIDandSPpair) IDPSession(com.sun.identity.saml2.profile.IDPSession) NameID(com.sun.identity.saml2.assertion.NameID) SessionException(com.sun.identity.plugin.session.SessionException) SessionProvider(com.sun.identity.plugin.session.SessionProvider)

Example 3 with NameID

use of com.sun.identity.saml2.assertion.NameID in project OpenAM by OpenRock.

the class DefaultFedletAdapter method doFedletSLO.

/**
     * Invokes after Fedlet receives SLO request from IDP. It does the work
     * of logout the user.
     * @param request servlet request
     * @param response servlet response
     * @param hostedEntityID entity ID for the fedlet
     * @param idpEntityID entity id for the IDP to which the request is
     *          received from.
     * @param siList List of SessionIndex whose session to be logged out
     * @param nameIDValue nameID value whose session to be logged out
     * @param binding Single Logout binding used,
     *      one of following values:
     *          <code>SAML2Constants.SOAP</code>,
     *          <code>SAML2Constants.HTTP_POST</code>,
     *          <code>SAML2Constants.HTTP_REDIRECT</code>
     * @return <code>true</code> if user is logged out successfully;
     *          <code>false</code> otherwise.
     * @exception SAML2Exception if user want to fail the process.
     */
public boolean doFedletSLO(HttpServletRequest request, HttpServletResponse response, LogoutRequest logoutReq, String hostedEntityID, String idpEntityID, List siList, String nameIDValue, String binding) throws SAML2Exception {
    boolean status = true;
    String method = "DefaultFedletAdapter:doFedletSLO:";
    try {
        if (logoutUrl == null) {
            BaseConfigType spConfig = SAML2Utils.getSAML2MetaManager().getSPSSOConfig("/", hostedEntityID);
            List appLogoutURL = (List) SAML2MetaUtils.getAttributes(spConfig).get(SAML2Constants.APP_LOGOUT_URL);
            if ((appLogoutURL != null) && !appLogoutURL.isEmpty()) {
                logoutUrl = (String) appLogoutURL.get(0);
            }
        }
        if (logoutUrl == null) {
            String deployuri = request.getRequestURI();
            int slashLoc = deployuri.indexOf("/", 1);
            if (slashLoc != -1) {
                deployuri = deployuri.substring(0, slashLoc);
            }
            if (deployuri != null) {
                String url = request.getRequestURL().toString();
                int loc = url.indexOf(deployuri + "/");
                if (loc != -1) {
                    logoutUrl = url.substring(0, loc + deployuri.length()) + "/logout";
                }
            }
        }
        if (logoutUrl == null) {
            return status;
        }
        URL url = new URL(logoutUrl);
        HttpURLConnection conn = HttpURLConnectionManager.getConnection(url);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setFollowRedirects(false);
        conn.setInstanceFollowRedirects(false);
        // replay cookies
        String strCookies = SAML2Utils.getCookiesString(request);
        if (strCookies != null) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(method + "Sending cookies : " + strCookies);
            }
            conn.setRequestProperty("Cookie", strCookies);
        }
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("IDP", URLEncDec.encode(idpEntityID));
        conn.setRequestProperty("SP", URLEncDec.encode(hostedEntityID));
        conn.setRequestProperty("NameIDValue", URLEncDec.encode(nameIDValue));
        if (siList != null && !siList.isEmpty()) {
            Iterator iter = siList.iterator();
            StringBuffer siValue = new StringBuffer();
            siValue.append((String) iter.next());
            while (iter.hasNext()) {
                siValue.append(",").append((String) iter.next());
            }
            conn.setRequestProperty("SessionIndex", URLEncDec.encode(siValue.toString()));
        }
        conn.setRequestProperty("Binding", binding);
        OutputStream outputStream = conn.getOutputStream();
        // Write the request to the HTTP server.
        outputStream.write("".getBytes());
        outputStream.flush();
        outputStream.close();
        // Check response code
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(method + "Response code OK");
            }
            status = true;
        } else {
            SAML2Utils.debug.error(method + "Response code NOT OK: " + conn.getResponseCode());
            status = false;
        }
    } catch (Exception e) {
        status = false;
    }
    return status;
}
Also used : BaseConfigType(com.sun.identity.saml2.jaxb.entityconfig.BaseConfigType) HttpURLConnection(java.net.HttpURLConnection) OutputStream(java.io.OutputStream) Iterator(java.util.Iterator) List(java.util.List) URL(java.net.URL) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception)

Example 4 with NameID

use of com.sun.identity.saml2.assertion.NameID in project OpenAM by OpenRock.

the class SAML2TokenGenerationImpl method encryptNameID.

private void encryptNameID(Assertion assertion, SAML2Config saml2Config, STSInstanceState stsInstanceState) throws TokenCreationException {
    /*
        The null checks below model IDPSSOUtil#signAndEncryptResponseComponents. The Subject and NameID will
        never be null when generated by the DefaultSubjectProvider, but when generated by a custom provider, this
        invariant is not assured.
         */
    Subject subject = assertion.getSubject();
    if (subject == null) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "In SAML2TokenGenerationImpl, saml2Config specifies encryption of NameID, but " + "encapsulating subject is null.");
    }
    NameID nameID = subject.getNameID();
    if (nameID == null) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "In SAML2TokenGenerationImpl, saml2Config specifies encryption of NameID, but " + "NameID in subject is null.");
    }
    try {
        EncryptedID encryptedNameID = nameID.encrypt(stsInstanceState.getSAML2CryptoProvider().getSPX509Certificate(saml2Config.getEncryptionKeyAlias()).getPublicKey(), saml2Config.getEncryptionAlgorithm(), saml2Config.getEncryptionAlgorithmStrength(), saml2Config.getSpEntityId());
        if (encryptedNameID == null) {
            throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "In SAML2TokenGenerationImpl, the EncryptedID returned from NameID#encrypt is null.");
        }
        subject.setEncryptedID(encryptedNameID);
        // reset NameID
        subject.setNameID(null);
        assertion.setSubject(subject);
    } catch (SAML2Exception e) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception thrown encrypting NameID in SAML2TokenGenerationImpl: " + e, e);
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) NameID(com.sun.identity.saml2.assertion.NameID) TokenCreationException(org.forgerock.openam.sts.TokenCreationException) EncryptedID(com.sun.identity.saml2.assertion.EncryptedID) Subject(com.sun.identity.saml2.assertion.Subject)

Example 5 with NameID

use of com.sun.identity.saml2.assertion.NameID 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);
}
Also used : ServletException(javax.servlet.ServletException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SessionException(com.sun.identity.plugin.session.SessionException) List(java.util.List) ArrayList(java.util.ArrayList) SAML2MetaManager(com.sun.identity.saml2.meta.SAML2MetaManager) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) SessionProvider(com.sun.identity.plugin.session.SessionProvider)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)46 NameID (com.sun.identity.saml2.assertion.NameID)33 List (java.util.List)25 ArrayList (java.util.ArrayList)22 EncryptedID (com.sun.identity.saml2.assertion.EncryptedID)18 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)15 HashMap (java.util.HashMap)14 SessionException (com.sun.identity.plugin.session.SessionException)12 NameIDInfo (com.sun.identity.saml2.common.NameIDInfo)12 Map (java.util.Map)11 Subject (com.sun.identity.saml2.assertion.Subject)10 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)10 Element (org.w3c.dom.Element)10 Date (java.util.Date)9 Iterator (java.util.Iterator)9 AssertionFactory (com.sun.identity.saml2.assertion.AssertionFactory)8 SAML2MetaManager (com.sun.identity.saml2.meta.SAML2MetaManager)8 Assertion (com.sun.identity.saml2.assertion.Assertion)7 Issuer (com.sun.identity.saml2.assertion.Issuer)7 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)7