...
- Add the OpenSAML library to the build path of the project. You can download the open SAML JAR file from here.
- A sample <AuthnRequest> message can be found here.
According to SAML 2.0 specifications, the message must contain an element. Create the Issuer element first.
Code Block String issuerId = "saml2.sso.demo"; IssuerBuilder issuerBuilder = new IssuerBuilder(); Issuer issuer = issuerBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "Issuer", "samlp"); issuer.setValue(issuerId);
Create the
<AuthnRequest>
next.Code Block // the issuerUrl is the url of the service provider who generates the message String issuerUrl = "http://localhost:8080/saml2.sso.demo/consumer"; DateTime issueInstant = new DateTime(); AuthnRequestBuilder authnRequestBuilder = new AuthnRequestBuilder(); AuthnRequest authnRequest = authnRequestBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:protocol", "AuthnRequest", "samlp"); authnRequest.setForceAuthn(false); authnRequest.setIsPassive(false); authnRequest.setIssueInstant(issueInstant); authnRequest.setProtocolBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"); authnRequest.setAssertionConsumerServiceURL(issuerUrl); authnRequest.setIssuer(issuer); authnRequest.setID(aRandomId); authnRequest.setVersion(SAMLVersion.VERSION_20);
The message may contain many other elements like , etc. those elements can be created and added to the message in the same way.
Next encode the message using Base64 encoding.
Code Block Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(authnRequest); Element authDOM = marshaller.marshall(authnRequest); StringWriter rspWrt = new StringWriter(); XMLHelper.writeNode(authDOM, rspWrt); String requestMessage = rspWrt.toString(); Deflater deflater = new Deflater(Deflater.DEFLATED, true); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater); deflaterOutputStream.write(requestMessage.getBytes()); deflaterOutputStream.close(); /* Encoding the compressed message */ String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES); String encodedAuthnRequest = URLEncoder.encode(encodedRequestMessage,"UTF-8").trim();
Construct the redirection URL.
Panel redirectionUrl = identitypProviderUrl+ "?SAMLRequest=" + encodedRequestMessage;
Redirect the user to the identity provider.
Panel response.sendRedirect(redirectionUrl);
...