To parse a SAML request and extract important attributes such as the ID, Issuer, NameID, and AssertionConsumerServiceURL, you can use the following JavaScript function. This function uses the built-in DOMParser for XML parsing and XPath for attribute extraction [1][2]:
```javascript
function parseSAMLRequest(samlRequest) {
try {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(samlRequest, 'application/xml');
const ID = xmlDoc.documentElement.getAttribute('ID');
const Issuer = xmlDoc.querySelector('saml\\:Issuer').textContent; // Handle namespaces
const NameID = xmlDoc.querySelector('saml\\:NameID').textContent; // Handle namespaces
const AssertionConsumerServiceURL = xmlDoc.documentElement.getAttribute('AssertionConsumerServiceURL');
return {
ID,
Issuer,
NameID,
AssertionConsumerServiceURL,
};
} catch (error) {
throw new Error('Error parsing SAML request: ' + error.message);
}
}
// Example SAML request XML
const samlRequestXML = `
<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
ID="12345"
AssertionConsumerServiceURL="https://example.com/acs"
IssueInstant="2023-10-30T10:00:00Z">
<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">https://issuer.example.com</saml:Issuer>
<samlp:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">user123</samlp:NameID>
</samlp:AuthnRequest>
`;
// Usage
const samlAttributes = parseSAMLRequest(samlRequestXML);
console.log('SAML Request Attributes:');
console.log('ID:', samlAttributes.ID);
console.log('Issuer:', samlAttributes.Issuer);
console.log('NameID:', samlAttributes.NameID);
console.log('AssertionConsumerServiceURL:', samlAttributes.AssertionConsumerServiceURL);
```
This function should accurately parse the SAML request and extract the specified attributes. Make sure to replace the example SAML request XML with your own XML input when using the function.