How to verify a SAML signature for HTTP-redirect binding

前端 未结 6 1482
生来不讨喜
生来不讨喜 2020-12-30 09:40

I\'m receiving a SAML request via HTTP-redirect binding the content of the SAML request look like this

{\"SigAlg\"=>\"http://www.w3.org/2000/09/xmldsi

6条回答
  •  灰色年华
    2020-12-30 10:24

    For those still stuck, here is the complete method

    public static void verifySignature(boolean isResponse, String samlQueryString, String relayStateString, String sigAlgString, String signature, X509Certificate cert) throws Exception {
        String type = isResponse ? "SAMLResponse" : "SAMLRequest";
    
        String query = type + "=" + URLEncoder.encode(samlQueryString, "UTF-8");
            query += relayStateString == null ? "" : "&RelayState=" + URLEncoder.encode(relayStateString, "UTF-8");
            query += "&SigAlg=" + URLEncoder.encode(sigAlgString, "UTF-8");
    
        String javaSigAlgName = null;
    
        if(sigAlgString.equals("http://www.w3.org/2000/09/xmldsig#rsa-sha1")) {
            javaSigAlgName = "SHA1withRSA";
        } else if(sigAlgString.equals("http://www.w3.org/2000/09/xmldsig#rsa-sha256")) {
            javaSigAlgName = "SHA256withRSA";
        } else {
            throw new Exception("signature: " + sigAlgString + " not supported by SP/IDP");
        }
    
        byte[] signatureBytes = Base64.getDecoder().decode(signature);
    
        Signature sig = Signature.getInstance(javaSigAlgName);
        sig.initVerify(cert.getPublicKey());
        sig.update(query.getBytes());
    
        Boolean valid = sig.verify(signatureBytes);
        System.out.println("is valid: " + valid);
    }
    

提交回复
热议问题