Package com.onelogin.saml2.authn
Class SamlResponse
- java.lang.Object
-
- com.onelogin.saml2.authn.SamlResponse
-
public class SamlResponse extends java.lang.ObjectSamlResponse 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.StringcurrentUrlURL of the current host + current viewprivate org.w3c.dom.DocumentdecryptedDocumentA DOMDocument object loaded from the SAML Response (Decrypted).private java.lang.BooleanencryptedMark if the response contains an encrypted assertion.private static org.slf4j.LoggerLOGGERPrivate property to construct a logger for this class.private java.util.Map<java.lang.String,java.lang.String>nameIdDataNameID Dataprivate SamlResponseStatusresponseStatusThe respone status code and messagesprivate org.w3c.dom.DocumentsamlResponseDocumentA DOMDocument object loaded from the SAML Response.private java.lang.StringsamlResponseStringThe decoded, unprocessed XML response provided to the constructor.private Saml2SettingssettingsSettings data.private java.lang.ExceptionvalidationExceptionAfter 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.BooleancheckOneAuthnStatement()Checks that the samlp:Response/saml:Assertion/saml:AuthnStatement element exists and is unique.java.lang.BooleancheckOneCondition()Checks that the samlp:Response/saml:Assertion/saml:Conditions element exists and is unique.voidcheckStatus()Checks the Statusprivate org.w3c.dom.DocumentdecryptAssertion(org.w3c.dom.Document dom)Decrypt assertion.java.lang.StringgetAssertionId()java.lang.StringgetAssertionIssuer()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.StringgetError()After execute a validation process, if fails this method returns the causejava.lang.StringgetId()java.util.List<java.lang.String>getIssuers()Deprecated.usegetResponseIssuer()and/orgetAssertionIssuer(); the contract of this method is quite controversialjava.lang.StringgetNameId()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.StringgetNameIdFormat()Gets the NameID Format provided from the SAML Response String.java.lang.StringgetNameIdNameQualifier()Gets the NameID NameQualifier provided from the SAML Response String.java.lang.StringgetNameIdSPNameQualifier()Gets the NameID SP NameQualifier provided from the SAML Response String.java.util.CalendargetResponseIssueInstant()Returns the issue instant of this message.java.lang.StringgetResponseIssuer()Gets the Response Issuer.SamlResponseStatusgetResponseStatus()Returns the ResponseStatus objectprotected org.w3c.dom.DocumentgetSAMLResponseDocument()java.lang.StringgetSAMLResponseXml()java.lang.StringgetSessionIndex()Gets the SessionIndex from the AuthnStatement.org.joda.time.DateTimegetSessionNotOnOrAfter()Gets the SessionNotOnOrAfter from the AuthnStatement.static SamlResponseStatusgetStatus(org.w3c.dom.Document dom)Get Status from a Responsejava.lang.ExceptiongetValidationException()After execute a validation process, if fails this method returns the Exception objectbooleanisValid()Determines if the SAML Response is valid using the certificate.booleanisValid(java.lang.String requestId)Determines if the SAML Response is valid using the certificate.voidloadXmlFromBase64(java.lang.String responseStr)Load a XML base64encoded SAMLResponsejava.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.NodeListquery(java.lang.String nameQuery, org.w3c.dom.Node context)Extracts nodes that match the query from the DOMDocument (Response Message)protected org.w3c.dom.NodeListqueryAssertion(java.lang.String assertionXpath)Extracts a node from the DOMDocument (Assertion).voidsetDestinationUrl(java.lang.String url)Aux method to set the destination urlprotected voidsetValidationException(java.lang.Exception validationException)Sets the validation exception that thisSamlResponseshould return when a validation error occurs.protected voidvalidateAudiences()Validates the audiences.protected voidvalidateDestination(org.w3c.dom.Element element)Validate the destination.java.lang.BooleanvalidateNumAssertions()Verifies that the document only contains a single Assertion (encrypted or not).protected SubjectConfirmationIssuevalidateRecipient(org.w3c.dom.Node recipient, int index)Validate a subject confirmation recipient.booleanvalidateSignedElements(java.util.ArrayList<java.lang.String> signedElements)Verifies that the document has the expected signed nodes.protected voidvalidateSpNameQualifier(java.lang.String spNameQualifier)Validates a SPNameQualifier.private voidvalidateSubjectConfirmation(java.lang.String responseInResponseTo)Check SubjectConfirmation, at least one SubjectConfirmation must be validbooleanvalidateTimestamps()Verifies that the document is still valid according Conditions Element.
-
-
-
Field Detail
-
LOGGER
private static final org.slf4j.Logger LOGGER
Private property to construct a logger for this class.
-
settings
private final Saml2Settings settings
Settings data.
-
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 datacurrentUrl- URL of the current host + current viewsamlResponse- A string containting the base64 encoded response from the IdP- Throws:
ValidationErrorSettingsExceptionjava.io.IOExceptionorg.xml.sax.SAXExceptionjavax.xml.parsers.ParserConfigurationExceptionjavax.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 datarequest- the HttpRequest object to be processed (Contains GET and POST parameters, request URL, ...).- Throws:
ValidationErrorSettingsExceptionjava.io.IOExceptionorg.xml.sax.SAXExceptionjavax.xml.parsers.ParserConfigurationExceptionjavax.xml.xpath.XPathExpressionExceptionjava.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, ValidationErrorLoad a XML base64encoded SAMLResponse- Parameters:
responseStr- Saml2Settings object. Setting data- Throws:
javax.xml.parsers.ParserConfigurationExceptionSettingsExceptionjava.io.IOExceptionorg.xml.sax.SAXExceptionjavax.xml.xpath.XPathExpressionExceptionValidationError
-
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, ValidationErrorCheck SubjectConfirmation, at least one SubjectConfirmation must be valid- Parameters:
responseInResponseTo- The InResponseTo value of the SAML Response- Throws:
javax.xml.xpath.XPathExpressionExceptionValidationError
-
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.ExceptionGets 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.ExceptionGets 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.ExceptionGets 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.ExceptionGets 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.ExceptionGets 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, ValidationErrorGets the Attributes from the AttributeStatement element.- Returns:
- the attributes of the SAML Assertion
- Throws:
javax.xml.xpath.XPathExpressionExceptionValidationError
-
getResponseStatus
public SamlResponseStatus getResponseStatus()
Returns the ResponseStatus object- Returns:
-
checkStatus
public void checkStatus() throws ValidationErrorChecks the Status- Throws:
ValidationError- If status is not success
-
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 errorValidationError
-
checkOneCondition
public java.lang.Boolean checkOneCondition() throws javax.xml.xpath.XPathExpressionExceptionChecks 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.XPathExpressionExceptionChecks 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.XPathExpressionExceptionGets the audiences.- Returns:
- the audiences of the response
- Throws:
javax.xml.xpath.XPathExpressionException
-
getResponseIssuer
public java.lang.String getResponseIssuer() throws javax.xml.xpath.XPathExpressionException, ValidationErrorGets the Response Issuer.- Returns:
- the Response Issuer, or
nullif not specified - Throws:
javax.xml.xpath.XPathExpressionExceptionValidationError- if multiple Response issuers were found- See Also:
getAssertionIssuer(),getIssuers()
-
getAssertionIssuer
public java.lang.String getAssertionIssuer() throws javax.xml.xpath.XPathExpressionException, ValidationErrorGets the Assertion Issuer.- Returns:
- the Assertion Issuer
- Throws:
javax.xml.xpath.XPathExpressionExceptionValidationError- 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, ValidationErrorDeprecated.usegetResponseIssuer()and/orgetAssertionIssuer(); the contract of this method is quite controversialGets 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
ValidationErrorwill 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
ValidationErrorbecause it won't find any Assertion Issuer. In this case, if you need to retrieve the Response Issuer any way, you must usegetResponseIssuer()instead.- Returns:
- the issuers of the assertion/response
- Throws:
javax.xml.xpath.XPathExpressionExceptionValidationError- if multiple Response Issuers or multiple Assertion Issuers were found, or if no Assertion Issuer could be found- See Also:
getResponseIssuer(),getAssertionIssuer()
- it will never contain zero elements (it means an Assertion Issuer could
not be found, hence a
-
getSessionNotOnOrAfter
public org.joda.time.DateTime getSessionNotOnOrAfter() throws javax.xml.xpath.XPathExpressionExceptionGets 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.XPathExpressionExceptionGets 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.IllegalArgumentExceptionVerifies 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, ValidationErrorVerifies 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.XPathExpressionExceptionValidationError
-
validateSignedElements
public boolean validateSignedElements(java.util.ArrayList<java.lang.String> signedElements) throws javax.xml.xpath.XPathExpressionException, ValidationErrorVerifies that the document has the expected signed nodes.- Parameters:
signedElements- the elements to be validated- Returns:
- true if is valid
- Throws:
javax.xml.xpath.XPathExpressionExceptionValidationError
-
validateTimestamps
public boolean validateTimestamps() throws ValidationErrorVerifies 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 thisSamlResponseshould 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.XPathExpressionExceptionExtracts 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.XPathExpressionExceptionExtracts nodes that match the query from the DOMDocument (Response Message)- Parameters:
nameQuery- Xpath Expressioncontext- 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, ValidationErrorDecrypt assertion.- Parameters:
dom- Encrypted assertion- Returns:
- Decrypted Assertion.
- Throws:
javax.xml.xpath.XPathExpressionExceptionjava.io.IOExceptionorg.xml.sax.SAXExceptionjavax.xml.parsers.ParserConfigurationExceptionSettingsExceptionValidationError
-
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, ValidationErrorValidates the audiences.- Throws:
javax.xml.xpath.XPathExpressionExceptionValidationError
-
validateDestination
protected void validateDestination(org.w3c.dom.Element element) throws ValidationErrorValidate 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 nodeindex- index of the subject confirmation node- Returns:
- a subject confirmation issue or null
-
validateSpNameQualifier
protected void validateSpNameQualifier(java.lang.String spNameQualifier) throws ValidationErrorValidates a SPNameQualifier.- Parameters:
spNameQualifier- the SPNameQualifier- Throws:
ValidationError
-
getResponseIssueInstant
public java.util.Calendar getResponseIssueInstant() throws ValidationErrorReturns the issue instant of this message.- Returns:
- a new
Calendarinstance 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
-
-