创建' HTTP重定向绑定'使用Java的SAML请求

时间:2014-10-21 10:53:43

标签: java base64 saml http-redirect deflate

我正在尝试在Java中为SAML HTTP重定向绑定实现相同的算法,如下所述:How do I correctly prepare an 'HTTP Redirect Binding' SAML Request using C#

算法相当简单:

  1. 构建SAML字符串
  2. 压缩此字符串
  3. Base64编码字符串
  4. UrlEncode the string。
  5. 这应该是等效的Java算法:

        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" );
        }
    

    我尝试编码最简单的断言:

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

    这是输出:

    eJyzKU7MzTGyciwuTi0qyczPU6jIzckrtgKL2iqVFuVZ5ScWZxZb5SXmphZblSRbBTv6%2BlgZ6RlYJcK0KOnbAQCHfRi3
    

    然后尝试使用

    等在线工具进行解码

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

    输出无效。有人可以发现错误吗?也许Java Deflater的工作方式不同?

1 个答案:

答案 0 :(得分:1)

您需要专门指导Deflater noWrap选项。这是工作代码:

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" );
}