Create 'HTTP Redirect Binding' SAML Reques

2019-08-12 07:01发布

I am trying to implement the same algorithm in Java for SAML HTTP Redirect Binding which is described here: How do I correctly prepare an 'HTTP Redirect Binding' SAML Request using C#

The algorithm is rather simple:

  1. Build a SAML string
  2. Compress this string
  3. Base64 encode the string
  4. UrlEncode the string.

This should be the equivalent Java algorithm:

    public String encodeRedirectFormat( String samlXML ) throws IOException{
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(os);
            deflaterOutputStream.write( samlXML.getBytes( "UTF-8" ) );
            deflaterOutputStream.close();
            os.close();
            String base64 = Base64.encodeBase64String( os.toByteArray() );
            return URLEncoder.encode( base64, "UTF-8" );
    }

I try to encode the simplest assertion:

<saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion"/>

This is the output:

eJyzKU7MzTGyciwuTi0qyczPU6jIzckrtgKL2iqVFuVZ5ScWZxZb5SXmphZblSRbBTv6%2BlgZ6RlYJcK0KOnbAQCHfRi3

And then try to decode with an online tool like

https://rnd.feide.no/simplesaml/module.php/saml2debug/debug.php

the output is invalid. Can someone spot the error? Maybe the Java Deflater works differently?

1条回答
贪生不怕死
2楼-- · 2019-08-12 07:19

You need to instruct specifically the Deflater for noWrap option. This is the working code:

public String encodeRedirectFormat( String samlXML ) throws IOException{
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Deflater deflater = new Deflater( Deflater.DEFAULT_COMPRESSION, true );
        DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(os, deflater);
        deflaterOutputStream.write( samlXML.getBytes( "UTF-8" ) );
        deflaterOutputStream.close();
        os.close();
        String base64 = Base64.encodeBase64String( os.toByteArray() );
        return URLEncoder.encode( base64, "UTF-8" );
}
查看更多
登录 后发表回答