├── .gitignore ├── LICENSE ├── Procfile ├── README.md ├── app.json ├── pom.xml ├── src └── main │ ├── java │ └── com │ │ └── salesforce │ │ ├── Main.java │ │ ├── saml │ │ ├── Identity.java │ │ ├── InvalidSignatureException.java │ │ ├── SAMLException.java │ │ ├── SAMLNamespaceResolver.java │ │ ├── SAMLServlet.java │ │ ├── SAMLValidator.java │ │ └── TLSFilter.java │ │ └── util │ │ ├── Bag.java │ │ └── XSDDateTime.java │ └── webapp │ ├── WEB-INF │ └── web.xml │ ├── configure.jsp │ ├── css │ └── style.css │ ├── img │ └── logo.png │ └── index.jsp └── system.properties /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Package Files # 4 | *.jar 5 | *.war 6 | *.ear 7 | 8 | # IDE and filesystem # 9 | .idea 10 | .idea/* 11 | .DS_Store 12 | *.iml 13 | target 14 | target/* 15 | 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: java $JAVA_OPTS -cp target/classes:target/dependency/* com.salesforce.Main 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | heroku-identity-java 2 | ==================== 3 | 4 | A sample java app that integrates with Salesforce Identity. Run it! 5 | 6 | [![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy?template=https://github.com/salesforceidentity/heroku-identity-java) 7 | 8 | 9 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "heroku-identity-java", 3 | "description": "A java based sample for integrating Salesforce Identity and Heroku", 4 | "keywords": ["identity", "saml", "salesforce", "java"], 5 | "website": "https://www.salesforce.com/platform/identity", 6 | "repository": "https://github.com/salesforceidentity/heroku-identity-java", 7 | "logo": "https://www.salesforceidentity.info/img/launcher.png", 8 | "success_url": "/", 9 | "env": { 10 | "BUILDPACK_URL": "https://github.com/heroku/heroku-buildpack-java" 11 | } 12 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | com.example 5 | 1.0 6 | herokusamlsp 7 | herokusamlsp 8 | jar 9 | 10 | 11 | 1.8 12 | UTF-8 13 | 8.5.2 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | org.apache.tomcat.embed 22 | tomcat-embed-core 23 | 8.5.55 24 | 25 | 26 | org.apache.tomcat.embed 27 | tomcat-embed-logging-juli 28 | ${tomcat.version} 29 | 30 | 31 | org.apache.tomcat.embed 32 | tomcat-embed-jasper 33 | ${tomcat.version} 34 | 35 | 36 | org.apache.tomcat 37 | tomcat-jasper 38 | ${tomcat.version} 39 | 40 | 41 | org.apache.tomcat 42 | tomcat-jasper-el 43 | ${tomcat.version} 44 | 45 | 46 | org.apache.tomcat 47 | tomcat-jsp-api 48 | ${tomcat.version} 49 | 50 | 51 | 52 | 53 | org.json 54 | json 55 | 20140107 56 | 57 | 58 | 59 | commons-httpclient 60 | commons-httpclient 61 | 3.1 62 | 63 | 64 | 65 | 66 | commons-codec 67 | commons-codec 68 | 1.6 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | org.apache.maven.plugins 77 | maven-dependency-plugin 78 | 2.4 79 | 80 | 81 | copy-dependencies 82 | package 83 | copy-dependencies 84 | 85 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /src/main/java/com/salesforce/Main.java: -------------------------------------------------------------------------------- 1 | package com.salesforce; 2 | 3 | import java.io.File; 4 | 5 | import org.apache.catalina.WebResourceRoot; 6 | import org.apache.catalina.core.StandardContext; 7 | import org.apache.catalina.startup.Tomcat; 8 | import org.apache.catalina.webresources.DirResourceSet; 9 | import org.apache.catalina.webresources.StandardRoot; 10 | 11 | public class Main { 12 | 13 | public static void main(String[] args) throws Exception { 14 | 15 | String webappDirLocation = "src/main/webapp/"; 16 | Tomcat tomcat = new Tomcat(); 17 | 18 | //The port that we should run on can be set into an environment variable 19 | //Look for that variable and default to 8080 if it isn't there. 20 | String webPort = System.getenv("PORT"); 21 | if(webPort == null || webPort.isEmpty()) { 22 | webPort = "8080"; 23 | } 24 | 25 | tomcat.setPort(Integer.valueOf(webPort)); 26 | 27 | StandardContext ctx = (StandardContext) tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath()); 28 | System.out.println("configuring app with basedir: " + new File("./" + webappDirLocation).getAbsolutePath()); 29 | 30 | // Declare an alternative location for your "WEB-INF/classes" dir 31 | // Servlet 3.0 annotation will work 32 | File additionWebInfClasses = new File("target/classes"); 33 | WebResourceRoot resources = new StandardRoot(ctx); 34 | resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes", 35 | additionWebInfClasses.getAbsolutePath(), "/")); 36 | ctx.setResources(resources); 37 | 38 | tomcat.start(); 39 | tomcat.getServer().await(); 40 | } 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/salesforce/saml/Identity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012, Salesforce.com 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in the 12 | * documentation and/or other materials provided with the distribution. 13 | * * Neither the names salesforce, salesforce.com, nor the 14 | * names of its contributors may be used to endorse or promote products 15 | * derived from this software without specific prior written permission. 16 | * 17 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY 18 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 19 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 20 | * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY 21 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 22 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 23 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 24 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | package com.salesforce.saml; 30 | 31 | import com.salesforce.util.Bag; 32 | import org.apache.commons.codec.binary.Base64; 33 | import org.json.JSONArray; 34 | import org.json.JSONObject; 35 | 36 | import java.io.UnsupportedEncodingException; 37 | import java.util.Iterator; 38 | 39 | public class Identity { 40 | 41 | 42 | 43 | private String subject; 44 | private Bag attributes; 45 | 46 | public Identity(String identity, boolean encoded) throws UnsupportedEncodingException { 47 | 48 | this.attributes = new Bag(); 49 | if (encoded) { 50 | byte[] theBytes = Base64.decodeBase64(identity); 51 | String jsonString = new String(theBytes,"UTF-8"); 52 | JSONObject j = new JSONObject(jsonString); 53 | this.subject = j.getString("subject"); 54 | 55 | Iterator iterator = j.keySet().iterator(); 56 | while (iterator.hasNext()) { 57 | String key = (String) iterator.next(); 58 | if (!key.equals("subject")) { 59 | JSONArray ja = j.getJSONArray(key); 60 | for (int i = 0; i < ja.length(); i++) { 61 | this.attributes.put(key, ja.getString(i)); 62 | } 63 | } 64 | } 65 | } else { 66 | this.subject = identity; 67 | } 68 | } 69 | 70 | public String getSubject() { 71 | return subject; 72 | } 73 | 74 | public Bag getAttributes() { 75 | return attributes; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/salesforce/saml/InvalidSignatureException.java: -------------------------------------------------------------------------------- 1 | package com.salesforce.saml; 2 | 3 | public class InvalidSignatureException extends Exception{ 4 | public InvalidSignatureException() { 5 | super(); 6 | } 7 | 8 | public InvalidSignatureException(String s) { 9 | super(s); 10 | } 11 | 12 | public InvalidSignatureException(String s, Throwable throwable) { 13 | super(s, throwable); 14 | } 15 | 16 | public InvalidSignatureException(Throwable throwable) { 17 | super(throwable); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/salesforce/saml/SAMLException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2006, Chuck Mortimore - xmldap.org 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in the 12 | * documentation and/or other materials provided with the distribution. 13 | * * Neither the names xmldap, xmldap.org, xmldap.com nor the 14 | * names of its contributors may be used to endorse or promote products 15 | * derived from this software without specific prior written permission. 16 | * 17 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY 18 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 19 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 20 | * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY 21 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 22 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 23 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 24 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | package com.salesforce.saml; 30 | 31 | public class SAMLException extends Exception{ 32 | 33 | public SAMLException() { 34 | super(); 35 | } 36 | 37 | public SAMLException(String s) { 38 | super(s); 39 | } 40 | 41 | public SAMLException(String s, Throwable throwable) { 42 | super(s, throwable); 43 | } 44 | 45 | public SAMLException(Throwable throwable) { 46 | super(throwable); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/salesforce/saml/SAMLNamespaceResolver.java: -------------------------------------------------------------------------------- 1 | package com.salesforce.saml; 2 | 3 | import javax.xml.namespace.NamespaceContext; 4 | import java.util.Iterator; 5 | 6 | public class SAMLNamespaceResolver implements NamespaceContext { 7 | 8 | public String getNamespaceURI(String prefix) { 9 | if (prefix == null) { 10 | throw new IllegalArgumentException("No prefix provided!"); 11 | } else if (prefix.equals("samlp")) { 12 | return "urn:oasis:names:tc:SAML:2.0:protocol"; 13 | } else if (prefix.equals("saml")) { 14 | return "urn:oasis:names:tc:SAML:2.0:assertion"; 15 | } else if (prefix.equals("ds")) { 16 | return "http://www.w3.org/2000/09/xmldsig#"; 17 | } else if (prefix.equals("md")) { 18 | return "urn:oasis:names:tc:SAML:2.0:metadata"; 19 | } else return null; 20 | 21 | } 22 | 23 | public String getPrefix(String namespaceURI) { 24 | return null; 25 | } 26 | 27 | public Iterator getPrefixes(String namespaceURI) { 28 | return null; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/salesforce/saml/SAMLServlet.java: -------------------------------------------------------------------------------- 1 | package com.salesforce.saml; 2 | 3 | import com.salesforce.util.Bag; 4 | import com.salesforce.util.XSDDateTime; 5 | import org.apache.commons.codec.binary.Base64; 6 | import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; 7 | import org.apache.commons.httpclient.HttpClient; 8 | import org.apache.commons.httpclient.HttpException; 9 | import org.apache.commons.httpclient.HttpStatus; 10 | import org.apache.commons.httpclient.methods.GetMethod; 11 | import org.apache.commons.httpclient.params.HttpMethodParams; 12 | import org.json.JSONObject; 13 | import org.w3c.dom.Document; 14 | import org.w3c.dom.Node; 15 | import org.w3c.dom.NodeList; 16 | import org.xml.sax.InputSource; 17 | 18 | import javax.servlet.RequestDispatcher; 19 | import javax.servlet.ServletException; 20 | import javax.servlet.http.Cookie; 21 | import javax.servlet.http.HttpServlet; 22 | import javax.servlet.http.HttpServletRequest; 23 | import javax.servlet.http.HttpServletResponse; 24 | import javax.xml.namespace.NamespaceContext; 25 | import javax.xml.parsers.DocumentBuilder; 26 | import javax.xml.parsers.DocumentBuilderFactory; 27 | import javax.xml.xpath.*; 28 | import java.io.ByteArrayInputStream; 29 | import java.io.ByteArrayOutputStream; 30 | import java.io.IOException; 31 | import java.io.UnsupportedEncodingException; 32 | import java.net.URI; 33 | import java.net.URISyntaxException; 34 | import java.net.URLEncoder; 35 | import java.security.PublicKey; 36 | import java.security.cert.Certificate; 37 | import java.security.cert.CertificateException; 38 | import java.security.cert.CertificateFactory; 39 | import java.text.MessageFormat; 40 | import java.util.ArrayList; 41 | import java.util.Iterator; 42 | import java.util.Set; 43 | import java.util.UUID; 44 | import java.util.zip.Deflater; 45 | import java.util.zip.DeflaterOutputStream; 46 | 47 | public class SAMLServlet extends HttpServlet{ 48 | 49 | private static final String SAML_REQUEST = "{4}"; 50 | private Boolean INITIALIZED = false; 51 | private String ISSUER = null; 52 | private String IDP_URL = null; 53 | private PublicKey IDP_PUBLIC_KEY = null; 54 | 55 | @Override 56 | public void init() throws ServletException { 57 | String samlMetadata = System.getenv("SAML_METADATA"); 58 | 59 | 60 | 61 | if (samlMetadata != null) { 62 | 63 | Document metadataDocument = null; 64 | 65 | try { 66 | 67 | String response = null; 68 | 69 | if (samlMetadata.toLowerCase().startsWith("https")) { 70 | 71 | HttpClient client = new HttpClient(); 72 | 73 | // Create a method instance. 74 | GetMethod method = new GetMethod(samlMetadata); 75 | 76 | // Provide custom retry handler is necessary 77 | method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); 78 | 79 | // Execute the method. 80 | int statusCode = client.executeMethod(method); 81 | 82 | if (statusCode != HttpStatus.SC_OK) { 83 | System.err.println("Method failed: " + method.getStatusLine()); 84 | } 85 | 86 | // Read the response body. 87 | byte[] responseBody = method.getResponseBody(); 88 | 89 | // Deal with the response. 90 | response = new String(responseBody, "UTF-8"); 91 | 92 | } else { 93 | 94 | response = new String(Base64.decodeBase64(samlMetadata.getBytes("UTF-8")),"UTF-8"); 95 | 96 | } 97 | 98 | DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); 99 | domFactory.setNamespaceAware(true); 100 | DocumentBuilder builder = null; 101 | builder = domFactory.newDocumentBuilder(); 102 | metadataDocument = builder.parse(new InputSource(new ByteArrayInputStream(response.getBytes("UTF-8")))); 103 | 104 | } catch (Exception e) { 105 | throw new ServletException("Error decoding SAML Metadata", e); 106 | } 107 | 108 | //Setup XPath 109 | NamespaceContext namespaceContext = new SAMLNamespaceResolver(); 110 | XPathFactory factory = XPathFactory.newInstance(); 111 | XPath xpath = factory.newXPath(); 112 | xpath.setNamespaceContext(namespaceContext); 113 | 114 | try { 115 | 116 | XPathExpression edXPath = xpath.compile("/md:EntityDescriptor"); 117 | NodeList edXPathResult = (NodeList) edXPath.evaluate(metadataDocument, XPathConstants.NODESET); 118 | if (edXPathResult.getLength() != 1) throw new ServletException("No EntityDescriptor in SAML_METADATA"); 119 | Node edNode = edXPathResult.item(0); 120 | ISSUER = edNode.getAttributes().getNamedItem("entityID").getTextContent(); 121 | if (ISSUER == null)throw new ServletException("No entityID on Entity Descriptor in SAML_METADATA"); 122 | 123 | XPathExpression certXPath = xpath.compile("/md:EntityDescriptor/md:IDPSSODescriptor/md:KeyDescriptor/ds:KeyInfo/ds:X509Data/ds:X509Certificate"); 124 | NodeList certXPathResult = (NodeList) certXPath.evaluate(metadataDocument, XPathConstants.NODESET); 125 | if (certXPathResult.getLength() != 1) throw new ServletException("No X509Certificate node"); 126 | Node certNode = certXPathResult.item(0); 127 | StringBuffer encodedCert = new StringBuffer("-----BEGIN CERTIFICATE-----\n"); 128 | encodedCert.append(certNode.getTextContent()); 129 | encodedCert.append("\n-----END CERTIFICATE-----\n"); 130 | String cert = encodedCert.toString(); 131 | if (cert == null)throw new ServletException("No cert in cert node"); 132 | //System.out.println(cert); 133 | 134 | try { 135 | CertificateFactory cf = CertificateFactory.getInstance("X.509"); 136 | Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(cert.getBytes("UTF-8"))); 137 | IDP_PUBLIC_KEY = certificate.getPublicKey(); 138 | } catch (CertificateException e) { 139 | throw new ServletException("Error getting PublicKey from Cert", e); 140 | } catch (UnsupportedEncodingException e) { 141 | throw new ServletException("Error getting PublicKey from Cert", e); 142 | } 143 | 144 | XPathExpression ssoXPath = xpath.compile("//md:SingleSignOnService[@Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect']"); 145 | NodeList ssoXPathResult = (NodeList) ssoXPath.evaluate(metadataDocument, XPathConstants.NODESET); 146 | if (ssoXPathResult.getLength() != 1) throw new ServletException("No SingleSignOnService with Redirect Binding"); 147 | Node ssoNode = ssoXPathResult.item(0); 148 | IDP_URL = ssoNode.getAttributes().getNamedItem("Location").getTextContent(); 149 | if (IDP_URL == null)throw new ServletException("No Location for SingleSignOnService with Redirect Binding"); 150 | 151 | 152 | } catch (XPathExpressionException e) { 153 | throw new ServletException("Error Executing XPaths on Metadata", e); 154 | } 155 | 156 | System.out.println("Initialized SAML with:"); 157 | System.out.println("ISSUER:" + ISSUER); 158 | System.out.println("IDP_URL:" + IDP_URL); 159 | System.out.println("IDP_PUBLIC_KEY:" + IDP_PUBLIC_KEY); 160 | INITIALIZED = true; 161 | 162 | } else { 163 | System.out.println("SAML isn't yet initialized!"); 164 | } 165 | 166 | 167 | } 168 | 169 | @Override 170 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 171 | 172 | String logout = request.getParameter("logout"); 173 | if (logout != null) { 174 | Cookie cookie = new Cookie("IDENTITY", ""); 175 | cookie.setMaxAge(0); 176 | response.addCookie(cookie); 177 | response.sendRedirect("/"); 178 | return; 179 | } 180 | 181 | 182 | String url = request.getRequestURL().toString(); 183 | //herokuism 184 | url = url.replaceFirst("http", "https"); 185 | String app = null; 186 | try { 187 | app = new URI(url).getHost().split("\\.")[0]; 188 | } catch (URISyntaxException e) { 189 | throw new ServletException(e); 190 | } 191 | if (!INITIALIZED) { 192 | //DO some error handling 193 | request.setAttribute("URL", url); 194 | request.setAttribute("app", app); 195 | RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/configure.jsp"); 196 | dispatcher.forward(request, response); 197 | return; 198 | 199 | } else { 200 | 201 | //Pretty simply way to build a SAML Request. Beats building a DOM... 202 | String[] args = new String[5]; 203 | args[0] = url; 204 | args[1] = IDP_URL; 205 | args[2] = UUID.randomUUID().toString(); 206 | args[3] = new XSDDateTime().getDateTime(); 207 | args[4] = url; 208 | MessageFormat html; 209 | html = new MessageFormat(SAML_REQUEST); 210 | String requestXml = html.format(args); 211 | byte[] input = requestXml.getBytes("UTF-8"); 212 | 213 | //Deflate that XML 214 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 215 | Deflater d = new Deflater(Deflater.DEFLATED, true); 216 | DeflaterOutputStream dout = new DeflaterOutputStream(baos, d); 217 | dout.write(input); 218 | dout.close(); 219 | 220 | //B64 encode it 221 | String encodedRequest = Base64.encodeBase64String(baos.toByteArray()); 222 | 223 | //URLEncode it 224 | String SAMLRequest = URLEncoder.encode(encodedRequest, "UTF-8"); 225 | 226 | //Redirect that browser 227 | String relayState = request.getParameter("RelayState"); 228 | String redirect = IDP_URL + "?SAMLRequest=" + SAMLRequest; 229 | if (relayState != null) redirect += "&RelayState=" + relayState; 230 | response.sendRedirect(redirect); 231 | 232 | } 233 | 234 | } 235 | 236 | @Override 237 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 238 | 239 | String url = request.getRequestURL().toString(); 240 | //herokuism 241 | url = url.replaceFirst("http", "https"); 242 | 243 | //Get the SAMLResponse and RelayState 244 | String encodedResponse = request.getParameter("SAMLResponse"); 245 | String relayState = request.getParameter("RelayState"); 246 | if ((relayState == null) || ( relayState.equals(""))) relayState = "/"; 247 | 248 | //validate the response 249 | SAMLValidator sv = new SAMLValidator(); 250 | try { 251 | Identity identity = sv.validate(encodedResponse, IDP_PUBLIC_KEY, null, ISSUER, url, url); 252 | //DO something with the Identity 253 | JSONObject identityJSON = new JSONObject(); 254 | identityJSON.put("subject",identity.getSubject()); 255 | Bag attributes = identity.getAttributes(); 256 | Set keySet = attributes.keySet(); 257 | Iterator iterator = keySet.iterator(); 258 | while (iterator.hasNext()) { 259 | String key = (String) iterator.next(); 260 | identityJSON.put(key, (ArrayList) attributes.getValues(key)); 261 | } 262 | Cookie identityCookie = new Cookie("IDENTITY", Base64.encodeBase64URLSafeString(identityJSON.toString().getBytes("UTF-8"))); 263 | response.addCookie(identityCookie); 264 | } catch (Exception e) { 265 | response.sendError(401, "Access Denied: " + e.getMessage()); 266 | return; 267 | } 268 | response.sendRedirect(relayState); 269 | 270 | 271 | 272 | } 273 | 274 | } 275 | -------------------------------------------------------------------------------- /src/main/java/com/salesforce/saml/SAMLValidator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012, Salesforce.com 3 | * All rights reserved. 4 | * 5 | * Derived from 6 | * Copyright (c) 2009, Chuck Mortimore 7 | * All rights reserved. 8 | * 9 | * 10 | * Redistribution and use in source and binary forms, with or without 11 | * modification, are permitted provided that the following conditions are met: 12 | * 13 | * * Redistributions of source code must retain the above copyright 14 | * notice, this list of conditions and the following disclaimer. 15 | * * Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in the 17 | * documentation and/or other materials provided with the distribution. 18 | * * Neither the names salesforce, salesforce.com xmldap, xmldap.org, nor the 19 | * names of its contributors may be used to endorse or promote products 20 | * derived from this software without specific prior written permission. 21 | * 22 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY 23 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 24 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 25 | * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY 26 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 27 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 28 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 29 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 31 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | */ 33 | 34 | 35 | package com.salesforce.saml; 36 | 37 | import org.apache.commons.codec.binary.Base64; 38 | import org.w3c.dom.Document; 39 | import org.w3c.dom.Element; 40 | import org.w3c.dom.Node; 41 | import org.w3c.dom.NodeList; 42 | import org.xml.sax.InputSource; 43 | import org.xml.sax.SAXException; 44 | 45 | import javax.xml.bind.DatatypeConverter; 46 | import javax.xml.crypto.MarshalException; 47 | import javax.xml.crypto.dsig.Reference; 48 | import javax.xml.crypto.dsig.XMLSignature; 49 | import javax.xml.crypto.dsig.XMLSignatureException; 50 | import javax.xml.crypto.dsig.XMLSignatureFactory; 51 | import javax.xml.crypto.dsig.dom.DOMValidateContext; 52 | import javax.xml.namespace.NamespaceContext; 53 | import javax.xml.parsers.DocumentBuilder; 54 | import javax.xml.parsers.DocumentBuilderFactory; 55 | import javax.xml.parsers.ParserConfigurationException; 56 | import javax.xml.xpath.*; 57 | import java.io.ByteArrayInputStream; 58 | import java.io.IOException; 59 | import java.io.UnsupportedEncodingException; 60 | import java.security.PublicKey; 61 | import java.util.Calendar; 62 | import java.util.Iterator; 63 | import java.util.List; 64 | 65 | 66 | public class SAMLValidator { 67 | 68 | private static Boolean DEBUG = false; 69 | 70 | public Identity validate(String encodedResponse, PublicKey publicKey, PublicKey secondaryPublicKey, String issuer, String recipient, String audience) throws SAMLException { 71 | 72 | Identity identity = null; 73 | boolean isValid = false; 74 | 75 | //Build the document 76 | Document responseDocument = null; 77 | try { 78 | String response = new String(Base64.decodeBase64(encodedResponse.getBytes("UTF-8")),"UTF-8"); 79 | DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); 80 | domFactory.setNamespaceAware(true); 81 | DocumentBuilder builder = null; 82 | builder = domFactory.newDocumentBuilder(); 83 | responseDocument = builder.parse(new InputSource(new ByteArrayInputStream(response.getBytes("UTF-8")))); 84 | } catch (Exception e) { 85 | throw new SAMLException("Error decoding SAMLResponse", e); 86 | } 87 | 88 | Node responseNode = null; 89 | Node assertionNode = null; 90 | NodeList responseXPathSignatureResult = null; 91 | 92 | //Setup XPath 93 | NamespaceContext namespaceContext = new SAMLNamespaceResolver(); 94 | XPathFactory factory = XPathFactory.newInstance(); 95 | XPath xpath = factory.newXPath(); 96 | xpath.setNamespaceContext(namespaceContext); 97 | 98 | if (DEBUG) System.err.println("Successfully setup Doc for parsing"); 99 | 100 | try { 101 | 102 | //Check the status 103 | XPathExpression statusXPath = xpath.compile("/samlp:Response/samlp:Status/samlp:StatusCode"); 104 | NodeList statusXPathResult = (NodeList) statusXPath.evaluate(responseDocument, XPathConstants.NODESET); 105 | if (statusXPathResult.getLength() != 1) throw new SAMLException("No StatusCode"); 106 | Node statusNode = statusXPathResult.item(0); 107 | String statusCode = statusNode.getAttributes().getNamedItem("Value").getTextContent(); 108 | if (!statusCode.equals("urn:oasis:names:tc:SAML:2.0:status:Success"))throw new SAMLException("IDP responded with status of: " + statusCode); 109 | if (DEBUG) System.err.println("Status: " + statusCode); 110 | 111 | 112 | //Get the Response node and fail if more than one 113 | XPathExpression responseXPath = xpath.compile("/samlp:Response"); 114 | NodeList responseXPathResult = (NodeList) responseXPath.evaluate(responseDocument, XPathConstants.NODESET); 115 | if (responseXPathResult.getLength() != 1) throw new SAMLException("More than 1 Response"); 116 | responseNode = responseXPathResult.item(0); 117 | if (DEBUG) System.err.println("Only 1 Response"); 118 | 119 | //Get the Assertion node and fail if more than one 120 | XPathExpression assertionXPath = xpath.compile("/samlp:Response/saml:Assertion"); 121 | NodeList assertionXPathResult = (NodeList) assertionXPath.evaluate(responseDocument, XPathConstants.NODESET); 122 | if (assertionXPathResult.getLength() != 1) throw new SAMLException("More than 1 Assertion"); 123 | assertionNode = assertionXPathResult.item(0); 124 | if (DEBUG) System.err.println("Only 1 Assertion"); 125 | 126 | //See if the response is signed 127 | XPathExpression responseSignatureXPath = xpath.compile("/samlp:Response/ds:Signature"); 128 | responseXPathSignatureResult = (NodeList) responseSignatureXPath.evaluate(responseDocument, XPathConstants.NODESET); 129 | 130 | } catch (XPathExpressionException e) { 131 | throw new SAMLException("Error Executing XPaths on Assertion", e); 132 | } 133 | 134 | 135 | if (responseXPathSignatureResult.getLength() > 1) { 136 | 137 | throw new SAMLException("More than 1 Response Signature"); 138 | 139 | } else if (responseXPathSignatureResult.getLength() == 1) { 140 | 141 | if (DEBUG) System.err.println("Response is Signed and there is only 1 signature"); 142 | 143 | //Check the response signature 144 | String responseId = responseNode.getAttributes().getNamedItem("ID").getTextContent(); 145 | Node signature = responseXPathSignatureResult.item(0); 146 | if (DEBUG) System.err.println("Signature node: " + signature); 147 | 148 | try { 149 | //check to see if the sig validates with the primary public key 150 | isValid = validateSignature(responseNode, signature, responseId, publicKey); 151 | if (DEBUG) System.err.println("Response Signature is valid: " + isValid); 152 | 153 | 154 | } catch (InvalidSignatureException e) { 155 | if (DEBUG) System.err.println("InvalidSignatureException: " + e.getMessage()); 156 | 157 | //If we have multiple keys, and the first one fails, check the sig with the second one 158 | if (secondaryPublicKey != null) { 159 | if (DEBUG) System.err.println("Checking second key"); 160 | try { 161 | isValid = validateSignature(responseNode, signature, responseId, secondaryPublicKey); 162 | if (DEBUG) System.err.println("Response Signature validated with second public key"); 163 | } catch (InvalidSignatureException e1) { 164 | throw new SAMLException("Invalid Response Signature", e1); 165 | } 166 | } 167 | } 168 | 169 | } else { 170 | if (DEBUG) System.err.println("No response signature. Check the assertion signature"); 171 | //No response signature. Check the assertion signature 172 | NodeList assertionSignatureXPathResult = null; 173 | try { 174 | XPathExpression assertionSignatureXPath = xpath.compile("/samlp:Response/saml:Assertion/ds:Signature"); 175 | assertionSignatureXPathResult = (NodeList) assertionSignatureXPath.evaluate(responseDocument, XPathConstants.NODESET); 176 | } catch (XPathExpressionException e) { 177 | throw new SAMLException("Error Executing XPaths on Assertion", e); 178 | } 179 | if (assertionSignatureXPathResult.getLength() > 1) { 180 | throw new SAMLException("More than 1 Assertion Signature"); 181 | } else if (assertionSignatureXPathResult.getLength() ==1 ) { 182 | String assertionId = assertionNode.getAttributes().getNamedItem("ID").getTextContent(); 183 | Node signature = assertionSignatureXPathResult.item(0); 184 | try { 185 | isValid = validateSignature(assertionNode,signature, assertionId, publicKey); 186 | if (DEBUG) System.err.println("Assertion Signature validated with first public key"); 187 | 188 | } catch (InvalidSignatureException e) { 189 | if (secondaryPublicKey != null) { 190 | try { 191 | isValid = validateSignature(assertionNode,signature, assertionId, secondaryPublicKey); 192 | if (DEBUG) System.err.println("Assertion Signature validated with second public key"); 193 | 194 | } catch (InvalidSignatureException e1) { 195 | throw new SAMLException("Invalid Assertion Signature", e1); 196 | } 197 | } 198 | } 199 | } else throw new SAMLException("No Signature"); 200 | 201 | } 202 | 203 | if (isValid) { 204 | if (DEBUG) System.err.println("Signature was valid. Let's check some other stuff"); 205 | 206 | 207 | try { 208 | 209 | //check the issuer 210 | XPathExpression issuerXPath = xpath.compile("saml:Issuer"); 211 | Node issuerNode = (Node) issuerXPath.evaluate(assertionNode, XPathConstants.NODE); 212 | String assertedIssuer = issuerNode.getTextContent(); 213 | if (!issuer.equals(assertedIssuer)) throw new SAMLException("Invalid Issuer"); 214 | 215 | //check the recipient 216 | XPathExpression subjectConfirmationDataXPath = xpath.compile("saml:Subject/saml:SubjectConfirmation/saml:SubjectConfirmationData"); 217 | Node subjectConfirmationDataNode = (Node) subjectConfirmationDataXPath.evaluate(assertionNode, XPathConstants.NODE); 218 | String assertedRecipient = subjectConfirmationDataNode.getAttributes().getNamedItem("Recipient").getTextContent(); 219 | if (!recipient.equals(assertedRecipient)) throw new SAMLException("Invalid Recipient. Expected "+recipient+", received "+assertedRecipient); 220 | 221 | //check the audience 222 | XPathExpression audienceXPath = xpath.compile("saml:Conditions/saml:AudienceRestriction/saml:Audience"); 223 | Node audienceNode = (Node) audienceXPath.evaluate(assertionNode, XPathConstants.NODE); 224 | String assertedAudience = audienceNode.getTextContent(); 225 | if (!audience.equals(assertedAudience)) throw new SAMLException("Invalid Audience"); 226 | 227 | //Check the validity 228 | XPathExpression conditionsXPath = xpath.compile("saml:Conditions"); 229 | Node conditionsNode = (Node) conditionsXPath.evaluate(assertionNode, XPathConstants.NODE); 230 | String notOnOrAfter = conditionsNode.getAttributes().getNamedItem("NotOnOrAfter").getTextContent(); 231 | String notBefore = conditionsNode.getAttributes().getNamedItem("NotBefore").getTextContent(); 232 | Calendar start = DatatypeConverter.parseDateTime(notBefore); 233 | Calendar end = DatatypeConverter.parseDateTime(notOnOrAfter); 234 | if ( System.currentTimeMillis() <= start.getTimeInMillis() ) throw new SAMLException("Assertion appears to have arrived early"); 235 | if ( System.currentTimeMillis() > end.getTimeInMillis() ) throw new SAMLException("Assertion Expired"); 236 | 237 | //get the subject 238 | XPathExpression nameIDXPath = xpath.compile("saml:Subject/saml:NameID"); 239 | Node nameIdNode = (Node) nameIDXPath.evaluate(assertionNode, XPathConstants.NODE); 240 | identity = new Identity(nameIdNode.getTextContent(), false); 241 | 242 | XPathExpression attributeXPath = xpath.compile("/samlp:Response/saml:Assertion/saml:AttributeStatement"); 243 | NodeList attributeXPathResult = (NodeList) attributeXPath.evaluate(responseDocument, XPathConstants.NODESET); 244 | for(int i = 0; i < attributeXPathResult.getLength(); i++) { 245 | Node attributeStatement = attributeXPathResult.item(i); 246 | NodeList attributes = attributeStatement.getChildNodes(); 247 | for(int j = 0; j < attributes.getLength(); j++) { 248 | Node attribute = attributes.item(j); 249 | String name = attribute.getAttributes().getNamedItem("Name").getTextContent(); 250 | String value = attribute.getFirstChild().getTextContent(); 251 | identity.getAttributes().put(name,value); 252 | } 253 | } 254 | 255 | } catch (XPathExpressionException e) { 256 | throw new SAMLException("Error Executing XPaths on Assertion", e); 257 | } catch (UnsupportedEncodingException e) { 258 | throw new SAMLException("Error constructing Identity", e); 259 | } 260 | 261 | } else { 262 | 263 | throw new SAMLException("Invalid Signature"); 264 | 265 | } 266 | 267 | return identity; 268 | 269 | } 270 | 271 | private boolean validateSignature(Node env, Node signature, String id, PublicKey publicKey) throws SAMLException, InvalidSignatureException { 272 | 273 | DOMValidateContext valContext = new DOMValidateContext (publicKey, signature); 274 | valContext.setIdAttributeNS((Element)env, null, "ID"); 275 | XMLSignatureFactory xsf = XMLSignatureFactory.getInstance("DOM"); 276 | XMLSignature xs = null; 277 | try { 278 | xs = xsf.unmarshalXMLSignature(valContext); 279 | } catch (MarshalException e) { 280 | throw new SAMLException(e); 281 | } 282 | if (DEBUG) System.err.println("Signature stuff all setup to start checking"); 283 | 284 | List references = xs.getSignedInfo().getReferences(); 285 | if (references.size() != 1) throw new SAMLException("1 and Only 1 Reference is allowed"); 286 | if (DEBUG) System.err.println("Only 1 reference in signature"); 287 | 288 | Reference ref = references.get(0); 289 | String refURI = ref.getURI(); 290 | if ((refURI != null) && (!refURI.equals(""))) { 291 | String refURIStripped = refURI.substring(1); 292 | if (DEBUG) System.err.println("Reference: " + refURIStripped); 293 | if (!id.equals(refURIStripped)) throw new SAMLException("Signature Reference is NOT targeting enveloping node: " + id + "|" + refURIStripped); 294 | } 295 | 296 | try { 297 | if (DEBUG) System.err.println("Validating signature "); 298 | return xs.validate(valContext); 299 | } catch (XMLSignatureException e) { 300 | throw new InvalidSignatureException(e); 301 | } 302 | 303 | } 304 | } -------------------------------------------------------------------------------- /src/main/java/com/salesforce/saml/TLSFilter.java: -------------------------------------------------------------------------------- 1 | package com.salesforce.saml; 2 | 3 | import java.io.IOException; 4 | import javax.servlet.*; 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | 8 | 9 | public class TLSFilter implements Filter { 10 | 11 | 12 | @Override 13 | public void init(FilterConfig filterConfig) throws ServletException { 14 | 15 | } 16 | 17 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 18 | HttpServletRequest httpRequest = (HttpServletRequest) request; 19 | HttpServletResponse httpResponse = (HttpServletResponse) response; 20 | String scheme = httpRequest.getHeader("x-forwarded-proto"); 21 | 22 | if(!scheme.equals("https")) { 23 | StringBuilder tlsURL = new StringBuilder("https://"); 24 | tlsURL.append(request.getServerName()); 25 | if (httpRequest.getRequestURI() != null) { 26 | tlsURL.append(httpRequest.getRequestURI()); 27 | } 28 | if (httpRequest.getQueryString() != null) { 29 | tlsURL.append("?").append(httpRequest.getQueryString()); 30 | } 31 | 32 | httpResponse.sendRedirect(tlsURL.toString()); 33 | 34 | } else { 35 | if (chain != null) chain.doFilter(request, response); 36 | } 37 | } 38 | 39 | @Override 40 | public void destroy() { 41 | 42 | } 43 | } -------------------------------------------------------------------------------- /src/main/java/com/salesforce/util/Bag.java: -------------------------------------------------------------------------------- 1 | package com.salesforce.util; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.Iterator; 6 | import java.util.LinkedHashMap; 7 | import java.util.List; 8 | 9 | 10 | /** 11 | * This extension of HashMap support duplicate keys 12 | */ 13 | public class Bag extends LinkedHashMap { 14 | public List getValues(Object key) { 15 | if (super.containsKey(key)) { 16 | return (List) super.get(key); 17 | } else { 18 | return new ArrayList(); 19 | } 20 | } 21 | 22 | public Object get(Object key) { 23 | ArrayList values = (ArrayList) super.get(key); 24 | if (values != null && !values.isEmpty()) { 25 | return values.get(0); 26 | } else { 27 | return null; 28 | } 29 | } 30 | 31 | public boolean containsValue(Object value) { 32 | return values().contains(value); 33 | } 34 | 35 | public int size() { 36 | int size = 0; 37 | Iterator keyIterator = super.keySet().iterator(); 38 | 39 | while (keyIterator.hasNext()) { 40 | ArrayList values = (ArrayList) super.get(keyIterator.next()); 41 | size = size + values.size(); 42 | } 43 | 44 | return size; 45 | } 46 | 47 | public Object put(Object key, Object value) { 48 | ArrayList values = new ArrayList(); 49 | 50 | if (super.containsKey(key)) { 51 | values = (ArrayList) super.get(key); 52 | values.add(value); 53 | 54 | } else { 55 | values.add(value); 56 | } 57 | 58 | super.put(key, values); 59 | 60 | return null; 61 | } 62 | 63 | public boolean remove(Object key, Object value) { 64 | boolean removed = false; 65 | List values = getValues(key); 66 | if (values != null) { 67 | values.remove(value); 68 | if (values.isEmpty()) { 69 | remove(key); 70 | } 71 | removed = true; 72 | } 73 | return removed; 74 | } 75 | 76 | public Collection values() { 77 | List values = new ArrayList(); 78 | Iterator keyIterator = super.keySet().iterator(); 79 | 80 | while (keyIterator.hasNext()) { 81 | List keyValues = (List) super.get(keyIterator.next()); 82 | values.addAll(keyValues); 83 | } 84 | 85 | return values; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/salesforce/util/XSDDateTime.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2006, Chuck Mortimore - xmldap.org 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in the 12 | * documentation and/or other materials provided with the distribution. 13 | * * Neither the names xmldap, xmldap.org, xmldap.com nor the 14 | * names of its contributors may be used to endorse or promote products 15 | * derived from this software without specific prior written permission. 16 | * 17 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY 18 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 19 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 20 | * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY 21 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 22 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 23 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 24 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | 30 | package com.salesforce.util; 31 | 32 | import java.text.SimpleDateFormat; 33 | import java.util.Calendar; 34 | import java.util.TimeZone; 35 | 36 | public class XSDDateTime { 37 | 38 | private int moreMinutes; 39 | 40 | public XSDDateTime() { 41 | moreMinutes = 0; 42 | } 43 | 44 | public XSDDateTime(int moreMinutes) { 45 | this.moreMinutes = moreMinutes; 46 | } 47 | 48 | public String getDateTime() { 49 | SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); 50 | df.setTimeZone(TimeZone.getTimeZone("GMT")); 51 | Calendar cal = Calendar.getInstance(); 52 | cal.add(Calendar.MINUTE, moreMinutes); //Adding 1 day to current date 53 | return df.format(cal.getTime()) + "Z"; 54 | } 55 | 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | index.jsp 10 | 11 | 12 | TLSFilter 13 | com.salesforce.saml.TLSFilter 14 | 15 | 16 | TLSFilter 17 | /* 18 | 19 | 20 | SAMLServlet 21 | com.salesforce.saml.SAMLServlet 22 | 23 | 24 | 25 | SAMLServlet 26 | /_saml 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/main/webapp/configure.jsp: -------------------------------------------------------------------------------- 1 | <% 2 | String url = (String)request.getAttribute("URL"); 3 | String app = (String)request.getAttribute("app"); 4 | %> 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |

