Class SAMLUtils


  • public class SAMLUtils
    extends SAMLUtilsCommon
    This class contains some utility methods for processing SAML protocols.
    • Field Detail

      • HTTP_MAX_CONTENT_LENGTH

        public static final String HTTP_MAX_CONTENT_LENGTH
        Attribute that specifies maximum content length for SAML request in AMConfig.properties file.
        See Also:
        Constant Field Values
      • defaultMaxLength

        public static final int defaultMaxLength
        Default maximum content length is set to 16k.
        See Also:
        Constant Field Values
      • DEFAULT_CONTENT_LENGTH

        public static final String DEFAULT_CONTENT_LENGTH
        Default maximum content length in string format.
    • Method Detail

      • generateAssertionID

        public static String generateAssertionID()
        Generates an ID String with length of SAMLConstants.ID_LENGTH.
        Returns:
        string the ID String; or null if it fails.
      • checkQuery

        public static boolean checkQuery​(Element element,
                                         String queryname)
        Verifies if an element is a type of a specific query. Currently, this method is used by class AuthenticationQuery, AuthorizationDecisionQuery, and AttributeQuery.
        Parameters:
        element - a DOM Element which needs to be verified.
        queryname - A specific name of a query, for example, AuthenticationQuery, AuthorizationDecisionQuery, or AttributeQuery.
        Returns:
        true if the element is a type of the specified query; false otherwise.
      • generateSourceID

        public static String generateSourceID​(String siteURL)
        Generates sourceID of a site.
        Parameters:
        siteURL - a String that uniquely identifies a site.
        Returns:
        Base64 encoded SHA digest of siteURL.
      • generateAssertionHandle

        public static String generateAssertionHandle()
        Generates assertion handle.
        Returns:
        20-byte random string to be used to form an artifact.
      • hexStringToByteArray

        public static byte[] hexStringToByteArray​(String hexString)
        Converts a HEX encoded string to a byte array.
        Parameters:
        hexString - HEX encoded string
        Returns:
        byte array.
      • hexStringToBase64

        public static String hexStringToBase64​(String hexString)
        Converts HEX encoded string to Base64 encoded string.
        Parameters:
        hexString - HEX encoded string.
        Returns:
        Base64 encoded string.
      • getSourceSite

        public static SAMLServiceManager.SOAPEntry getSourceSite​(String issuer)
        Gets sourceSite corresponding to an issuer from the partner URL list.
        Parameters:
        issuer - The issuer string.
        Returns:
        SAMLServiceManager.SOAPEntry of the issuer if it's on the list; null otherwise.
      • main

        public static void main​(String[] args)
        Returns site ID based on the host name. The site ID will be in Base64 encoded format. This method will print out site ID to the standard output
        Parameters:
        args - host name
      • isCorrectConfirmationMethod

        public static boolean isCorrectConfirmationMethod​(SubjectConfirmation sc)
        Checks if a SubjectConfirmation is correct.
        Parameters:
        sc - SubjectConfirmation instance to be checked.
        Returns:
        true if the SubjectConfirmation instance passed in has only one ConfirmationMethod, and this ConfirmationMethod is set to SAMLConstants.CONFIRMATION_METHOD_IS.
      • isAuthNAssertion

        public static boolean isAuthNAssertion​(Assertion assertion)
        Returns true if the assertion is valid both time wise and signature wise, and contains at least one AuthenticationStatement.
        Parameters:
        assertion - Assertion instance to be checked.
        Returns:
        true if the assertion is valid both time wise and signature wise, and contains at least one AuthenticationStatement.
      • stringToByteArray

        public static byte[] stringToByteArray​(String input)
        Converts a string to a byte array.
        Parameters:
        input - a String to be converted.
        Returns:
        result byte array.
      • getServerID

        public static String getServerID​(String idTypeString)
        Returns server ID.
        Parameters:
        idTypeString - An ID string
        Returns:
        server ID part of the id.
      • getServerURL

        public static String getServerURL​(String str)
        Returns server url of a site.
        Parameters:
        str - Server ID.
        Returns:
        Server url corresponding to the server id.
      • getFullServiceURL

        public static String getFullServiceURL​(String shortUrl)
        Returns full service url.
        Parameters:
        shortUrl - short URL of the service.
        Returns:
        full service url.
      • addEnvParamsFromAssertion

        public static void addEnvParamsFromAssertion​(Map envParameters,
                                                     Assertion assertion,
                                                     Subject subject)
        Returns attributes included in AttributeStatement of the assertion.
        Parameters:
        envParameters - return map which includes name value pairs of attributes included in AttributeStatement of the assertion
        assertion - an Assertion object which contains AttributeStatement
        subject - the Subject instance from AuthenticationStatement. The Subject included in AttributeStatement must match this Subject instance.
      • getMaxContentLength

        public static int getMaxContentLength()
        Returns maximum content length of a SAML request.
        Returns:
        maximum content length of a SAML request.
      • checkHTTPContentLength

        public static void checkHTTPContentLength​(jakarta.servlet.http.HttpServletRequest request)
                                           throws jakarta.servlet.ServletException
        Checks content length of a http request to avoid dos attack. In case SAML inter-op with other SAML vendor who may not provide content length in HttpServletRequest. We decide to support no length restriction for Http communication. Here, we use a special value (e.g. 0) to indicate that no enforcement is required.
        Parameters:
        request - HttpServletRequest instance to be checked.
        Throws:
        jakarta.servlet.ServletException - if context length of the request exceeds maximum content length allowed.
      • postToTarget

        public static void postToTarget​(jakarta.servlet.http.HttpServletResponse response,
                                        PrintWriter out,
                                        List assertion,
                                        String targeturl,
                                        Map attrMap)
                                 throws IOException
        Post assertions and attributes to the target url. This method opens a URL connection to the target specified and POSTs assertions to it using the passed HttpServletResponse object. It POSTs multiple parameter names "assertion" with value being each of the Assertion in the passed Set.
        Parameters:
        response - HttpServletResponse object
        out - The print writer which for content is to be written too.
        assertion - List of Assertions to be posted.
        targeturl - target url
        attrMap - Map of attributes to be posted to the target
        Throws:
        IOException
      • postYN

        public static boolean postYN​(String targetIn)
        Returns true of false based on whether the target passed as parameter accepts form POST.
        Parameters:
        targetIn - url to be checked
        Returns:
        true if it should post assertion to the target passed in; false otherwise.
      • HTMLEncode

        public static String HTMLEncode​(String srcStr,
                                        char ch)
        Replaces every occurence of ch with "&#<ascii code of ch>;"
        Parameters:
        srcStr - orginal string to to be encoded.
        ch - the charactor needs to be encoded.
        Returns:
        encoded string
      • displayXML

        public static String displayXML​(String input)
        Displays an XML string. This is a utility function used to hack up an HTML display of an XML string.
        Parameters:
        input - original string
        Returns:
        encoded string so it can be displayed properly by html.
      • getListOfAssertions

        public static List getListOfAssertions​(List assertions)
        Gets the list of Assertion objects from a list of 'String' assertions.
        Parameters:
        assertions - List of assertions in string format
        Returns:
        List of Assertion objects
      • getResponseBytes

        public static byte[] getResponseBytes​(Response samlResponse)
                                       throws SAMLException
        Returns byte array from a SAML Response.
        Parameters:
        samlResponse - Response object
        Returns:
        byte array
        Throws:
        SAMLException - if error occurrs during the process.
      • getResponse

        public static Response getResponse​(byte[] bytes)
        Returns Response object from byte array.
        Parameters:
        bytes - byte array
        Returns:
        Response object
      • verifyResponse

        public static boolean verifyResponse​(Response response,
                                             String requestUrl,
                                             jakarta.servlet.http.HttpServletRequest request)
        Verifies a Response.
        Parameters:
        response - SAML Response object
        requestUrl - this server's POST profile URL
        request - HttpServletRequest object
        Returns:
        true if the response is valid; false otherwise.
      • getStrAssertions

        public static List getStrAssertions​(List assertions)
        Gets List of assertions in String format from a list of Assertion objects.
        Parameters:
        assertions - List of Assertion objects.
        Returns:
        List of assertions in String format
      • verifySignature

        public static boolean verifySignature​(Response samlResponse)
        Verifies Signature for Post response.
        Parameters:
        samlResponse - Response object from post profile.
        Returns:
        true if the signature on the reponse is valid; false otherwise.
      • getAttributeMap

        public static Map getAttributeMap​(SAMLServiceManager.SOAPEntry partnerdest,
                                          List assertions,
                                          Subject subject,
                                          String target)
                                   throws Exception
        Gets Attribute Map to be set in the Session.
        Parameters:
        partnerdest - SOAPEntry object
        assertions - List of Assertions
        subject - Subject object
        target - target of final SSO
        Returns:
        Map which contains name and attributes.
        Throws:
        Exception - if an error occurrs.
      • verifyAssertionAndGetSSMap

        public static Map verifyAssertionAndGetSSMap​(Response response)
        Checks response and get back a Map of relevant data including, Subject, SOAPEntry for the partner and the List of Assertions.
        Parameters:
        response - Response object
        Returns:
        Map of data including Subject, SOAPEntry, and list of assertions.
      • examAssertions

        public static Subject examAssertions​(List assertions)
                                      throws IOException
        Determines if there is a valid SSO Assertion inside of SAML Response.
        Parameters:
        assertions - a List of Assertion objects
        Returns:
        a Subject object
        Throws:
        IOException - IOException
      • checkSignatureValid

        public static boolean checkSignatureValid​(String xmlString,
                                                  String idAttribute,
                                                  String issuer)
        Return whether the signature on the object is valid or not.
        Parameters:
        xmlString - input XML String
        idAttribute - ASSERTION_ID_ATTRIBUTE or RESPONSE_ID_ATTRIBUTE
        issuer - the issuer of the Assertion
        Returns:
        true if the signature on the object is valid; false otherwise.
      • setMimeHeaders

        public static void setMimeHeaders​(jakarta.xml.soap.MimeHeaders headers,
                                          jakarta.servlet.http.HttpServletResponse response)
        Sets the given HttpServletResponse object with the headers in the given MimeHeaders object.
        Parameters:
        headers - the MimeHeaders object
        response - the HttpServletResponse object to which the headers are to be written.
      • getMimeHeaders

        public static jakarta.xml.soap.MimeHeaders getMimeHeaders​(jakarta.servlet.http.HttpServletRequest req)
        Returns a MimeHeaders object that contains the headers in the given HttpServletRequest object.
        Parameters:
        req - the HttpServletRequest object.
        Returns:
        a new MimeHeaders object containing the headers.
      • getLoginRedirectURL

        public static String getLoginRedirectURL​(jakarta.servlet.http.HttpServletRequest req)
        Returns the authenticaion login url with goto parameter in the given HttpServletRequest object.
        Parameters:
        req - the HttpServletRequest object.
        Returns:
        a new authenticaion login url with goto parameter.
      • processArtifact

        public static Map processArtifact​(String[] artifact,
                                          String target)
                                   throws SAMLException
        Processes SAML Artifact
        Parameters:
        artifact - SAML Artifact
        target - Target URL
        Returns:
        Attribute Map
        Throws:
        SAMLException - if failed to get the Assertions or Attribute Map.
      • generateSession

        public static Object generateSession​(jakarta.servlet.http.HttpServletRequest request,
                                             jakarta.servlet.http.HttpServletResponse response,
                                             Map attrMap)
                                      throws SAMLException
        Creates Session
        Parameters:
        request - HttpServletRequest
        response - HttpServletResponse
        attrMap - Attribute Map
        Throws:
        SAMLException
      • processResponse

        public static Map processResponse​(Response samlResponse,
                                          String target)
                                   throws SAMLException
        Processes SAML Response
        Parameters:
        samlResponse - SAML Response object
        target - Target URL
        Returns:
        Attribute Map
        Throws:
        SAMLException - if failed to get Attribute Map.
      • getCanonicalElement

        public static Element getCanonicalElement​(Node node)
        Gets input Node Canonicalized
        Parameters:
        node - Node
        Returns:
        Canonical element if the operation succeeded. Otherwise, return null.
      • sendError

        public static void sendError​(jakarta.servlet.http.HttpServletRequest request,
                                     jakarta.servlet.http.HttpServletResponse response,
                                     int httpStatusCode,
                                     String errorCode,
                                     String errorMsg)
        Sends to error page URL for SAML protocols. If the error page is hosted in the same web application, forward is used with parameters. Otherwise, redirection or HTTP POST is used with parameters. Three parameters are passed to the error URL: -- errorcode : Error key, this is the I18n key of the error message. -- httpstatuscode : Http status code for the error -- message : detailed I18n'd error message
        Parameters:
        request - HttpServletRequest object
        response - HttpServletResponse object
        httpStatusCode - Http Status code
        errorCode - Error code
        errorMsg - Detailed error message