如何验证SAML断言签名

时间:2018-03-13 18:26:36

标签: saml x509certificate signature xml-signature opensaml

如何验证SAML断言签名?

    for (Assertion assertion : samlResponse.getAssertions()) {
        try {
            if (assertion.getSignature() != null) {
                Optional<X509Certificate> x509Certificate = assertion.getSignature().getKeyInfo().getX509Datas()
                        .stream()
                        .findFirst()
                        .map(x509Data -> x509Data.getX509Certificates()
                                .stream()
                                .findFirst()
                                .orElse(null)
                        );
                if (x509Certificate.isPresent()) {
                    BasicX509Credential credential = new BasicX509Credential();
                    credential.setEntityCertificate(KeyInfoHelper.getCertificate(x509Certificate.get()));
                    // what pub key credential to use here?
                    SignatureValidator validator = new SignatureValidator(credential);
                    validator.validate(assertion.getSignature());
                }
            }
        } catch (ValidationException | CertificateException e) {
            throw new SAMLException(e.getMessage(), e);
        }
    }

基本上放在new SignatureValidator(credential)

中的内容

据我了解,提供KeyInfo的SAML断言和X809证书至少应验证(SAML: Why is the certificate within the Signature?

我还有来自idps元数据的x509证书,如果断言中或信任链中没有x509证书,我猜应该使用该证书(?)

基本上,断言中的x509证书和idp元数据中的证书似乎都不起作用。我在这里错过了什么?

1 个答案:

答案 0 :(得分:1)

原来我做的一切都正确。

打印opensaml对象xml时,不应使用以下代码:

public static String xmlObjectToString(XMLObject xmlObject) {
    try {
        Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(xmlObject);
        StringWriter sw = new StringWriter();
        Element authDOM = marshaller.marshall(xmlObject);
        toString(sw, authDOM);
        return sw.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}


private static void toString(StringWriter rspWrt, Element authDOM) throws ParserConfigurationException, TransformerException {
    DOMSource domSource = new DOMSource(authDOM);
    StreamResult result = new StreamResult(rspWrt);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.transform(domSource, result);
} 

上面的代码更改了原始对象的一些内部状态

取而代之的是

org.opensaml.xml.util.XMLHelper.prettyPrintXML(message.getDOM())