fork(17) download
  1. // This file contains the core of the sso - receiving saml request and sending saml responses.
  2. // And maintaining authentication information.
  3.  
  4. import java.io.ByteArrayInputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.PrintWriter;
  8. import java.io.StringWriter;
  9. import java.net.URL;
  10. import java.security.KeyStore;
  11. import java.security.PrivateKey;
  12. import java.security.PublicKey;
  13. import java.security.cert.X509Certificate;
  14. import java.security.interfaces.DSAPrivateKey;
  15. import java.security.interfaces.DSAPublicKey;
  16. import java.util.ArrayList;
  17. import java.util.Collections;
  18. import java.util.List;
  19. import java.util.Scanner;
  20. import java.util.zip.Inflater;
  21.  
  22. import javax.servlet.ServletException;
  23. import javax.servlet.http.HttpServlet;
  24. import javax.servlet.http.HttpServletRequest;
  25. import javax.servlet.http.HttpServletResponse;
  26. import javax.servlet.http.HttpSession;
  27. import javax.xml.crypto.dsig.CanonicalizationMethod;
  28. import javax.xml.crypto.dsig.DigestMethod;
  29. import javax.xml.crypto.dsig.Reference;
  30. import javax.xml.crypto.dsig.SignatureMethod;
  31. import javax.xml.crypto.dsig.SignedInfo;
  32. import javax.xml.crypto.dsig.Transform;
  33. import javax.xml.crypto.dsig.XMLSignature;
  34. import javax.xml.crypto.dsig.XMLSignatureFactory;
  35. import javax.xml.crypto.dsig.dom.DOMSignContext;
  36. import javax.xml.crypto.dsig.keyinfo.KeyInfo;
  37. import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
  38. import javax.xml.crypto.dsig.keyinfo.KeyValue;
  39. import javax.xml.crypto.dsig.keyinfo.X509Data;
  40. import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
  41. import javax.xml.crypto.dsig.spec.TransformParameterSpec;
  42. import javax.xml.parsers.DocumentBuilder;
  43. import javax.xml.parsers.DocumentBuilderFactory;
  44.  
  45. import org.apache.commons.codec.binary.Base64; // To decode from Base64 Strings
  46. import org.apache.xml.security.c14n.Canonicalizer;
  47. import org.jdom.input.DOMBuilder;
  48. import org.jdom.input.SAXBuilder;
  49. import org.jdom.output.XMLOutputter;
  50. import org.joda.time.DateTime;
  51. import org.opensaml.Configuration;
  52. import org.opensaml.DefaultBootstrap;
  53. import org.opensaml.common.impl.SecureRandomIdentifierGenerator;
  54. import org.opensaml.saml2.core.AuthnRequest;
  55. import org.opensaml.saml2.core.Response;
  56. import org.opensaml.xml.XMLObject;
  57. import org.opensaml.xml.io.Unmarshaller;
  58. import org.opensaml.xml.io.UnmarshallerFactory;
  59. import org.opensaml.xml.parse.BasicParserPool;
  60. import org.opensaml.xml.util.XMLHelper;
  61. import org.w3c.dom.Document;
  62. import org.w3c.dom.Element;
  63. // To decode %2f url components
  64. //import org.opensaml.xml.signature.X509Certificate;
  65.  
  66. public class SamlHandler extends HttpServlet {
  67.  
  68. // set DEBUG to true to enable debug specific actions and pauses.
  69. private static boolean DEBUG = true;
  70.  
  71. // Session specific user data
  72. private String sessionId;
  73. private String email;
  74. private String domain;
  75.  
  76. // Request attributes
  77. private String req_Id;
  78. private String req_issuer;
  79. private String req_issueInstant;
  80.  
  81. // Common Info
  82. private String acs;
  83. private String relayState;
  84. private String relayStateb64; // To check if relay state is b64 encoded.
  85. private boolean relayStateIsb64 = false;
  86.  
  87. // Response attributes
  88. private String res_Id;
  89. private String res_issuer;
  90. private String res_issueInstant;
  91. private String res_timeout;
  92. private String res_assertionId;
  93. private String res_nameId;
  94. private String res_notonorafter;
  95. private String res_notbefore;
  96. private String res_authnInstant; // Can be equal to issueInstance
  97.  
  98. private String strResponseXML;
  99. private String strFinalResponse; // The final signed SAML Response.
  100.  
  101. private Response samlResponseObject; // The SAML Response object
  102.  
  103. /**
  104. * Check the current session state and return true if the current session is
  105. * valid.
  106. *
  107. * @param request
  108. * - The HttpServletRequest object corresponding to the GET /
  109. * POST request.
  110. * @return true if the session is valid.
  111. *
  112. */
  113. public boolean checkSession(HttpServletRequest request) {
  114.  
  115. try {
  116.  
  117. HttpSession session = request.getSession(false);
  118.  
  119. if (session.getAttribute("loggedIn").equals("yes")) {
  120. System.out.println("Session is valid.");
  121. // If the session is valid retrieve the user credentials
  122. // Every user will be uniquely identified by the email and
  123. // domain.
  124. email = (String) session.getAttribute("email");
  125. domain = (String) session.getAttribute("domain");
  126. sessionId = (String) session.getId();
  127. return true;
  128.  
  129. }
  130.  
  131. else {
  132. System.out.println("User is not logged in.");
  133. return false;
  134.  
  135. }
  136.  
  137. } catch (Exception e) {
  138. // If the loggedIn attribute is not set.
  139. System.out.println("User session invalid / User is not logged in.");
  140. return false;
  141. }
  142.  
  143. }
  144.  
  145. public void doPost(HttpServletRequest request, HttpServletResponse response)
  146. throws ServletException, IOException {
  147.  
  148. handleSamlRequest(request, response);
  149.  
  150. }
  151.  
  152. public void doGet(HttpServletRequest request, HttpServletResponse response)
  153. throws ServletException, IOException {
  154.  
  155. handleSamlRequest(request, response);
  156.  
  157. }
  158.  
  159. /**
  160. * handleSamlRequest method accepts SP's GET / POST request, parses the
  161. * SAMLRequest data and responds to the same by issuing a signed
  162. * SAMLResponse data
  163. *
  164. * @param request
  165. * - HttpServletRequest object
  166. * @param response
  167. * - HttpServletResponse object
  168. * @return void
  169. */
  170. public void handleSamlRequest(HttpServletRequest request,
  171. HttpServletResponse response) {
  172.  
  173. // Validates the current user session before parsing the SAMLRequest
  174. if (!checkSession(request)) {
  175. try {
  176. response.sendRedirect("/SignOut.action");
  177. } catch (Exception e) {
  178. System.out
  179. .println("Exception while trying to redirect to SignOut action.");
  180. e.printStackTrace();
  181. }
  182. return;
  183. }
  184.  
  185. // If the session is valid proceed further ...
  186.  
  187. // Parsing the RelayState
  188. // ----------------------
  189. try {
  190.  
  191. relayState = request.getParameter("RelayState");
  192.  
  193. System.out.println("\nThe received Relay State is : " + relayState);
  194.  
  195. // If RelayState is Base64 encoded, it will not contain the text
  196. // "http"
  197. // hence 'try' decoding it ...
  198. if (!relayState.contains("http") && relayState.length() > 1) {
  199.  
  200. relayStateb64 = relayState;
  201. relayStateIsb64 = true;
  202.  
  203. // Base64 decode it
  204. relayState = new String(Base64.decodeBase64(relayState
  205. .getBytes("UTF-8")), "UTF-8");
  206.  
  207. System.out
  208. .println("\nThe BASE64 Decoded Relay State Parameter is : "
  209. + relayStateb64);
  210.  
  211. }
  212.  
  213. } catch (Exception e) {
  214. System.out
  215. .println("\n\nException while trying to parse the RelayState value.");
  216. e.printStackTrace();
  217.  
  218. if (DEBUG) {
  219. try {
  220. System.in.read(); // Wait for Enter key to process further
  221. } catch (Exception e2) {
  222. System.out.println(e2.toString());
  223. }
  224. }
  225. }
  226.  
  227. // Parsing the SAMLRequest
  228. // -----------------------
  229. try {
  230.  
  231. String SAMLRequest = request.getParameter("SAMLRequest");
  232.  
  233. parseAuthnRequest(SAMLRequest, request);
  234.  
  235. } catch (Exception e) {
  236. System.out
  237. .println("Exception while trying to parse the SAMLRequest");
  238. }
  239.  
  240. try {
  241.  
  242. buildResponseXMLString();
  243. canonicalizeSamlResponse();
  244. generateSamlResponseObject();
  245. signSamlResponseObject2();
  246. encodeSamlResponse();
  247. postSamlResponse(response);
  248.  
  249. } catch (Exception e) {
  250. System.out
  251. .println("Exception while constructing / posting the SAML Response data ...");
  252. System.out.println("The error is : " + e.toString());
  253. e.printStackTrace();
  254. }
  255. }
  256.  
  257. public void parseAuthnRequest(String SAMLRequest, HttpServletRequest request) {
  258. try {
  259.  
  260. System.out.println("\n\nThe BASE64 Encoded SAML Request is : "
  261. + SAMLRequest);
  262.  
  263. // SAMLRequest = (new URI(SAMLRequest)).toString();
  264.  
  265. // System.out.println("\n\nThe URI Decoded SAML Request is s : " +
  266. // SAMLRequest);
  267.  
  268. // To decode from Base64
  269. byte[] decodedSAMLRequestBytes = Base64.decodeBase64(SAMLRequest
  270. .getBytes("UTF-8"));
  271.  
  272. SAMLRequest = new String(decodedSAMLRequestBytes, "UTF-8");
  273.  
  274. System.out
  275. .println("\n\nThe base 64 decoded SAML Request ( deflated ) is : "
  276. + SAMLRequest);
  277. // It will still be deflated ( compressed )
  278.  
  279. System.out.println("The Accept-Encoding header data is : "
  280. + request.getHeader("Accept-Encoding"));
  281.  
  282. if (request.getHeader("Accept-Encoding").contains("deflate")) {
  283.  
  284. try {
  285.  
  286. // try Inflating it
  287. Inflater inflater = new Inflater(true);
  288. inflater.setInput(decodedSAMLRequestBytes);
  289.  
  290. byte[] xmlMessageBytes = new byte[5000];
  291. int resultLength = inflater.inflate(xmlMessageBytes);
  292. inflater.end();
  293.  
  294. SAMLRequest = new String(xmlMessageBytes, 0, resultLength,
  295. "UTF-8");
  296.  
  297. System.out.println("\n\nThe deflated SAMLRequest is : "
  298. + SAMLRequest);
  299.  
  300. } catch (Exception e) {
  301. System.out
  302. .println("\n\nException during inflation attempt. Data might be already deflated.");
  303. e.printStackTrace();
  304. }
  305. }
  306.  
  307. // Parsing the XML
  308. SAMLRequest.getBytes("UTF-8"));
  309.  
  310. DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
  311. .newInstance();
  312.  
  313. documentBuilderFactory.setNamespaceAware(true);
  314.  
  315. DocumentBuilder docBuilder = documentBuilderFactory
  316. .newDocumentBuilder();
  317.  
  318. Document document = docBuilder.parse(is);
  319.  
  320. Element element = document.getDocumentElement();
  321.  
  322. // Code taken from OpenSAML documentation
  323. // Using OpenSAML library to Unmarshal
  324.  
  325. DefaultBootstrap.bootstrap(); // Loading default XML Configurations
  326.  
  327. UnmarshallerFactory unmarshallerFactory = Configuration
  328. .getUnmarshallerFactory();
  329.  
  330. Unmarshaller unmarshaller = unmarshallerFactory
  331. .getUnmarshaller(element);
  332.  
  333. XMLObject responseXmlObj = unmarshaller.unmarshall(element);
  334.  
  335. AuthnRequest samlRequestObject = (AuthnRequest) responseXmlObj;
  336.  
  337. SAMLRequest = samlRequestObject.toString();
  338.  
  339. System.out.println("\n\nThe received SAML Request is : "
  340. + SAMLRequest);
  341.  
  342. String acsUrl = samlRequestObject.getAssertionConsumerServiceURL();
  343.  
  344. String requestId = samlRequestObject.getID();
  345.  
  346. DateTime issueInstance = samlRequestObject.getIssueInstant();
  347.  
  348. String issuer = samlRequestObject.getIssuer().getValue()
  349. .toLowerCase().trim();
  350.  
  351. System.out.println("Parsed SAML Request is : ");
  352. System.out.println("\n\nacs : " + acsUrl);
  353. System.out.println("\nrequestId : " + requestId);
  354. System.out.println("\nissueInstance : " + issueInstance.toString());
  355. System.out.println("\nissuer : " + issuer);
  356.  
  357. acs = acsUrl;
  358. req_Id = requestId;
  359. req_issueInstant = issueInstance.toString();
  360. req_issuer = issuer;
  361.  
  362. } catch (Exception e) {
  363. System.out
  364. .println("Exception while processing GET Request from SP. ");
  365. System.out.println("The error is : " + e.toString());
  366. e.printStackTrace();
  367. }
  368. }
  369.  
  370. public void buildResponseXMLString() {
  371.  
  372. try {
  373.  
  374. // The certificate and template xml file for saml response is stored
  375. // in the saml-data folder
  376.  
  377. String strAssertionXMLTemplateFile = "/WEB-INF/classes/saml-data/saml.xml";
  378. String samlTemplateFileUrl = getServletContext().getResource(
  379. strAssertionXMLTemplateFile).toString();
  380. InputStream assertionTemplateFile = new URL(samlTemplateFileUrl)
  381. .openStream();
  382.  
  383. // templateXmlString contains the raw SAML Response templates with
  384. // field handle to be replaced with appropriate parameters
  385.  
  386. strResponseXML = new Scanner(assertionTemplateFile, "UTF-8")
  387. .useDelimiter("\\A").next().trim();
  388.  
  389. assertionTemplateFile.close();
  390.  
  391. System.out.println("\n\nThe assertion template is : \n"
  392. + strResponseXML);
  393.  
  394. // Id generation
  395. SecureRandomIdentifierGenerator generator = new
  396.  
  397. SecureRandomIdentifierGenerator();
  398.  
  399. res_Id = generator.generateIdentifier().trim();
  400. res_assertionId = generator.generateIdentifier().trim();
  401.  
  402. // Other important identifying parameters
  403. res_issuer = "https://r...content-available-to-author-only...p.com";
  404. res_nameId = getEmail().trim();
  405. String dateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss'+05:30'";
  406. res_issueInstant = new DateTime().toString(dateTimeFormat).trim();
  407. res_notbefore = new DateTime().toString(dateTimeFormat).trim();
  408. res_notonorafter = new DateTime().plusMinutes(5)
  409. .toString(dateTimeFormat).trim();
  410.  
  411. // Filling the parameters into the template...
  412. strResponseXML = strResponseXML.replaceAll("_ASSERTION_ID",
  413. res_assertionId);
  414. strResponseXML = strResponseXML.replaceAll("_REQUEST_ID", req_Id);
  415. strResponseXML = strResponseXML.replaceAll("_RESPONSE_ID", res_Id);
  416. strResponseXML = strResponseXML.replaceAll("_ISSUE_INSTANT",
  417. res_issueInstant);
  418. strResponseXML = strResponseXML.replaceAll("_ISSUER", res_issuer);
  419. strResponseXML = strResponseXML.replaceAll("_NAMEID", res_nameId);
  420. strResponseXML = strResponseXML.replaceAll("_NOTBEFORE",
  421. res_notbefore);
  422. strResponseXML = strResponseXML.replaceAll("_NOTONORAFTER",
  423. res_notonorafter);
  424. strResponseXML = strResponseXML.replaceAll("_ACS_URL", acs);
  425. strResponseXML = strResponseXML.replaceAll("_DOMAIN", domain);
  426.  
  427. // Replace the handles in strAssertionXML with appropriate
  428. // parameters
  429.  
  430. System.out.println("\n\nThe complete SAML Response is : \n"
  431. + strResponseXML);
  432.  
  433. } catch (Exception e) {
  434. System.out.println("Exception while filling SAML Response ...");
  435. System.out.println("The error is : " + e.toString());
  436. e.printStackTrace();
  437. }
  438.  
  439. }
  440.  
  441. public void generateSamlResponseObject() {
  442. try {
  443.  
  444. InputStream xmlResponseAsStream = new ByteArrayInputStream(
  445. strResponseXML.getBytes());
  446. // Load initial configurations
  447. DefaultBootstrap.bootstrap();
  448.  
  449. // Get parser pool manager
  450. BasicParserPool ppMgr = new BasicParserPool();
  451. ppMgr.setNamespaceAware(true);
  452.  
  453. Document parsedDocumentObject = ppMgr.parse(xmlResponseAsStream);
  454. Element parsedElementObject = parsedDocumentObject
  455. .getDocumentElement();
  456.  
  457. // Get apropriate unmarshaller
  458. UnmarshallerFactory unmarshallerFactory = Configuration
  459. .getUnmarshallerFactory();
  460. Unmarshaller unmarshaller = unmarshallerFactory
  461. .getUnmarshaller(parsedElementObject);
  462.  
  463. // Unmarshall using the document root element, an EntitiesDescriptor
  464. // in this case
  465. Response responseObject = (Response) unmarshaller
  466. .unmarshall(parsedElementObject);
  467. // responseObject.
  468. System.out.println("\nThe unmarshalled saml response is : ");
  469.  
  470. // System.out.println(XMLHelper.nodeToString(parsedElementObject));
  471. System.out.println(XMLHelper.nodeToString(parsedElementObject));
  472.  
  473. xmlResponseAsStream.close();
  474.  
  475. samlResponseObject = responseObject;
  476.  
  477. System.out.println("\nThe SAML signature is : "
  478. + samlResponseObject.getSignature());
  479.  
  480. } catch (Exception e) {
  481. System.out
  482. .println("Exception while trying to parse samlResponseObject :"
  483. + e.toString());
  484. e.printStackTrace();
  485.  
  486. }
  487.  
  488. }
  489.  
  490. public void canonicalizeSamlResponse() {
  491.  
  492. try {
  493.  
  494. // Initializing the Apache XML security library
  495. org.apache.xml.security.Init.init();
  496.  
  497. // Canonicalizing the XML String.
  498. Canonicalizer canonicalizer = Canonicalizer
  499. .getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
  500.  
  501. byte canonicalizedResponseXML[] = canonicalizer
  502. .canonicalize(strResponseXML.getBytes("UTF-8"));
  503.  
  504. strFinalResponse = new String(canonicalizedResponseXML);
  505.  
  506. System.out.println("\n\nThe Response after canonicalization is : "
  507. + strResponseXML);
  508.  
  509. } catch (Exception e) {
  510. System.out
  511. .println("Exception while canonicalizing the SAML Response.");
  512. e.printStackTrace();
  513. }
  514.  
  515. }
  516.  
  517. public void signSamlResponseObject2() {
  518.  
  519. try {
  520.  
  521. String keyStoreFileName = "/WEB-INF/classes/saml-data/keystore.jks";
  522. InputStream fis = getServletContext().getResource(keyStoreFileName)
  523. .openStream();
  524. KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  525.  
  526. ks.load(fis, "abc123456*".toCharArray());
  527. fis.close();
  528.  
  529. // Get Private Key Entry From keystore
  530.  
  531. KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks
  532. .getEntry("zohosso", new KeyStore.PasswordProtection(
  533. "abc123456*".toCharArray()));
  534.  
  535. PrivateKey privKey = pkEntry.getPrivateKey();
  536.  
  537. PublicKey pubKey = ks.getCertificate("zohosso").getPublicKey();
  538.  
  539. .getCertificate("zohosso");
  540.  
  541. /*
  542. * // Getting x509 Certificate from the keystore directly.
  543. *
  544. * KeyStore.TrustedCertificateEntry certEntry =
  545. * (KeyStore.TrustedCertificateEntry) ks .getEntry("zohosso", new
  546. * KeyStore.PasswordProtection( "abc123456*".toCharArray()));
  547. *
  548. * X509Certificate cert = (X509Certificate)
  549. * certEntry.getTrustedCertificate();
  550. */
  551.  
  552. // Create a DOM XMLSignatureFactory that will be used to generate
  553. // the
  554. // enveloped signature.
  555.  
  556. // String providerName =
  557. // System.getProperty("jsr105Provider",JSR_105_PROVIDER);
  558. XMLSignatureFactory sigFactory = XMLSignatureFactory
  559. .getInstance("DOM");
  560.  
  561. // Create a Reference to the enveloped document (we are
  562. // signing the whole document, so a URI of "" signifies that) and
  563. // also specify the SHA1 digest algorithm and the ENVELOPED
  564. // Transform.
  565.  
  566. List envelopedTransform = Collections.singletonList(sigFactory
  567. .newTransform(Transform.ENVELOPED,
  568. (TransformParameterSpec) null));
  569.  
  570. Reference ref = sigFactory.newReference("",
  571. sigFactory.newDigestMethod(DigestMethod.SHA1, null),
  572. envelopedTransform, null, null);
  573.  
  574. SignatureMethod signatureMethod = sigFactory.newSignatureMethod(
  575. SignatureMethod.DSA_SHA1, null);
  576.  
  577. CanonicalizationMethod canonicalizationMethod = sigFactory
  578. .newCanonicalizationMethod(
  579. CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
  580. (C14NMethodParameterSpec) null);
  581.  
  582. // Create the SignedInfo
  583. SignedInfo signedInfo = sigFactory.newSignedInfo(
  584. canonicalizationMethod, signatureMethod,
  585. Collections.singletonList(ref));
  586.  
  587. // Create a KeyValue containing the DSA PublicKey
  588. KeyInfoFactory keyInfoFactory = sigFactory.getKeyInfoFactory();
  589. KeyValue keyValuePair = keyInfoFactory.newKeyValue(pubKey);
  590.  
  591.  
  592. // Creating the x509 certificate data from Certificate object ( cert )
  593.  
  594. List x509 = new ArrayList();
  595.  
  596. x509.add(cert);
  597.  
  598. X509Data x509Data = keyInfoFactory.newX509Data(x509);
  599.  
  600. // Create a KeyInfo and add the KeyValue to it
  601. // keyInfoItems.add(Collections.singletonList(keyValuePair));
  602.  
  603. // Adding the certificate data and the key value pair to the keyInfo
  604.  
  605.  
  606. List keyInfoItems = new ArrayList();
  607.  
  608. keyInfoItems.add(x509Data);
  609. keyInfoItems.add(keyValuePair);
  610.  
  611. KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoItems);
  612.  
  613.  
  614. // Building the org.jdom.Document object from the samlResponse
  615. // string
  616. // ------------------------------------------------------------------
  617. SAXBuilder builder = new SAXBuilder();
  618. org.jdom.Document doc = builder.build(new ByteArrayInputStream(
  619. strResponseXML.getBytes()));
  620. // ------------------------------------------------------------------
  621.  
  622. // Convert the rootElement extracted from the doc to w3cElement
  623. // ------------------------------------------------------------------
  624.  
  625. org.jdom.Element docRootElement = doc.getRootElement();
  626. doc = docRootElement.getDocument();
  627.  
  628. XMLOutputter xmlOutputter = new XMLOutputter();
  629. StringWriter elemStrWriter = new StringWriter();
  630. xmlOutputter.output(doc, elemStrWriter);
  631. byte[] xmlBytes = elemStrWriter.toString().getBytes();
  632. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  633. dbf.setNamespaceAware(true);
  634. org.w3c.dom.Element w3cElement = dbf.newDocumentBuilder()
  635. .parse(new ByteArrayInputStream(xmlBytes))
  636. .getDocumentElement();
  637.  
  638. // --------------------------------------------------------------------
  639.  
  640. // Create a DOMSignContext and specify the DSA PrivateKey and
  641. // location of the resulting XMLSignature's parent element
  642.  
  643. DOMSignContext dsc = new DOMSignContext(privKey, w3cElement);
  644.  
  645. // compute the correct location to insert the signature xml
  646. // (location is important because the SAML xsd's enforce sequence on
  647. // signed
  648. // info.)
  649.  
  650. org.w3c.dom.Node xmlSigInsertionPoint = null;
  651.  
  652. String JSR_105_PROVIDER = "org.jcp.xml.dsig.internal.dom.XMLDSigRI";
  653. String SAML_PROTOCOL_NS_URI_V20 = "urn:oasis:names:tc:SAML:2.0:protocol";
  654.  
  655. org.w3c.dom.NodeList nodeList = w3cElement.getElementsByTagNameNS(
  656. SAML_PROTOCOL_NS_URI_V20, "Extensions");
  657. if (nodeList.getLength() != 0) {
  658. xmlSigInsertionPoint = nodeList.item(nodeList.getLength() - 1);
  659. } else {
  660. nodeList = w3cElement.getElementsByTagNameNS(
  661. SAML_PROTOCOL_NS_URI_V20, "Status");
  662. xmlSigInsertionPoint = nodeList.item(nodeList.getLength() - 1);
  663. }
  664. dsc.setNextSibling(xmlSigInsertionPoint);
  665.  
  666. // Marshal, generate (and sign) the enveloped signature
  667. XMLSignature signature = sigFactory.newXMLSignature(signedInfo,
  668. keyInfo);
  669. signature.sign(dsc);
  670.  
  671. // Create the root dom element from the w3cElement using DOMBuilder
  672. DOMBuilder domBuilder = new DOMBuilder();
  673. org.jdom.Element signedElement = domBuilder.build(w3cElement);
  674.  
  675. doc.setRootElement((org.jdom.Element) signedElement.detach());
  676. xmlOutputter = new XMLOutputter();
  677. strFinalResponse = xmlOutputter.outputString(doc);
  678.  
  679. System.out.println("The signed SAML Response is : "
  680. + strFinalResponse);
  681.  
  682. } catch (Exception e) {
  683. System.out
  684. .println("Exception while attempting to sign the SAML Response.");
  685. e.printStackTrace();
  686. }
  687.  
  688. }
  689.  
  690. /*
  691. * public void signSamlResponseObject() {
  692. *
  693. * try {
  694. *
  695. * String keyStoreFileName = "/WEB-INF/classes/saml-data/keystore.jks";
  696. * InputStream fis = getServletContext().getResource(keyStoreFileName)
  697. * .openStream();
  698. *
  699. * // Get Default Instance of KeyStore KeyStore ks =
  700. * KeyStore.getInstance(KeyStore.getDefaultType());
  701. *
  702. * ks.load(fis, "abc123456*".toCharArray()); fis.close();
  703. *
  704. * // Get Private Key Entry From keystore KeyStore.PrivateKeyEntry pkEntry =
  705. * (KeyStore.PrivateKeyEntry) ks .getEntry("zohosso", new
  706. * KeyStore.PasswordProtection( "abc123456*".toCharArray()));
  707. *
  708. * PrivateKey pk = pkEntry.getPrivateKey();
  709. *
  710. * X509Certificate certificate = (X509Certificate) pkEntry
  711. * .getCertificate();
  712. *
  713. * BasicX509Credential credential = new BasicX509Credential();
  714. * credential.setEntityCertificate(certificate);
  715. *
  716. * credential.setPrivateKey(pk);
  717. *
  718. * System.out.println("\n\nPrivate Key : " + pk.toString());
  719. *
  720. * DefaultBootstrap.bootstrap(); Signature signature = null;
  721. *
  722. * signature = (Signature) Configuration.getBuilderFactory()
  723. * .getBuilder(Signature.DEFAULT_ELEMENT_NAME)
  724. * .buildObject(Signature.DEFAULT_ELEMENT_NAME);
  725. *
  726. * signature.setSigningCredential(credential);
  727. *
  728. * // This is also the default if a null SecurityConfiguration is //
  729. * SecurityConfiguration secConfig = Configuration
  730. * .getGlobalSecurityConfiguration(); // If null this would result in the //
  731. * default KeyInfoGenerator being used String keyInfoGeneratorProfile =
  732. * "XMLSignature";
  733. *
  734. * SecurityHelper.prepareSignatureParams(signature, credential, secConfig,
  735. * null);
  736. *
  737. * samlResponseObject.setSignature(signature);
  738. *
  739. * Configuration.getMarshallerFactory() .getMarshaller(samlResponseObject)
  740. * .marshall(samlResponseObject);
  741. *
  742. * Signer.signObject(signature);
  743. *
  744. * ResponseMarshaller marshaller = new ResponseMarshaller(); Element
  745. * finalResponseElement = marshaller .marshall(samlResponseObject);
  746. * strFinalResponse = XMLHelper.nodeToString(finalResponseElement) .trim();
  747. *
  748. * System.out.println("\n\n\nThe final Response as string is : \n\n");
  749. * System.out.println(strFinalResponse);
  750. *
  751. * File f = new File("finalSamlResponse.xml");
  752. * System.out.println("Writing to absolute path : " + f.getAbsolutePath());
  753. * FileWriter fw = new FileWriter(f); BufferedWriter finalXmlFile = new
  754. * BufferedWriter(fw); finalXmlFile.write(strFinalResponse);
  755. * finalXmlFile.close();
  756. *
  757. * } catch (Exception e) { System.out
  758. * .println("\nException while trying to digitally sign the SAMLResponse Object"
  759. * ); System.out.println("The error is : " + e.toString());
  760. * e.printStackTrace();
  761. *
  762. * } }
  763. */
  764. public void encodeSamlResponse() {
  765. try {
  766.  
  767. System.out.println("\n\nAttempting to b64 encode the response ...");
  768.  
  769. // strFinalResponse =
  770. // strFinalResponse.replaceAll("<?xml version=\"1.0\", encoding=\"UTF-8\"?>",
  771. // "");
  772.  
  773. strFinalResponse = new String(Base64.encodeBase64(strFinalResponse
  774. .getBytes("UTF-8")), "UTF-8");
  775.  
  776. // strFinalResponse.replaceAll("(\\r|\\n|\\r\\n)+", "")
  777.  
  778. strFinalResponse = strFinalResponse.trim();
  779.  
  780. StringBuilder formattedResponse = new StringBuilder();
  781.  
  782. // Splitting the final response text to 60 char lines
  783. for (int i = 0; i < strFinalResponse.length(); i++) {
  784. if (((i % 60) == 0) && i != 0)
  785. formattedResponse.append("\n");
  786.  
  787. formattedResponse.append(strFinalResponse.charAt(i));
  788. }
  789.  
  790. strFinalResponse = formattedResponse.toString();
  791.  
  792. System.out.println("\nThe base64 encoded saml response is : ");
  793. System.out.println(strFinalResponse);
  794.  
  795. } catch (Exception e) {
  796. System.out
  797. .println("Exception while trying to access session data .");
  798. System.out.println("The error is : " + e.toString());
  799. e.printStackTrace();
  800.  
  801. }
  802.  
  803. }
  804.  
  805. public void postSamlResponse(HttpServletResponse responseObject)
  806. throws IOException {
  807.  
  808. String relState = relayStateIsb64 ? relayStateb64 : relayState;
  809. String html = "<HTML>"
  810. + "<BODY onload='document.forms[\"saml-form\"].submit()'>"
  811. + "<FORM name='saml-form' action='" + acs + "' method='POST'>"
  812. + "<INPUT type='hidden' name='RelayState' value='"
  813. + relState.trim() + "' />"
  814. + "<INPUT type='hidden' name='SAMLResponse' value='"
  815. + strFinalResponse + "' />"
  816. + "<INPUT type='hidden' value='submit' />";
  817.  
  818. PrintWriter out = responseObject.getWriter();
  819. out.write(html);
  820. out.close();
  821.  
  822. }
  823.  
  824. public String getSessionId() {
  825. return sessionId;
  826. }
  827.  
  828. public void setSessionId(String sessionId) {
  829. this.sessionId = sessionId;
  830. }
  831.  
  832. public String getEmail() {
  833. return email;
  834. }
  835.  
  836. public void setEmail(String email) {
  837. this.email = email;
  838. }
  839.  
  840. public String getDomain() {
  841. return domain;
  842. }
  843.  
  844. public void setDomain(String domain) {
  845. this.domain = domain;
  846. }
  847.  
  848. public String getReq_Id() {
  849. return req_Id;
  850. }
  851.  
  852. public void setReq_Id(String req_Id) {
  853. this.req_Id = req_Id;
  854. }
  855.  
  856. public String getReq_issuer() {
  857. return req_issuer;
  858. }
  859.  
  860. public void setReq_issuer(String req_issuer) {
  861. this.req_issuer = req_issuer;
  862. }
  863.  
  864. public String getReq_issueInstant() {
  865. return req_issueInstant;
  866. }
  867.  
  868. public void setReq_issueInstant(String req_issueInstant) {
  869. this.req_issueInstant = req_issueInstant;
  870. }
  871.  
  872. public String getAcs() {
  873. return acs;
  874. }
  875.  
  876. public void setAcs(String acs) {
  877. this.acs = acs;
  878. }
  879.  
  880. public String getRes_Id() {
  881. return res_Id;
  882. }
  883.  
  884. public void setRes_Id(String res_Id) {
  885. this.res_Id = res_Id;
  886. }
  887.  
  888. public String getRes_issuer() {
  889. return res_issuer;
  890. }
  891.  
  892. public void setRes_issuer(String res_issuer) {
  893. this.res_issuer = res_issuer;
  894. }
  895.  
  896. public String getRes_issueInstant() {
  897. return res_issueInstant;
  898. }
  899.  
  900. public void setRes_issueInstant(String res_issueInstant) {
  901. this.res_issueInstant = res_issueInstant;
  902. }
  903.  
  904. public String getRes_timeout() {
  905. return res_timeout;
  906. }
  907.  
  908. public void setRes_timeout(String res_timeout) {
  909. this.res_timeout = res_timeout;
  910. }
  911.  
  912. public String getRes_assertionId() {
  913. return res_assertionId;
  914. }
  915.  
  916. public void setRes_assertionId(String res_assertionId) {
  917. this.res_assertionId = res_assertionId;
  918. }
  919.  
  920. public String getRes_nameId() {
  921. return res_nameId;
  922. }
  923.  
  924. public void setRes_nameId(String res_nameId) {
  925. this.res_nameId = res_nameId;
  926. }
  927.  
  928. public String getRes_notonorafter() {
  929. return res_notonorafter;
  930. }
  931.  
  932. public void setRes_notonorafter(String res_notonorafter) {
  933. this.res_notonorafter = res_notonorafter;
  934. }
  935.  
  936. public String getRes_notbefore() {
  937. return res_notbefore;
  938. }
  939.  
  940. public void setRes_notbefore(String res_notbefore) {
  941. this.res_notbefore = res_notbefore;
  942. }
  943.  
  944. public String getRes_authnInstant() {
  945. return res_authnInstant;
  946. }
  947.  
  948. public void setRes_authnInstant(String res_authnInstant) {
  949. this.res_authnInstant = res_authnInstant;
  950. }
  951.  
  952. public String getStrAssertionXML() {
  953. return strResponseXML;
  954. }
  955.  
  956. public void setStrAssertionXML(String strAssertionXML) {
  957. this.strResponseXML = strAssertionXML;
  958. }
  959.  
  960. public String getStrResponseXML() {
  961. return strResponseXML;
  962. }
  963.  
  964. public void setStrResponseXML(String strResponseXML) {
  965. this.strResponseXML = strResponseXML;
  966. }
  967.  
  968. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Main.java:66: error: class SamlHandler is public, should be declared in a file named SamlHandler.java
