如何使用 opensaml 验证 (azure) saml xml 响应?

How to validate (azure) saml xml response with opensaml?

我有来自我的 IDP 的 XML 格式的响应,我想使用 opensaml2 来验证它。怎么做到的?

根据 OpenSAML2 官方文档 (doc1 & doc2),您可以尝试使用以下代码通过 OpenSAML 验证 saml xml 响应。

// Initialize the library
DefaultBootstrap.bootstrap(); 

// Get parser pool manager
BasicParserPool ppMgr = new BasicParserPool();
ppMgr.setNamespaceAware(true);

// Get org.w3c.dom.Document Object from response
HttpURLConnection req = (HttpURLConnection) new URL("<saml-xml-url>").openConnection();
// Add some necessary headers for the request
// req.addRequestProperty("...", "...");
// ...
InputStream in = req.getInputStream();
Document inCommonMDDoc = ppMgr.parse(in);

// Get the DOMSource from org.w3c.dom.Document Object
DOMSource domSource=new DOMSource(document);  

//Add an extension schema via the code SAMLSchemaBuilder.addExtensionSchema(String schema) if necessary
Schema schema = SAMLSchemaBuilder.getSAML11Schema();

// Get a Validator instance.
Validator validator = schema.newValidator();
try {
    validator.validate(domSource);
    System.out.println("Result : Valid!");
} catch(Exception e) {
    System.out.println("Result : Invalid!");
}