Whoops!

13 | 14 | It doesn't look like you've configured SAML quite yet....please follow these steps: 15 | 16 |
    17 | 18 |

  1. Go to your Salesforce org, and create a Connected App:
  2. 19 |

    Navigate to Setup | Create | Apps

    20 |

    Scroll down to Connected Apps and click New

    21 |

    Give your app a name, enter your email address and, optionally, set a logo, icon and description

    22 |

    Scroll down to Web App Settings and check the Enable SAML checkbox

    23 |

    Use the following Start Url: <%= url %>

    24 |

    Use the following Entity Id: <%= url %>

    25 |

    Use the following ACS URL: <%= url %>

    26 |

    ...and don't forget to authorize your Profile or Permission Set

    27 | 28 | 29 | 30 |

  3. Now, configure SAML via a Metadata URL:
  4. 31 |

    Click 'Manage' from the Connected App detail page and copy your Metadata URL

    32 |

    Run this command using toolbelt:

    33 |
    heroku config:set --app <%= app %> SAML_METADATA=<your metadata url>
    34 |

    Refresh this page

    35 | 36 | 37 |

  5. Or...configured SAML via a Metadata File
  6. 38 |

    Click 'Manage' from the Connected App detail page and download your Connected App's SAML Metadata

    39 |

    Base64 Encode the Metadata

    40 |

    Run this command using toolbelt:

    41 |
    heroku config:set --app <%= app %> SAML_METADATA=<your base64 encoded metadata>
    42 |

    Refresh this page

    43 | 44 | -------------------------------------------------------------------------------- /src/main/webapp/css/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: Arial; 3 | background-color: #F0F1F2; 4 | 5 | } 6 | 7 | .centered { 8 | position: fixed; 9 | top: 50%; 10 | left: 50%; 11 | margin-top: -100px; 12 | margin-left: -100px; 13 | width:3 60px; 14 | 15 | } 16 | 17 | .button { 18 | background-color:#2A94D6; 19 | -webkit-border-radius:4px; 20 | -moz-border-radius:4px; 21 | border-radius:4px; 22 | text-indent:0; 23 | border:1px solid #469df5; 24 | display:inline-block; 25 | color:#ffffff; 26 | font-family:Arial; 27 | font-size:15px; 28 | font-style:normal; 29 | height:50px; 30 | line-height:50px; 31 | text-decoration:none; 32 | text-align:center; 33 | padding-left:20px; 34 | padding-right:20px; 35 | width:200px; 36 | 37 | } 38 | 39 | .inputbox { 40 | 41 | padding:10px; 42 | font-size:16px; 43 | width:300px; 44 | 45 | } 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/main/webapp/img/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/salesforceidentity/heroku-identity-java/1cc22cfe190aa74e85750f5f16fc66a3c8592b12/src/main/webapp/img/logo.png -------------------------------------------------------------------------------- /src/main/webapp/index.jsp: -------------------------------------------------------------------------------- 1 | <%@ page import="com.salesforce.saml.Identity,com.salesforce.util.Bag,java.util.Set,java.util.Iterator,java.util.ArrayList" %> 2 | <% 3 | Identity identity = null; 4 | Cookie[] cookies = request.getCookies(); 5 | if (cookies != null) { 6 | for (Cookie cookie : cookies) { 7 | if (cookie.getName().equals("IDENTITY")) { 8 | identity = new Identity(cookie.getValue(),true); 9 | } 10 | } 11 | } 12 | 13 | %> 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | <% if (identity != null ) { %> 24 |
    25 |

    <%= identity.getSubject() %>

    26 | 27 | <% 28 | Bag attributes = identity.getAttributes(); 29 | Set keySet = attributes.keySet(); 30 | Iterator iterator = keySet.iterator(); 31 | while (iterator.hasNext()){ 32 | String key = (String)iterator.next(); 33 | %><% 39 | 40 | } 41 | 42 | %> 43 |
    <%= key %>:<% 34 | ArrayList values = (ArrayList)attributes.getValues(key); 35 | for (String value : values) { 36 | %><%= value %>
    <% 37 | } 38 | %>
    44 |
    45 | Logout 46 |
    47 | <% } else { %> 48 |
    49 | Login 50 |
    51 | 52 | <% } %> 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /system.properties: -------------------------------------------------------------------------------- 1 | java.runtime.version=1.8 --------------------------------------------------------------------------------