Class SamlResponse


  • public class SamlResponse
    extends java.lang.Object
    SamlResponse class of OneLogin's Java Toolkit. A class that implements SAML 2 Authentication Response parser/validator
    • Field Summary

      Fields 
      Modifier and Type Field Description
      private java.lang.String currentUrl
      URL of the current host + current view
      private org.w3c.dom.Document decryptedDocument
      A DOMDocument object loaded from the SAML Response (Decrypted).
      private java.lang.Boolean encrypted
      Mark if the response contains an encrypted assertion.
      private static org.slf4j.Logger LOGGER
      Private property to construct a logger for this class.
      private java.util.Map<java.lang.String,​java.lang.String> nameIdData
      NameID Data
      private SamlResponseStatus responseStatus
      The respone status code and messages
      private org.w3c.dom.Document samlResponseDocument
      A DOMDocument object loaded from the SAML Response.
      private java.lang.String samlResponseString
      The decoded, unprocessed XML response provided to the constructor.
      private Saml2Settings settings
      Settings data.
      private java.lang.Exception validationException
      After validation, if it fails this property has the cause of the problem
    • Constructor Summary

      Constructors 
      Constructor Description
      SamlResponse​(Saml2Settings settings, HttpRequest request)
      Constructor to have a Response object fully built and ready to validate the saml response.
      SamlResponse​(Saml2Settings settings, java.lang.String currentUrl, java.lang.String samlResponse)
      Constructor to have a Response object fully built and ready to validate the saml response.
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      java.lang.Boolean checkOneAuthnStatement()
      Checks that the samlp:Response/saml:Assertion/saml:AuthnStatement element exists and is unique.
      java.lang.Boolean checkOneCondition()
      Checks that the samlp:Response/saml:Assertion/saml:Conditions element exists and is unique.
      void checkStatus()
      Checks the Status
      private org.w3c.dom.Document decryptAssertion​(org.w3c.dom.Document dom)
      Decrypt assertion.
      java.lang.String getAssertionId()  
      java.lang.String getAssertionIssuer()
      Gets the Assertion Issuer.
      java.util.List<org.joda.time.Instant> getAssertionNotOnOrAfter()  
      java.util.HashMap<java.lang.String,​java.util.List<java.lang.String>> getAttributes()
      Gets the Attributes from the AttributeStatement element.
      java.util.List<java.lang.String> getAudiences()
      Gets the audiences.
      java.lang.String getError()
      After execute a validation process, if fails this method returns the cause
      java.lang.String getId()  
      java.util.List<java.lang.String> getIssuers()
      Deprecated.
      use getResponseIssuer() and/or getAssertionIssuer(); the contract of this method is quite controversial
      java.lang.String getNameId()
      Gets the NameID value provided from the SAML Response String.
      java.util.Map<java.lang.String,​java.lang.String> getNameIdData()
      Gets the NameID provided from the SAML Response Document.
      java.lang.String getNameIdFormat()
      Gets the NameID Format provided from the SAML Response String.
      java.lang.String getNameIdNameQualifier()
      Gets the NameID NameQualifier provided from the SAML Response String.
      java.lang.String getNameIdSPNameQualifier()
      Gets the NameID SP NameQualifier provided from the SAML Response String.
      java.util.Calendar getResponseIssueInstant()
      Returns the issue instant of this message.
      java.lang.String getResponseIssuer()
      Gets the Response Issuer.
      SamlResponseStatus getResponseStatus()
      Returns the ResponseStatus object
      protected org.w3c.dom.Document getSAMLResponseDocument()  
      java.lang.String getSAMLResponseXml()  
      java.lang.String getSessionIndex()
      Gets the SessionIndex from the AuthnStatement.
      org.joda.time.DateTime getSessionNotOnOrAfter()
      Gets the SessionNotOnOrAfter from the AuthnStatement.
      static SamlResponseStatus getStatus​(org.w3c.dom.Document dom)
      Get Status from a Response
      java.lang.Exception getValidationException()
      After execute a validation process, if fails this method returns the Exception object
      boolean isValid()
      Determines if the SAML Response is valid using the certificate.
      boolean isValid​(java.lang.String requestId)
      Determines if the SAML Response is valid using the certificate.
      void loadXmlFromBase64​(java.lang.String responseStr)
      Load a XML base64encoded SAMLResponse
      java.util.ArrayList<java.lang.String> processSignedElements()
      Verifies the signature nodes: - Checks that are Response or Assertion - Check that IDs and reference URI are unique and consistent.
      protected org.w3c.dom.NodeList query​(java.lang.String nameQuery, org.w3c.dom.Node context)
      Extracts nodes that match the query from the DOMDocument (Response Message)
      protected org.w3c.dom.NodeList queryAssertion​(java.lang.String assertionXpath)
      Extracts a node from the DOMDocument (Assertion).
      void setDestinationUrl​(java.lang.String url)
      Aux method to set the destination url
      protected void setValidationException​(java.lang.Exception validationException)
      Sets the validation exception that this SamlResponse should return when a validation error occurs.
      protected void validateAudiences()
      Validates the audiences.
      protected void validateDestination​(org.w3c.dom.Element element)
      Validate the destination.
      java.lang.Boolean validateNumAssertions()
      Verifies that the document only contains a single Assertion (encrypted or not).
      protected SubjectConfirmationIssue validateRecipient​(org.w3c.dom.Node recipient, int index)
      Validate a subject confirmation recipient.
      boolean validateSignedElements​(java.util.ArrayList<java.lang.String> signedElements)
      Verifies that the document has the expected signed nodes.
      protected void validateSpNameQualifier​(java.lang.String spNameQualifier)
      Validates a SPNameQualifier.
      private void validateSubjectConfirmation​(java.lang.String responseInResponseTo)
      Check SubjectConfirmation, at least one SubjectConfirmation must be valid
      boolean validateTimestamps()
      Verifies that the document is still valid according Conditions Element.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • LOGGER

        private static final org.slf4j.Logger LOGGER
        Private property to construct a logger for this class.
      • samlResponseString

        private java.lang.String samlResponseString
        The decoded, unprocessed XML response provided to the constructor.
      • samlResponseDocument

        private org.w3c.dom.Document samlResponseDocument
        A DOMDocument object loaded from the SAML Response.
      • decryptedDocument

        private org.w3c.dom.Document decryptedDocument
        A DOMDocument object loaded from the SAML Response (Decrypted).
      • nameIdData

        private java.util.Map<java.lang.String,​java.lang.String> nameIdData
        NameID Data
      • currentUrl

        private java.lang.String currentUrl
        URL of the current host + current view
      • encrypted

        private java.lang.Boolean encrypted
        Mark if the response contains an encrypted assertion.
      • validationException

        private java.lang.Exception validationException
        After validation, if it fails this property has the cause of the problem
      • responseStatus

        private SamlResponseStatus responseStatus
        The respone status code and messages
    • Constructor Detail

      • SamlResponse

        public SamlResponse​(Saml2Settings settings,
                            java.lang.String currentUrl,
                            java.lang.String samlResponse)
                     throws javax.xml.xpath.XPathExpressionException,
                            javax.xml.parsers.ParserConfigurationException,
                            org.xml.sax.SAXException,
                            java.io.IOException,
                            SettingsException,
                            ValidationError
        Constructor to have a Response object fully built and ready to validate the saml response.
        Parameters:
        settings - Saml2Settings object. Setting data
        currentUrl - URL of the current host + current view
        samlResponse - A string containting the base64 encoded response from the IdP
        Throws:
        ValidationError
        SettingsException
        java.io.IOException
        org.xml.sax.SAXException
        javax.xml.parsers.ParserConfigurationException
        javax.xml.xpath.XPathExpressionException
      • SamlResponse

        public SamlResponse​(Saml2Settings settings,
                            HttpRequest request)
                     throws javax.xml.xpath.XPathExpressionException,
                            javax.xml.parsers.ParserConfigurationException,
                            org.xml.sax.SAXException,
                            java.io.IOException,
                            SettingsException,
                            ValidationError
        Constructor to have a Response object fully built and ready to validate the saml response.
        Parameters:
        settings - Saml2Settings object. Setting data
        request - the HttpRequest object to be processed (Contains GET and POST parameters, request URL, ...).
        Throws:
        ValidationError
        SettingsException
        java.io.IOException
        org.xml.sax.SAXException
        javax.xml.parsers.ParserConfigurationException
        javax.xml.xpath.XPathExpressionException
        java.lang.NullPointerException
    • Method Detail

      • loadXmlFromBase64

        public void loadXmlFromBase64​(java.lang.String responseStr)
                               throws javax.xml.parsers.ParserConfigurationException,
                                      javax.xml.xpath.XPathExpressionException,
                                      org.xml.sax.SAXException,
                                      java.io.IOException,
                                      SettingsException,
                                      ValidationError
        Load a XML base64encoded SAMLResponse
        Parameters:
        responseStr - Saml2Settings object. Setting data
        Throws:
        javax.xml.parsers.ParserConfigurationException
        SettingsException
        java.io.IOException
        org.xml.sax.SAXException
        javax.xml.xpath.XPathExpressionException
        ValidationError
      • isValid

        public boolean isValid​(java.lang.String requestId)
        Determines if the SAML Response is valid using the certificate.
        Parameters:
        requestId - The ID of the AuthNRequest sent by this SP to the IdP
        Returns:
        if the response is valid or not
      • validateSubjectConfirmation

        private void validateSubjectConfirmation​(java.lang.String responseInResponseTo)
                                          throws javax.xml.xpath.XPathExpressionException,
                                                 ValidationError
        Check SubjectConfirmation, at least one SubjectConfirmation must be valid
        Parameters:
        responseInResponseTo - The InResponseTo value of the SAML Response
        Throws:
        javax.xml.xpath.XPathExpressionException
        ValidationError
      • isValid

        public boolean isValid()
        Determines if the SAML Response is valid using the certificate.
        Returns:
        if the response is valid or not
      • getNameIdData

        public java.util.Map<java.lang.String,​java.lang.String> getNameIdData()
                                                                             throws java.lang.Exception
        Gets the NameID provided from the SAML Response Document.
        Returns:
        the Name ID Data (Value, Format, NameQualifier, SPNameQualifier)
        Throws:
        java.lang.Exception
      • getNameId

        public java.lang.String getNameId()
                                   throws java.lang.Exception
        Gets the NameID value provided from the SAML Response String.
        Returns:
        string Name ID Value
        Throws:
        java.lang.Exception
      • getNameIdFormat

        public java.lang.String getNameIdFormat()
                                         throws java.lang.Exception
        Gets the NameID Format provided from the SAML Response String.
        Returns:
        string NameID Format
        Throws:
        java.lang.Exception
      • getNameIdNameQualifier

        public java.lang.String getNameIdNameQualifier()
                                                throws java.lang.Exception
        Gets the NameID NameQualifier provided from the SAML Response String.
        Returns:
        string NameQualifier
        Throws:
        java.lang.Exception
      • getNameIdSPNameQualifier

        public java.lang.String getNameIdSPNameQualifier()
                                                  throws java.lang.Exception
        Gets the NameID SP NameQualifier provided from the SAML Response String.
        Returns:
        string SP NameQualifier
        Throws:
        java.lang.Exception
      • getAttributes

        public java.util.HashMap<java.lang.String,​java.util.List<java.lang.String>> getAttributes()
                                                                                                 throws javax.xml.xpath.XPathExpressionException,
                                                                                                        ValidationError
        Gets the Attributes from the AttributeStatement element.
        Returns:
        the attributes of the SAML Assertion
        Throws:
        javax.xml.xpath.XPathExpressionException
        ValidationError
      • getResponseStatus

        public SamlResponseStatus getResponseStatus()
        Returns the ResponseStatus object
        Returns:
      • getStatus

        public static SamlResponseStatus getStatus​(org.w3c.dom.Document dom)
                                            throws ValidationError
        Get Status from a Response
        Parameters:
        dom - The Response as XML
        Returns:
        SamlResponseStatus
        Throws:
        java.lang.IllegalArgumentException - if the response not contain status or if Unexpected XPath error
        ValidationError
      • checkOneCondition

        public java.lang.Boolean checkOneCondition()
                                            throws javax.xml.xpath.XPathExpressionException
        Checks that the samlp:Response/saml:Assertion/saml:Conditions element exists and is unique.
        Returns:
        true if the Conditions element exists and is unique
        Throws:
        javax.xml.xpath.XPathExpressionException
      • checkOneAuthnStatement

        public java.lang.Boolean checkOneAuthnStatement()
                                                 throws javax.xml.xpath.XPathExpressionException
        Checks that the samlp:Response/saml:Assertion/saml:AuthnStatement element exists and is unique.
        Returns:
        true if the AuthnStatement element exists and is unique
        Throws:
        javax.xml.xpath.XPathExpressionException
      • getAudiences

        public java.util.List<java.lang.String> getAudiences()
                                                      throws javax.xml.xpath.XPathExpressionException
        Gets the audiences.
        Returns:
        the audiences of the response
        Throws:
        javax.xml.xpath.XPathExpressionException
      • getResponseIssuer

        public java.lang.String getResponseIssuer()
                                           throws javax.xml.xpath.XPathExpressionException,
                                                  ValidationError
        Gets the Response Issuer.
        Returns:
        the Response Issuer, or null if not specified
        Throws:
        javax.xml.xpath.XPathExpressionException
        ValidationError - if multiple Response issuers were found
        See Also:
        getAssertionIssuer(), getIssuers()
      • getAssertionIssuer

        public java.lang.String getAssertionIssuer()
                                            throws javax.xml.xpath.XPathExpressionException,
                                                   ValidationError
        Gets the Assertion Issuer.
        Returns:
        the Assertion Issuer
        Throws:
        javax.xml.xpath.XPathExpressionException
        ValidationError - if no Assertion Issuer could be found, or if multiple Assertion issuers were found
        See Also:
        getResponseIssuer(), getIssuers()
      • getIssuers

        @Deprecated
        public java.util.List<java.lang.String> getIssuers()
                                                    throws javax.xml.xpath.XPathExpressionException,
                                                           ValidationError
        Deprecated.
        use getResponseIssuer() and/or getAssertionIssuer(); the contract of this method is quite controversial
        Gets the Issuers (from Response and Assertion). If the same issuer appears both in the Response and in the Assertion (as it should), the returned list will contain it just once. Hence, the returned list should always return one element and in particular:
        • it will never contain zero elements (it means an Assertion Issuer could not be found, hence a ValidationError will be thrown instead)
        • if it contains more than one element, it means that the response is invalid and one of the returned issuers won't pass the check performed by isValid(String) (which requires both issuers to be equal to the Identity Provider entity id)

        Warning: as a consequence of the above, if this response status code is not a successful one, this method will throw a ValidationError because it won't find any Assertion Issuer. In this case, if you need to retrieve the Response Issuer any way, you must use getResponseIssuer() instead.

        Returns:
        the issuers of the assertion/response
        Throws:
        javax.xml.xpath.XPathExpressionException
        ValidationError - if multiple Response Issuers or multiple Assertion Issuers were found, or if no Assertion Issuer could be found
        See Also:
        getResponseIssuer(), getAssertionIssuer()
      • getSessionNotOnOrAfter

        public org.joda.time.DateTime getSessionNotOnOrAfter()
                                                      throws javax.xml.xpath.XPathExpressionException
        Gets the SessionNotOnOrAfter from the AuthnStatement. Could be used to set the local session expiration
        Returns:
        the SessionNotOnOrAfter value
        Throws:
        javax.xml.xpath.XPathExpressionException
      • getSessionIndex

        public java.lang.String getSessionIndex()
                                         throws javax.xml.xpath.XPathExpressionException
        Gets the SessionIndex from the AuthnStatement. Could be used to be stored in the local session in order to be used in a future Logout Request that the SP could send to the SP, to set what specific session must be deleted
        Returns:
        the SessionIndex value
        Throws:
        javax.xml.xpath.XPathExpressionException
      • getId

        public java.lang.String getId()
        Returns:
        the ID of the Response
      • getAssertionId

        public java.lang.String getAssertionId()
                                        throws javax.xml.xpath.XPathExpressionException
        Returns:
        the ID of the assertion in the Response
        Throws:
        javax.xml.xpath.XPathExpressionException
      • getAssertionNotOnOrAfter

        public java.util.List<org.joda.time.Instant> getAssertionNotOnOrAfter()
                                                                       throws javax.xml.xpath.XPathExpressionException
        Returns:
        a list of NotOnOrAfter values from SubjectConfirmationData nodes in this Response
        Throws:
        javax.xml.xpath.XPathExpressionException
      • validateNumAssertions

        public java.lang.Boolean validateNumAssertions()
                                                throws java.lang.IllegalArgumentException
        Verifies that the document only contains a single Assertion (encrypted or not).
        Returns:
        true if the document passes.
        Throws:
        java.lang.IllegalArgumentException
      • processSignedElements

        public java.util.ArrayList<java.lang.String> processSignedElements()
                                                                    throws javax.xml.xpath.XPathExpressionException,
                                                                           ValidationError
        Verifies the signature nodes: - Checks that are Response or Assertion - Check that IDs and reference URI are unique and consistent.
        Returns:
        array Signed element tags
        Throws:
        javax.xml.xpath.XPathExpressionException
        ValidationError
      • validateSignedElements

        public boolean validateSignedElements​(java.util.ArrayList<java.lang.String> signedElements)
                                       throws javax.xml.xpath.XPathExpressionException,
                                              ValidationError
        Verifies that the document has the expected signed nodes.
        Parameters:
        signedElements - the elements to be validated
        Returns:
        true if is valid
        Throws:
        javax.xml.xpath.XPathExpressionException
        ValidationError
      • validateTimestamps

        public boolean validateTimestamps()
                                   throws ValidationError
        Verifies that the document is still valid according Conditions Element.
        Returns:
        true if still valid
        Throws:
        ValidationError
      • setDestinationUrl

        public void setDestinationUrl​(java.lang.String url)
        Aux method to set the destination url
        Parameters:
        url - the url to set as currentUrl
      • getError

        public java.lang.String getError()
        After execute a validation process, if fails this method returns the cause
        Returns:
        the cause of the validation error as a string
      • getValidationException

        public java.lang.Exception getValidationException()
        After execute a validation process, if fails this method returns the Exception object
        Returns:
        the cause of the validation error
      • setValidationException

        protected void setValidationException​(java.lang.Exception validationException)
        Sets the validation exception that this SamlResponse should return when a validation error occurs.
        Parameters:
        validationException - the validation exception to set
      • queryAssertion

        protected org.w3c.dom.NodeList queryAssertion​(java.lang.String assertionXpath)
                                               throws javax.xml.xpath.XPathExpressionException
        Extracts a node from the DOMDocument (Assertion).
        Parameters:
        assertionXpath - Xpath Expression
        Returns:
        the queried node
        Throws:
        javax.xml.xpath.XPathExpressionException
      • query

        protected org.w3c.dom.NodeList query​(java.lang.String nameQuery,
                                             org.w3c.dom.Node context)
                                      throws javax.xml.xpath.XPathExpressionException
        Extracts nodes that match the query from the DOMDocument (Response Message)
        Parameters:
        nameQuery - Xpath Expression
        context - The context node
        Returns:
        DOMNodeList The queried nodes
        Throws:
        javax.xml.xpath.XPathExpressionException
      • decryptAssertion

        private org.w3c.dom.Document decryptAssertion​(org.w3c.dom.Document dom)
                                               throws javax.xml.xpath.XPathExpressionException,
                                                      javax.xml.parsers.ParserConfigurationException,
                                                      org.xml.sax.SAXException,
                                                      java.io.IOException,
                                                      SettingsException,
                                                      ValidationError
        Decrypt assertion.
        Parameters:
        dom - Encrypted assertion
        Returns:
        Decrypted Assertion.
        Throws:
        javax.xml.xpath.XPathExpressionException
        java.io.IOException
        org.xml.sax.SAXException
        javax.xml.parsers.ParserConfigurationException
        SettingsException
        ValidationError
      • getSAMLResponseXml

        public java.lang.String getSAMLResponseXml()
        Returns:
        the SAMLResponse XML, If the Assertion of the SAMLResponse was encrypted, returns the XML with the assertion decrypted
      • getSAMLResponseDocument

        protected org.w3c.dom.Document getSAMLResponseDocument()
        Returns:
        the SAMLResponse Document, If the Assertion of the SAMLResponse was encrypted, returns the Document with the assertion decrypted
      • validateAudiences

        protected void validateAudiences()
                                  throws javax.xml.xpath.XPathExpressionException,
                                         ValidationError
        Validates the audiences.
        Throws:
        javax.xml.xpath.XPathExpressionException
        ValidationError
      • validateDestination

        protected void validateDestination​(org.w3c.dom.Element element)
                                    throws ValidationError
        Validate the destination.
        Parameters:
        element - element with the destination attribute
        Throws:
        ValidationError
      • validateRecipient

        protected SubjectConfirmationIssue validateRecipient​(org.w3c.dom.Node recipient,
                                                             int index)
        Validate a subject confirmation recipient.
        Parameters:
        recipient - recipient node
        index - index of the subject confirmation node
        Returns:
        a subject confirmation issue or null
      • validateSpNameQualifier

        protected void validateSpNameQualifier​(java.lang.String spNameQualifier)
                                        throws ValidationError
        Validates a SPNameQualifier.
        Parameters:
        spNameQualifier - the SPNameQualifier
        Throws:
        ValidationError
      • getResponseIssueInstant

        public java.util.Calendar getResponseIssueInstant()
                                                   throws ValidationError
        Returns the issue instant of this message.
        Returns:
        a new Calendar instance carrying the issue instant of this message
        Throws:
        ValidationError - if the found IssueInstant attribute is not in the expected UTC form of ISO-8601 format