public class SamlHandler extends HttpServlet {
       ^
Main.java:22: error: package javax.servlet does not exist
import javax.servlet.ServletException;
                    ^
Main.java:23: error: package javax.servlet.http does not exist
import javax.servlet.http.HttpServlet;
                         ^
Main.java:24: error: package javax.servlet.http does not exist
import javax.servlet.http.HttpServletRequest;
                         ^
Main.java:25: error: package javax.servlet.http does not exist
import javax.servlet.http.HttpServletResponse;
                         ^
Main.java:26: error: package javax.servlet.http does not exist
import javax.servlet.http.HttpSession;
                         ^
Main.java:45: error: package org.apache.commons.codec.binary does not exist
import org.apache.commons.codec.binary.Base64; // To decode from Base64 Strings
                                      ^
Main.java:46: error: package org.apache.xml.security.c14n does not exist
import org.apache.xml.security.c14n.Canonicalizer;
                                   ^
Main.java:47: error: package org.jdom.input does not exist
import org.jdom.input.DOMBuilder;
                     ^
Main.java:48: error: package org.jdom.input does not exist
import org.jdom.input.SAXBuilder;
                     ^
Main.java:49: error: package org.jdom.output does not exist
import org.jdom.output.XMLOutputter;
                      ^
Main.java:50: error: package org.joda.time does not exist
import org.joda.time.DateTime;
                    ^
Main.java:51: error: package org.opensaml does not exist
import org.opensaml.Configuration;
                   ^
Main.java:52: error: package org.opensaml does not exist
import org.opensaml.DefaultBootstrap;
                   ^
Main.java:53: error: package org.opensaml.common.impl does not exist
import org.opensaml.common.impl.SecureRandomIdentifierGenerator;
                               ^
Main.java:54: error: package org.opensaml.saml2.core does not exist
import org.opensaml.saml2.core.AuthnRequest;
                              ^
Main.java:55: error: package org.opensaml.saml2.core does not exist
import org.opensaml.saml2.core.Response;
                              ^
Main.java:56: error: package org.opensaml.xml does not exist
import org.opensaml.xml.XMLObject;
                       ^
Main.java:57: error: package org.opensaml.xml.io does not exist
import org.opensaml.xml.io.Unmarshaller;
                          ^
Main.java:58: error: package org.opensaml.xml.io does not exist
import org.opensaml.xml.io.UnmarshallerFactory;
                          ^
Main.java:59: error: package org.opensaml.xml.parse does not exist
import org.opensaml.xml.parse.BasicParserPool;
                             ^
Main.java:60: error: package org.opensaml.xml.util does not exist
import org.opensaml.xml.util.XMLHelper;
                            ^
Main.java:66: error: cannot find symbol
public class SamlHandler extends HttpServlet {
                                 ^
  symbol: class HttpServlet
Main.java:101: error: cannot find symbol
	private Response samlResponseObject; // The SAML Response object
	        ^
  symbol:   class Response
  location: class SamlHandler
Main.java:113: error: cannot find symbol
	public boolean checkSession(HttpServletRequest request) {
	                            ^
  symbol:   class HttpServletRequest
  location: class SamlHandler
Main.java:145: error: cannot find symbol
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	                   ^
  symbol:   class HttpServletRequest
  location: class SamlHandler
Main.java:145: error: cannot find symbol
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	                                               ^
  symbol:   class HttpServletResponse
  location: class SamlHandler
Main.java:146: error: cannot find symbol
			throws ServletException, IOException {
			       ^
  symbol:   class ServletException
  location: class SamlHandler
Main.java:152: error: cannot find symbol
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	                  ^
  symbol:   class HttpServletRequest
  location: class SamlHandler
Main.java:152: error: cannot find symbol
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	                                              ^
  symbol:   class HttpServletResponse
  location: class SamlHandler
Main.java:153: error: cannot find symbol
			throws ServletException, IOException {
			       ^
  symbol:   class ServletException
  location: class SamlHandler
Main.java:170: error: cannot find symbol
	public void handleSamlRequest(HttpServletRequest request,
	                              ^
  symbol:   class HttpServletRequest
  location: class SamlHandler
Main.java:171: error: cannot find symbol
			HttpServletResponse response) {
			^
  symbol:   class HttpServletResponse
  location: class SamlHandler
Main.java:257: error: cannot find symbol
	public void parseAuthnRequest(String SAMLRequest, HttpServletRequest request) {
	                                                  ^
  symbol:   class HttpServletRequest
  location: class SamlHandler
Main.java:807: error: cannot find symbol
	public void postSamlResponse(HttpServletResponse responseObject)
	                             ^
  symbol:   class HttpServletResponse
  location: class SamlHandler
Main.java:117: error: cannot find symbol
			HttpSession session = request.getSession(false);
			^
  symbol:   class HttpSession
  location: class SamlHandler
Main.java:204: error: cannot find symbol
				relayState = new String(Base64.decodeBase64(relayState
				                        ^
  symbol:   variable Base64
  location: class SamlHandler
Main.java:269: error: cannot find symbol
			byte[] decodedSAMLRequestBytes = Base64.decodeBase64(SAMLRequest
			                                 ^
  symbol:   variable Base64
  location: class SamlHandler
Main.java:326: error: cannot find symbol
			DefaultBootstrap.bootstrap(); // Loading default XML Configurations
			^
  symbol:   variable DefaultBootstrap
  location: class SamlHandler
Main.java:328: error: cannot find symbol
			UnmarshallerFactory unmarshallerFactory = Configuration
			^
  symbol:   class UnmarshallerFactory
  location: class SamlHandler
Main.java:328: error: cannot find symbol
			UnmarshallerFactory unmarshallerFactory = Configuration
			                                          ^
  symbol:   variable Configuration
  location: class SamlHandler
Main.java:331: error: cannot find symbol
			Unmarshaller unmarshaller = unmarshallerFactory
			^
  symbol:   class Unmarshaller
  location: class SamlHandler
Main.java:334: error: cannot find symbol
			XMLObject responseXmlObj = unmarshaller.unmarshall(element);
			^
  symbol:   class XMLObject
  location: class SamlHandler
Main.java:336: error: cannot find symbol
			AuthnRequest samlRequestObject = (AuthnRequest) responseXmlObj;
			^
  symbol:   class AuthnRequest
  location: class SamlHandler
Main.java:336: error: cannot find symbol
			AuthnRequest samlRequestObject = (AuthnRequest) responseXmlObj;
			                                  ^
  symbol:   class AuthnRequest
  location: class SamlHandler
Main.java:347: error: cannot find symbol
			DateTime issueInstance = samlRequestObject.getIssueInstant();
			^
  symbol:   class DateTime
  location: class SamlHandler
Main.java:379: error: cannot find symbol
			String samlTemplateFileUrl = getServletContext().getResource(
			                             ^
  symbol:   method getServletContext()
  location: class SamlHandler
Main.java:396: error: cannot find symbol
			SecureRandomIdentifierGenerator generator = new
			^
  symbol:   class SecureRandomIdentifierGenerator
  location: class SamlHandler
Main.java:398: error: cannot find symbol
			SecureRandomIdentifierGenerator();
			^
  symbol:   class SecureRandomIdentifierGenerator
  location: class SamlHandler
Main.java:407: error: cannot find symbol
			res_issueInstant = new DateTime().toString(dateTimeFormat).trim();
			                       ^
  symbol:   class DateTime
  location: class SamlHandler
Main.java:408: error: cannot find symbol
			res_notbefore = new DateTime().toString(dateTimeFormat).trim();
			                    ^
  symbol:   class DateTime
  location: class SamlHandler
Main.java:409: error: cannot find symbol
			res_notonorafter = new DateTime().plusMinutes(5)
			                       ^
  symbol:   class DateTime
  location: class SamlHandler
Main.java:448: error: cannot find symbol
			DefaultBootstrap.bootstrap();
			^
  symbol:   variable DefaultBootstrap
  location: class SamlHandler
Main.java:451: error: cannot find symbol
			BasicParserPool ppMgr = new BasicParserPool();
			^
  symbol:   class BasicParserPool
  location: class SamlHandler
Main.java:451: error: cannot find symbol
			BasicParserPool ppMgr = new BasicParserPool();
			                            ^
  symbol:   class BasicParserPool
  location: class SamlHandler
Main.java:459: error: cannot find symbol
			UnmarshallerFactory unmarshallerFactory = Configuration
			^
  symbol:   class UnmarshallerFactory
  location: class SamlHandler
Main.java:459: error: cannot find symbol
			UnmarshallerFactory unmarshallerFactory = Configuration
			                                          ^
  symbol:   variable Configuration
  location: class SamlHandler
Main.java:461: error: cannot find symbol
			Unmarshaller unmarshaller = unmarshallerFactory
			^
  symbol:   class Unmarshaller
  location: class SamlHandler
Main.java:466: error: cannot find symbol
			Response responseObject = (Response) unmarshaller
			^
  symbol:   class Response
  location: class SamlHandler
Main.java:466: error: cannot find symbol
			Response responseObject = (Response) unmarshaller
			                           ^
  symbol:   class Response
  location: class SamlHandler
Main.java:472: error: cannot find symbol
			System.out.println(XMLHelper.nodeToString(parsedElementObject));
			                   ^
  symbol:   variable XMLHelper
  location: class SamlHandler
Main.java:496: error: package org.apache.xml.security does not exist
			org.apache.xml.security.Init.init();
			                       ^
Main.java:499: error: cannot find symbol
			Canonicalizer canonicalizer = Canonicalizer
			^
  symbol:   class Canonicalizer
  location: class SamlHandler
Main.java:500: error: cannot find symbol
					.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
					             ^
  symbol:   variable Canonicalizer
  location: class SamlHandler
Main.java:499: error: cannot find symbol
			Canonicalizer canonicalizer = Canonicalizer
			                              ^
  symbol:   variable Canonicalizer
  location: class SamlHandler
Main.java:523: error: cannot find symbol
			InputStream fis = getServletContext().getResource(keyStoreFileName)
			                  ^
  symbol:   method getServletContext()
  location: class SamlHandler
Main.java:619: error: cannot find symbol
			SAXBuilder builder = new SAXBuilder();
			^
  symbol:   class SAXBuilder
  location: class SamlHandler
Main.java:619: error: cannot find symbol
			SAXBuilder builder = new SAXBuilder();
			                         ^
  symbol:   class SAXBuilder
  location: class SamlHandler
Main.java:620: error: package org.jdom does not exist
			org.jdom.Document doc = builder.build(new ByteArrayInputStream(
			        ^
Main.java:627: error: package org.jdom does not exist
			org.jdom.Element docRootElement = doc.getRootElement();
			        ^
Main.java:630: error: cannot find symbol
			XMLOutputter xmlOutputter = new XMLOutputter();
			^
  symbol:   class XMLOutputter
  location: class SamlHandler
Main.java:630: error: cannot find symbol
			XMLOutputter xmlOutputter = new XMLOutputter();
			                                ^
  symbol:   class XMLOutputter
  location: class SamlHandler
Main.java:674: error: cannot find symbol
			DOMBuilder domBuilder = new DOMBuilder();
			^
  symbol:   class DOMBuilder
  location: class SamlHandler
Main.java:674: error: cannot find symbol
			DOMBuilder domBuilder = new DOMBuilder();
			                            ^
  symbol:   class DOMBuilder
  location: class SamlHandler
Main.java:675: error: package org.jdom does not exist
			org.jdom.Element signedElement = domBuilder.build(w3cElement);
			        ^
Main.java:677: error: package org.jdom does not exist
			doc.setRootElement((org.jdom.Element) signedElement.detach());
			                            ^
Main.java:678: error: cannot find symbol
			xmlOutputter = new XMLOutputter();
			                   ^
  symbol:   class XMLOutputter
  location: class SamlHandler
Main.java:775: error: cannot find symbol
			strFinalResponse = new String(Base64.encodeBase64(strFinalResponse
			                              ^
  symbol:   variable Base64
  location: class SamlHandler
Note: Main.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
78 errors
stdout
Standard output is empty