├── .travis.yml ├── .github ├── ISSUE_TEMPLATE │ ├── config.yml │ ├── feature_request.md │ ├── improvement.md │ ├── doc_issues.md │ └── bug_report.md ├── workflows │ └── pr-builder.yml └── PULL_REQUEST_TEMPLATE.md ├── codecov.yml ├── .gitignore ├── issue_template.md ├── io.asgardeo.java.saml.sdk ├── src │ └── main │ │ └── java │ │ └── io │ │ └── asgardeo │ │ └── java │ │ └── saml │ │ └── sdk │ │ ├── SAMLSignatureValidator.java │ │ ├── exception │ │ ├── ArtifactResolutionException.java │ │ ├── InvalidSessionException.java │ │ └── SSOAgentException.java │ │ ├── security │ │ ├── SSOAgentX509Credential.java │ │ ├── SSOAgentCredential.java │ │ ├── X509CredentialImpl.java │ │ ├── SSOAgentKeyStoreCredential.java │ │ └── SSOAgentX509KeyStoreCredential.java │ │ ├── util │ │ ├── SSOAgentDataHolder.java │ │ ├── SSOAgentFilterUtils.java │ │ ├── SSOAgentRequestResolver.java │ │ ├── SSOAgentConstants.java │ │ ├── SSOAgentConfigs.java │ │ └── SSOAgentUtils.java │ │ ├── request │ │ ├── SAML2RequestInfo.java │ │ ├── SAML2IdleRequestCleanupTask.java │ │ └── SAML2RequestDataHolder.java │ │ ├── session │ │ └── management │ │ │ ├── SSOAgentHttpSessionListener.java │ │ │ └── SSOAgentSessionManager.java │ │ ├── AESDecryptor.java │ │ ├── bean │ │ ├── SSOAgentSessionBean.java │ │ ├── LoggedInSessionBean.java │ │ └── SSOAgentConfig.java │ │ └── artifact │ │ ├── SAMLSSOSoapMessageService.java │ │ └── SAMLSSOArtifactResolutionService.java └── pom.xml ├── pull_request_template.md ├── README.md ├── LICENSE └── pom.xml /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - openjdk8 4 | cache: 5 | directories: 6 | - .autoconf 7 | - $HOME/.m2 8 | script: mvn clean install 9 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: true 2 | contact_links: 3 | - name: Ask a question 4 | url: https://github.com/wso2/product-is/wiki/Engage-with-the-community 5 | about: Check here on how you can ask a question about the product 6 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | 2 | codecov: 3 | require_ci_to_pass: yes 4 | notify: 5 | wait_for_ci: yes 6 | coverage: 7 | status: 8 | project: 9 | default: 10 | enabled: yes 11 | threshold: null 12 | target: auto 13 | patch: 14 | default: 15 | target: 80% 16 | threshold: 40% 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | .classpath 3 | .settings 4 | .project 5 | *.iml 6 | *.iws 7 | *.ipr 8 | .idea 9 | *.DS_Store 10 | 11 | # Mobile Tools for Java (J2ME) 12 | .mtj.tmp/ 13 | 14 | # Package Files # 15 | *.jar 16 | *.war 17 | *.ear 18 | 19 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 20 | hs_err_pid* 21 | 22 | # Ignore everything in this directory 23 | target -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: ➕ Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: 'feature' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | 12 | 13 | **Describe the solution you would prefer** 14 | 15 | 16 | **Additional context** 17 | 18 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/improvement.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: ✅ Improvement suggestion 3 | about: Suggest an improvement for the project 4 | title: '' 5 | labels: 'improvement' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your suggestion related to an experience ? Please describe.** 11 | 12 | 13 | **Describe the improvement** 14 | 15 | 16 | **Additional context** 17 | 18 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/doc_issues.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 📕 Doc issues 3 | about: Please report documentation issues here 4 | title: '' 5 | labels: 'docs' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your suggestion related to a missing or misleading document? Please describe.** 11 | 12 | 13 | **Describe the improvement** 14 | 15 | 16 | --- 17 | 18 | ### Optional Fields 19 | 20 | **Additional context** 21 | 22 | 23 | **Related Issues:** 24 | 25 | -------------------------------------------------------------------------------- /issue_template.md: -------------------------------------------------------------------------------- 1 | **Description:** 2 | 3 | 4 | **Suggested Labels:** 5 | 6 | 7 | **Suggested Assignees:** 8 | 9 | 10 | **Affected Product Version:** 11 | 12 | **OS, DB, other environment details and versions:** 13 | 14 | **Steps to reproduce:** 15 | 16 | 17 | **Related Issues:** 18 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: ❗️ Issue/Bug report 3 | about: Report issue or bug related to the project 4 | title: '' 5 | labels: 'bug' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the issue:** 11 | 12 | 13 | **How to reproduce:** 14 | 15 | 16 | **Expected behavior:** 17 | 18 | 19 | **Environment information** (_Please complete the following information; remove any unnecessary fields_) **:** 20 | - Product Version: [e.g., IS 5.10.0, IS 5.9.0] 21 | - OS: [e.g., Windows, Linux, Mac] 22 | - SDK Version: [e.g., 0.1.0, 0.1.1] 23 | 24 | --- 25 | 26 | ### Optional Fields 27 | 28 | **Related issues:** 29 | 30 | 31 | **Suggested labels:** 32 | 33 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/SAMLSignatureValidator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | package io.asgardeo.java.saml.sdk; 19 | 20 | import io.asgardeo.java.saml.sdk.bean.SSOAgentConfig; 21 | import io.asgardeo.java.saml.sdk.exception.SSOAgentException; 22 | import org.opensaml.saml.saml2.core.Assertion; 23 | import org.opensaml.saml.saml2.core.Response; 24 | 25 | public interface SAMLSignatureValidator { 26 | 27 | void validateSignature(Response response, Assertion assertion, SSOAgentConfig ssoAgentConfig) 28 | throws SSOAgentException; 29 | } -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/exception/ArtifactResolutionException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.asgardeo.java.saml.sdk.exception; 20 | 21 | /** 22 | * This class is used to denote exceptions thrown from the SAML2 Artifact Resolution 23 | */ 24 | public class ArtifactResolutionException extends Exception { 25 | 26 | public ArtifactResolutionException(String message) { 27 | 28 | super(message); 29 | } 30 | 31 | public ArtifactResolutionException(String message, Throwable cause) { 32 | 33 | super(message, cause); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/exception/InvalidSessionException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.asgardeo.java.saml.sdk.exception; 20 | 21 | /** 22 | * Invalid session exception. 23 | */ 24 | public class InvalidSessionException extends SSOAgentException { 25 | 26 | public InvalidSessionException(String message) { 27 | 28 | super(message); 29 | } 30 | 31 | public InvalidSessionException(Throwable cause) { 32 | 33 | super(cause); 34 | } 35 | 36 | public InvalidSessionException(String message, Throwable cause) { 37 | 38 | super(message, cause); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/security/SSOAgentX509Credential.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | * 18 | * 19 | */ 20 | 21 | package io.asgardeo.java.saml.sdk.security; 22 | 23 | import io.asgardeo.java.saml.sdk.exception.SSOAgentException; 24 | 25 | import java.security.PrivateKey; 26 | import java.security.PublicKey; 27 | import java.security.cert.X509Certificate; 28 | 29 | public interface SSOAgentX509Credential { 30 | 31 | PublicKey getPublicKey() throws SSOAgentException; 32 | 33 | PrivateKey getPrivateKey() throws SSOAgentException; 34 | 35 | X509Certificate getEntityCertificate() throws SSOAgentException; 36 | 37 | } 38 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/security/SSOAgentCredential.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | * 18 | * 19 | */ 20 | 21 | package io.asgardeo.java.saml.sdk.security; 22 | 23 | import io.asgardeo.java.saml.sdk.exception.SSOAgentException; 24 | 25 | import java.security.PrivateKey; 26 | import java.security.PublicKey; 27 | import java.security.cert.X509Certificate; 28 | 29 | public interface SSOAgentCredential { 30 | 31 | void init() throws SSOAgentException; 32 | 33 | PublicKey getPublicKey() throws SSOAgentException; 34 | 35 | PrivateKey getPrivateKey() throws SSOAgentException; 36 | 37 | X509Certificate getEntityCertificate() throws SSOAgentException; 38 | 39 | } 40 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/exception/SSOAgentException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | * 18 | * 19 | */ 20 | 21 | package io.asgardeo.java.saml.sdk.exception; 22 | 23 | import javax.servlet.ServletException; 24 | 25 | /** 26 | * This class is used to denote the exceptions thrown from the SSO agent module 27 | */ 28 | public class SSOAgentException extends ServletException { 29 | 30 | public SSOAgentException(String message) { 31 | 32 | super(message); 33 | } 34 | 35 | public SSOAgentException(Throwable cause) { 36 | 37 | super(cause); 38 | } 39 | 40 | public SSOAgentException(String message, Throwable cause) { 41 | 42 | super(message, cause); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /.github/workflows/pr-builder.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build the project on pull requests with tests 2 | # Uses: 3 | # OS: ubuntu-latest 4 | # JDK: Adopt JDK 8 5 | 6 | name: PR Builder 7 | 8 | on: 9 | pull_request: 10 | branches: [main, master] 11 | workflow_dispatch: 12 | 13 | env: 14 | MAVEN_OPTS: -Xmx4g -Xms1g 15 | 16 | jobs: 17 | build: 18 | runs-on: ubuntu-latest 19 | 20 | steps: 21 | - uses: actions/checkout@v2 22 | - name: Set up Adopt JDK 8 23 | uses: actions/setup-java@v2 24 | with: 25 | java-version: "8" 26 | distribution: "adopt" 27 | - name: Cache local Maven repository 28 | id: cache-maven-m2 29 | uses: actions/cache@v2 30 | env: 31 | cache-name: cache-m2 32 | with: 33 | path: ~/.m2/repository 34 | key: ${{ runner.os }}-maven-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} 35 | restore-keys: | 36 | ${{ runner.os }}-maven-${{ env.cache-name }}- 37 | ${{ runner.os }}-maven- 38 | ${{ runner.os }}- 39 | - name: Build with Maven 40 | run: mvn clean install -U -B 41 | 42 | - name: Generate coverage report 43 | run: mvn test jacoco:report 44 | 45 | - name: Upload coverage reports to Codecov 46 | uses: codecov/codecov-action@v4 47 | with: 48 | token: ${{ secrets.CODECOV_TOKEN }} 49 | files : target/site/jacoco/jacoco.xml 50 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/util/SSOAgentDataHolder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | * 18 | * 19 | */ 20 | 21 | package io.asgardeo.java.saml.sdk.util; 22 | 23 | public class SSOAgentDataHolder { 24 | 25 | private static SSOAgentDataHolder instance = new SSOAgentDataHolder(); 26 | private Object signatureValidator = null; 27 | 28 | private SSOAgentDataHolder() { 29 | 30 | } 31 | 32 | public static SSOAgentDataHolder getInstance() { 33 | 34 | return instance; 35 | } 36 | 37 | public Object getSignatureValidator() { 38 | 39 | return signatureValidator; 40 | } 41 | 42 | public void setSignatureValidator(Object signatureValidator) { 43 | 44 | this.signatureValidator = signatureValidator; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/request/SAML2RequestInfo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.asgardeo.java.saml.sdk.request; 20 | 21 | /** 22 | * SAML2 request info. 23 | * 24 | */ 25 | public class SAML2RequestInfo { 26 | 27 | private boolean loginRequest; 28 | 29 | private long initiatedTime; 30 | 31 | public SAML2RequestInfo(boolean loginRequest, long initiatedTime) { 32 | 33 | this.loginRequest = loginRequest; 34 | this.initiatedTime = initiatedTime; 35 | } 36 | 37 | public boolean isLoginRequest() { 38 | 39 | return loginRequest; 40 | } 41 | 42 | public void setLoginRequest(boolean loginRequest) { 43 | 44 | this.loginRequest = loginRequest; 45 | } 46 | 47 | public long getInitiatedTime() { 48 | 49 | return initiatedTime; 50 | } 51 | 52 | public void setInitiatedTime(long initiatedTime) { 53 | 54 | this.initiatedTime = initiatedTime; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/request/SAML2IdleRequestCleanupTask.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.asgardeo.java.saml.sdk.request; 20 | 21 | import io.asgardeo.java.saml.sdk.util.SSOAgentConstants; 22 | 23 | import java.util.logging.Logger; 24 | 25 | /** 26 | * SAML2 idle request cleanup task. 27 | */ 28 | public class SAML2IdleRequestCleanupTask implements Runnable { 29 | 30 | private static final Logger LOGGER = Logger.getLogger(SSOAgentConstants.LOGGER_NAME); 31 | // Default idle time is one day. 32 | private int idleTimeOutInMinutes = 1440; 33 | 34 | public SAML2IdleRequestCleanupTask(int idleTimeOutInMinutes) { 35 | 36 | if (idleTimeOutInMinutes > 0) { 37 | this.idleTimeOutInMinutes = idleTimeOutInMinutes; 38 | } 39 | } 40 | 41 | @Override 42 | public void run() { 43 | 44 | SAML2RequestDataHolder.getInstance().cleanIdleRequests(idleTimeOutInMinutes); 45 | LOGGER.info("SAML2 idle request cleanup task executed successfully."); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/session/management/SSOAgentHttpSessionListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.asgardeo.java.saml.sdk.session.management; 20 | 21 | import io.asgardeo.java.saml.sdk.util.SSOAgentConstants; 22 | 23 | import java.util.logging.Level; 24 | import java.util.logging.Logger; 25 | 26 | import javax.servlet.http.HttpSessionEvent; 27 | import javax.servlet.http.HttpSessionListener; 28 | 29 | public class SSOAgentHttpSessionListener implements HttpSessionListener { 30 | 31 | private static final Logger LOGGER = Logger.getLogger(SSOAgentConstants.LOGGER_NAME); 32 | 33 | @Override 34 | public void sessionCreated(HttpSessionEvent httpSessionEvent) { 35 | 36 | if (httpSessionEvent.getSession().getAttribute(SSOAgentConstants.SESSION_BEAN_NAME) == null) { 37 | // This log is not accurate, since we depend on request.getSession() to create new session 38 | // if there is no existing session. After that only we set the Session-Bean. 39 | // Thus in this listener the session always does not contain a Session-Bean Attribute. 40 | LOGGER.log(Level.WARNING, "HTTP Session created without LoggedInSessionBean"); 41 | } 42 | } 43 | 44 | @Override 45 | public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { 46 | // No need to invalidate session here, as it is going to be invalidated soon 47 | SSOAgentSessionManager.invalidateSession(httpSessionEvent.getSession()); 48 | httpSessionEvent.getSession().removeAttribute(SSOAgentConstants.SESSION_BEAN_NAME); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/util/SSOAgentFilterUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.asgardeo.java.saml.sdk.util; 20 | 21 | import io.asgardeo.java.saml.sdk.bean.SSOAgentConfig; 22 | import io.asgardeo.java.saml.sdk.exception.SSOAgentException; 23 | 24 | import javax.servlet.FilterConfig; 25 | import javax.servlet.ServletContext; 26 | import javax.servlet.http.HttpServletRequest; 27 | 28 | /** 29 | * Comprised of Util methods for SSOAgentFilters. 30 | */ 31 | public class SSOAgentFilterUtils { 32 | 33 | public static SSOAgentConfig getSSOAgentConfig(FilterConfig filterConfig) throws SSOAgentException { 34 | 35 | return getSSOAgentConfig(filterConfig.getServletContext()); 36 | } 37 | 38 | public static SSOAgentConfig getSSOAgentConfig(ServletContext application) throws SSOAgentException { 39 | 40 | // Make sure SSOAgentConstants.CONFIG_BEAN_NAME attribute is added on servlet context initialization. 41 | // It should be in the type of SSOAgentConfig. 42 | Object configBeingAttribute = application.getAttribute(SSOAgentConstants.CONFIG_BEAN_NAME); 43 | if (!(configBeingAttribute instanceof SSOAgentConfig)) { 44 | throw new SSOAgentException("Cannot find " + SSOAgentConstants.CONFIG_BEAN_NAME + 45 | " attribute of SSOAgentConfig type in the servletContext. Cannot proceed further."); 46 | } 47 | 48 | return (SSOAgentConfig) configBeingAttribute; 49 | } 50 | 51 | public static boolean shouldGoToWelcomePage(HttpServletRequest request) { 52 | 53 | if (request == null) { 54 | return true; 55 | } 56 | 57 | //check should go to welcome page, if so go to welcome page 58 | Object shouldGoToWelcomePage = request.getAttribute(SSOAgentConstants.SHOULD_GO_TO_WELCOME_PAGE); 59 | return shouldGoToWelcomePage instanceof String && Boolean.parseBoolean((String) shouldGoToWelcomePage); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /pull_request_template.md: -------------------------------------------------------------------------------- 1 | ## Purpose 2 | > Describe the problems, issues, or needs driving this feature/fix and include links to related issues in the following format: Resolves issue1, issue2, etc. 3 | 4 | ## Goals 5 | > Describe the solutions that this feature/fix will introduce to resolve the problems described above 6 | 7 | ## Approach 8 | > Describe how you are implementing the solutions. Include an animated GIF or screenshot if the change affects the UI (email documentation@wso2.com to review all UI text). Include a link to a Markdown file or Google doc if the feature write-up is too long to paste here. 9 | 10 | ## User stories 11 | > Summary of user stories addressed by this change> 12 | 13 | ## Release note 14 | > Brief description of the new feature or bug fix as it will appear in the release notes 15 | 16 | ## Documentation 17 | > Link(s) to product documentation that addresses the changes of this PR. If no doc impact, enter “N/A” plus brief explanation of why there’s no doc impact 18 | 19 | ## Training 20 | > Link to the PR for changes to the training content in https://github.com/wso2/WSO2-Training, if applicable 21 | 22 | ## Certification 23 | > Type “Sent” when you have provided new/updated certification questions, plus four answers for each question (correct answer highlighted in bold), based on this change. Certification questions/answers should be sent to certification@wso2.com and NOT pasted in this PR. If there is no impact on certification exams, type “N/A” and explain why. 24 | 25 | ## Marketing 26 | > Link to drafts of marketing content that will describe and promote this feature, including product page changes, technical articles, blog posts, videos, etc., if applicable 27 | 28 | ## Automation tests 29 | - Unit tests 30 | > Code coverage information 31 | - Integration tests 32 | > Details about the test cases and coverage 33 | 34 | ## Security checks 35 | - Followed secure coding standards in http://wso2.com/technical-reports/wso2-secure-engineering-guidelines? yes/no 36 | - Ran FindSecurityBugs plugin and verified report? yes/no 37 | - Confirmed that this PR doesn't commit any keys, passwords, tokens, usernames, or other secrets? yes/no 38 | 39 | ## Samples 40 | > Provide high-level details about the samples related to this feature 41 | 42 | ## Related PRs 43 | > List any other related PRs 44 | 45 | ## Migrations (if applicable) 46 | > Describe migration steps and platforms on which migration has been tested 47 | 48 | ## Test environment 49 | > List all JDK versions, operating systems, databases, and browser/versions on which this feature/fix was tested 50 | 51 | ## Learning 52 | > Describe the research phase and any blog posts, patterns, libraries, or add-ons you used to solve the problem. -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Proposed changes in this pull request 2 | 3 | [List all changes you want to add here. If you fixed an issue, please 4 | add a reference to that issue as well.] 5 | 6 | - 7 | 8 | ### When should this PR be merged 9 | 10 | [Please describe any preconditions that need to be addressed before we 11 | can merge this pull request.] 12 | 13 | 14 | ### Follow up actions 15 | 16 | [List any possible follow-up actions here; for instance, testing data 17 | migrations, software that we need to install on staging and production 18 | environments.] 19 | 20 | - 21 | 22 | 23 | ### Checklist (for reviewing) 24 | 25 | #### General 26 | 27 | - [ ] **Is this PR explained thoroughly?** All code changes must be accounted for in the PR description. 28 | - [ ] **Is the PR labeled correctly?** 29 | 30 | #### Functionality 31 | 32 | - [ ] **Are all requirements met?** Compare implemented functionality with the requirements specification. 33 | - [ ] **Does the UI work as expected?** There should be no Javascript errors in the console; all resources should load. There should be no unexpected errors. Deliberately try to break the feature to find out if there are corner cases that are not handled. 34 | 35 | #### Code 36 | 37 | - [ ] **Do you fully understand the introduced changes to the code?** If not ask for clarification, it might uncover ways to solve a problem in a more elegant and efficient way. 38 | - [ ] **Does the PR introduce any inefficient database requests?** Use the debug server to check for duplicate requests. 39 | - [ ] **Are all necessary strings marked for translation?** All strings that are exposed to users via the UI must be [marked for translation](https://docs.djangoproject.com/en/1.10/topics/i18n/translation/). 40 | 41 | #### Tests 42 | 43 | - [ ] **Are there sufficient test cases?** Ensure that all components are tested individually; models, forms, and serializers should be tested in isolation even if a test for a view covers these components. 44 | - [ ] **If this is a bug fix, are tests for the issue in place?** There must be a test case for the bug to ensure the issue won’t regress. Make sure that the tests break without the new code to fix the issue. 45 | - [ ] **If this is a new feature or a significant change to an existing feature?** has the manual testing spreadsheet been updated with instructions for manual testing? 46 | 47 | #### Security 48 | 49 | - [ ] **Confirm this PR doesn't commit any keys, passwords, tokens, usernames, or other secrets.** 50 | - [ ] **Are all UI and API inputs run through forms or serializers?** 51 | - [ ] **Are all external inputs validated and sanitized appropriately?** 52 | - [ ] **Does all branching logic have a default case?** 53 | - [ ] **Does this solution handle outliers and edge cases gracefully?** 54 | - [ ] **Are all external communications secured and restricted to SSL?** 55 | 56 | #### Documentation 57 | 58 | - [ ] **Are changes to the UI documented in the platform docs?** If this PR introduces new platform site functionality or changes existing ones, the changes should be documented. 59 | - [ ] **Are changes to the API documented in the API docs?** If this PR introduces new API functionality or changes existing ones, the changes must be documented. 60 | - [ ] **Are reusable components documented?** If this PR introduces components that are relevant to other developers (for instance a mixin for a view or a generic form) they should be documented in the Wiki. 61 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/request/SAML2RequestDataHolder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.asgardeo.java.saml.sdk.request; 20 | 21 | import java.util.HashMap; 22 | import java.util.Map; 23 | 24 | /** 25 | * SAML2 request data holder. 26 | */ 27 | public class SAML2RequestDataHolder { 28 | 29 | private static final SAML2RequestDataHolder INSTANCE = new SAML2RequestDataHolder(); 30 | 31 | private final Map requestInfoMap = new HashMap<>(); 32 | 33 | private SAML2RequestDataHolder() { 34 | 35 | } 36 | 37 | /** 38 | * Get request data holder instance. 39 | * 40 | * @return instance of SAML2RequestDataHolder 41 | */ 42 | public static SAML2RequestDataHolder getInstance() { 43 | 44 | return INSTANCE; 45 | } 46 | 47 | /** 48 | * Add login request to the holder. 49 | * 50 | * @param requestId request id 51 | */ 52 | public void addLoginRequest(String requestId) { 53 | 54 | SAML2RequestInfo saml2RequestInfo = new SAML2RequestInfo(true, System.currentTimeMillis()); 55 | requestInfoMap.put(requestId, saml2RequestInfo); 56 | } 57 | 58 | /** 59 | * Add logout request to the holder. 60 | * 61 | * @param requestId request id 62 | */ 63 | public void addLogoutRequest(String requestId) { 64 | 65 | SAML2RequestInfo saml2RequestInfo = new SAML2RequestInfo(false, System.currentTimeMillis()); 66 | requestInfoMap.put(requestId, saml2RequestInfo); 67 | } 68 | 69 | /** 70 | * Check 'InResponseTo' value is valid. 71 | * 72 | * @param inResponseId InResponseTo value 73 | * @param isLoginRequest is this a login request 74 | * @return true if 'InResponseTo' value is valid 75 | */ 76 | public boolean isValidInResponseToId(String inResponseId, boolean isLoginRequest) { 77 | 78 | return requestInfoMap.containsKey(inResponseId) && (isLoginRequest == requestInfoMap.get(inResponseId) 79 | .isLoginRequest()); 80 | } 81 | 82 | /** 83 | * Remove request from holder. 84 | * 85 | * @param requestId request id 86 | */ 87 | public void removeRequestId(String requestId) { 88 | 89 | requestInfoMap.remove(requestId); 90 | } 91 | 92 | /** 93 | * Clean idle requests from the holder. 94 | * 95 | * @param idleTimeOutInMinutes idle time out in minutes 96 | */ 97 | public void cleanIdleRequests(int idleTimeOutInMinutes) { 98 | 99 | long margin = System.currentTimeMillis() - ((long) idleTimeOutInMinutes * 60 * 1000); 100 | requestInfoMap.entrySet().removeIf(entry -> entry.getValue().getInitiatedTime() < margin); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/util/SSOAgentRequestResolver.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | * 18 | * 19 | */ 20 | 21 | package io.asgardeo.java.saml.sdk.util; 22 | 23 | import org.opensaml.saml.common.xml.SAMLConstants; 24 | import io.asgardeo.java.saml.sdk.bean.SSOAgentConfig; 25 | 26 | import javax.servlet.http.HttpServletRequest; 27 | import javax.servlet.http.HttpServletResponse; 28 | 29 | public class SSOAgentRequestResolver { 30 | 31 | SSOAgentConfig ssoAgentConfig = null; 32 | HttpServletRequest request = null; 33 | 34 | public SSOAgentRequestResolver(HttpServletRequest request, HttpServletResponse response, 35 | SSOAgentConfig ssoAgentConfig) { 36 | 37 | this.request = request; 38 | this.ssoAgentConfig = ssoAgentConfig; 39 | } 40 | 41 | public boolean isSLORequest() { 42 | 43 | return ssoAgentConfig.isSAML2SSOLoginEnabled() && 44 | request.getParameter(SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_AUTH_REQ) != null; 45 | } 46 | 47 | // This could be either SAML Response for a SSO SAML Request by the client application 48 | // or a SAML Response for a SLO SAML Request from a SP 49 | public boolean isSAML2SSOResponse() { 50 | 51 | return ssoAgentConfig.isSAML2SSOLoginEnabled() && 52 | request.getParameter(SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_RESP) != null; 53 | } 54 | 55 | public boolean isSAML2ArtifactResponse() { 56 | 57 | return ssoAgentConfig.isSAML2SSOLoginEnabled() && 58 | request.getParameter(SSOAgentConstants.SAML2SSO.SAML2_ARTIFACT_RESP) != null; 59 | } 60 | 61 | public boolean isSLOURL() { 62 | 63 | return ssoAgentConfig.isSAML2SSOLoginEnabled() && 64 | ssoAgentConfig.getSAML2().isSLOEnabled() && 65 | request.getRequestURI().endsWith(ssoAgentConfig.getSAML2().getSLOURL()); 66 | } 67 | 68 | public boolean isHttpPostBinding() { 69 | 70 | return ssoAgentConfig.getSAML2().getHttpBinding() != null && 71 | SAMLConstants.SAML2_POST_BINDING_URI.equals( 72 | ssoAgentConfig.getSAML2().getHttpBinding()); 73 | } 74 | 75 | public boolean isSAML2SSOURL() { 76 | 77 | return ssoAgentConfig.isSAML2SSOLoginEnabled() && 78 | request.getRequestURI().endsWith(ssoAgentConfig.getSAML2SSOURL()); 79 | } 80 | 81 | public boolean isPassiveAuthnRequest() { 82 | 83 | return (ssoAgentConfig.isSAML2SSOLoginEnabled() && 84 | (request.getSession(false) == null || 85 | request.getSession(false).getAttribute(SSOAgentConstants.SESSION_BEAN_NAME) == null)); 86 | } 87 | 88 | public boolean isURLToSkip() { 89 | 90 | return ssoAgentConfig.getSkipURIs().contains(request.getRequestURI()); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/AESDecryptor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.asgardeo.java.saml.sdk; 20 | 21 | import org.apache.commons.codec.binary.Base64; 22 | import org.bouncycastle.crypto.digests.SHA256Digest; 23 | import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator; 24 | import org.bouncycastle.crypto.params.KeyParameter; 25 | import io.asgardeo.java.saml.sdk.exception.SSOAgentException; 26 | 27 | import java.nio.ByteBuffer; 28 | import java.nio.CharBuffer; 29 | import java.nio.charset.StandardCharsets; 30 | 31 | import javax.crypto.Cipher; 32 | import javax.crypto.SecretKey; 33 | import javax.crypto.spec.IvParameterSpec; 34 | import javax.crypto.spec.SecretKeySpec; 35 | 36 | /** 37 | * Class for decrypt the encrypted values using AES algorithm. 38 | */ 39 | public class AESDecryptor { 40 | 41 | private static final String ALGORITHM = "AES/CBC/PKCS5Padding"; 42 | private static final String SALT = "84B03D034B409D4E"; 43 | private static final int KEY_DERIVATION_ITERATION_COUNT = 4096; 44 | private static final int KEY_SIZE = 128; 45 | 46 | /** 47 | * Decrypt and decrypt the encrypted values. 48 | * 49 | * @param encryptedSecret encrypted value. 50 | * @param cipherKey password used for encryption. 51 | * @return 52 | * @throws SSOAgentException If an error occurred. 53 | */ 54 | public static String decrypt(String encryptedSecret, char[] cipherKey) throws SSOAgentException { 55 | 56 | try { 57 | 58 | // Change char array to byte array. 59 | ByteBuffer buf = StandardCharsets.UTF_8.encode(CharBuffer.wrap(cipherKey)); 60 | byte[] secretKey = new byte[buf.limit()]; 61 | buf.get(secretKey); 62 | 63 | PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest()); 64 | gen.init(secretKey, SALT.getBytes(StandardCharsets.UTF_8), KEY_DERIVATION_ITERATION_COUNT); 65 | byte[] dk = ((KeyParameter) gen.generateDerivedParameters(KEY_SIZE)).getKey(); 66 | 67 | SecretKey key = new SecretKeySpec(dk, "AES"); 68 | Cipher cipher = Cipher.getInstance(ALGORITHM); 69 | 70 | // Create an initialization vector with Cipher's block size. 71 | byte[] iv = new byte[cipher.getBlockSize()]; 72 | IvParameterSpec ivParams = new IvParameterSpec(iv); 73 | cipher.init(Cipher.DECRYPT_MODE, key, ivParams); 74 | 75 | // Decode the encrypted value. 76 | byte[] decodedValue = new Base64().decode(encryptedSecret.getBytes(StandardCharsets.UTF_8)); 77 | 78 | // Decrypt the encrypted value and get the plain text password. 79 | byte[] decryptedValue = cipher.doFinal(decodedValue); 80 | return new String(decryptedValue, StandardCharsets.UTF_8); 81 | } catch (Exception ex) { 82 | throw new SSOAgentException("Error while decoding the encrypted value.", ex); 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/security/X509CredentialImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | * 18 | * 19 | */ 20 | 21 | package io.asgardeo.java.saml.sdk.security; 22 | 23 | import io.asgardeo.java.saml.sdk.exception.SSOAgentException; 24 | import org.opensaml.security.credential.Credential; 25 | import org.opensaml.security.credential.CredentialContextSet; 26 | import org.opensaml.security.credential.UsageType; 27 | import org.opensaml.security.x509.X509Credential; 28 | 29 | import java.security.PrivateKey; 30 | import java.security.PublicKey; 31 | import java.security.cert.X509CRL; 32 | import java.security.cert.X509Certificate; 33 | import java.util.ArrayList; 34 | import java.util.Collection; 35 | 36 | import javax.crypto.SecretKey; 37 | 38 | /** 39 | * X509Credential implementation for signing and verification. 40 | */ 41 | public class X509CredentialImpl implements X509Credential { 42 | 43 | private PublicKey publicKey = null; 44 | private X509Certificate entityCertificate = null; 45 | private PrivateKey privateKey = null; 46 | 47 | public X509CredentialImpl(SSOAgentX509Credential credential) throws SSOAgentException { 48 | 49 | publicKey = credential.getPublicKey(); 50 | this.entityCertificate = credential.getEntityCertificate(); 51 | this.privateKey = credential.getPrivateKey(); 52 | } 53 | 54 | /** 55 | * Retrieves the publicKey 56 | */ 57 | @Override 58 | public PublicKey getPublicKey() { 59 | 60 | return publicKey; 61 | } 62 | 63 | @Override 64 | public PrivateKey getPrivateKey() { 65 | 66 | return privateKey; 67 | } 68 | 69 | @Override 70 | public X509Certificate getEntityCertificate() { 71 | 72 | return entityCertificate; 73 | } 74 | 75 | // ********** Not implemented ************************************************************** 76 | 77 | @Override 78 | public Collection getCRLs() { 79 | 80 | return new ArrayList(); 81 | } 82 | 83 | @Override 84 | public Collection getEntityCertificateChain() { 85 | 86 | return new ArrayList(); 87 | } 88 | 89 | /*** 90 | * Get the credential context set. 91 | * @return This method is not supported so the return is null. 92 | */ 93 | @Override 94 | public CredentialContextSet getCredentialContextSet() { 95 | 96 | return null; 97 | } 98 | 99 | @Override 100 | public Class getCredentialType() { 101 | 102 | return null; 103 | } 104 | 105 | @Override 106 | public String getEntityId() { 107 | 108 | return null; 109 | } 110 | 111 | @Override 112 | public Collection getKeyNames() { 113 | 114 | return new ArrayList(); 115 | } 116 | 117 | @Override 118 | public SecretKey getSecretKey() { 119 | 120 | return null; 121 | } 122 | 123 | @Override 124 | public UsageType getUsageType() { 125 | 126 | return null; 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/session/management/SSOAgentSessionManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.asgardeo.java.saml.sdk.session.management; 20 | 21 | import io.asgardeo.java.saml.sdk.bean.LoggedInSessionBean; 22 | import io.asgardeo.java.saml.sdk.util.SSOAgentConstants; 23 | 24 | import java.util.HashMap; 25 | import java.util.HashSet; 26 | import java.util.Map; 27 | import java.util.Set; 28 | 29 | import javax.servlet.http.HttpSession; 30 | 31 | public class SSOAgentSessionManager { 32 | 33 | /* 34 | * Session Index at the IdP is mapped to the session at the SP so that a single logout request 35 | * can be handled by invalidating the SP session mapped to IdP Session Index. 36 | */ 37 | private static Map> ssoSessionsMap = 38 | new HashMap>(); 39 | 40 | private SSOAgentSessionManager() { 41 | 42 | } 43 | 44 | public static void invalidateSession(HttpSession session) { 45 | 46 | LoggedInSessionBean sessionBean = (LoggedInSessionBean) session.getAttribute( 47 | SSOAgentConstants.SESSION_BEAN_NAME); 48 | if (sessionBean != null && sessionBean.getSAML2SSO() != null) { 49 | String sessionIndex = sessionBean.getSAML2SSO().getSessionIndex(); 50 | if (sessionIndex != null) { 51 | Set sessions = ssoSessionsMap.get(sessionIndex); 52 | if (sessions != null) { 53 | sessions.remove(session); 54 | } 55 | } 56 | } 57 | } 58 | 59 | public static Set invalidateAllSessions(HttpSession session) { 60 | 61 | LoggedInSessionBean sessionBean = (LoggedInSessionBean) session.getAttribute( 62 | SSOAgentConstants.SESSION_BEAN_NAME); 63 | Set sessions = new HashSet(); 64 | if (sessionBean != null && sessionBean.getSAML2SSO() != null) { 65 | String sessionIndex = sessionBean.getSAML2SSO().getSessionIndex(); 66 | if (sessionIndex != null) { 67 | sessions = ssoSessionsMap.remove(sessionIndex); 68 | } 69 | } 70 | if (sessions == null) { 71 | sessions = new HashSet(); 72 | } 73 | return sessions; 74 | } 75 | 76 | public static Set invalidateAllSessions(String sessionIndex) { 77 | 78 | Set sessions = ssoSessionsMap.remove(sessionIndex); 79 | if (sessions == null) { 80 | sessions = new HashSet(); 81 | } 82 | return sessions; 83 | } 84 | 85 | public static void addAuthenticatedSession(HttpSession session) { 86 | 87 | String sessionIndex = ((LoggedInSessionBean) session.getAttribute( 88 | SSOAgentConstants.SESSION_BEAN_NAME)).getSAML2SSO().getSessionIndex(); 89 | if (ssoSessionsMap.get(sessionIndex) != null) { 90 | ssoSessionsMap.get(sessionIndex).add(session); 91 | } else { 92 | Set sessions = new HashSet(); 93 | sessions.add(session); 94 | ssoSessionsMap.put(sessionIndex, sessions); 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Asgardeo SAML SDK for Java 2 | 3 | [![Build Status](https://img.shields.io/jenkins/build?jobUrl=https%3A%2F%2Fwso2.org%2Fjenkins%2Fjob%2Fasgardeo%2Fjob%2Fasgardeo-java-saml-sdk%2F&style=flat)](https://wso2.org/jenkins/job/asgardeo/job/asgardeo-java-saml-sdk/) 4 | [![Stackoverflow](https://img.shields.io/badge/Ask%20for%20help%20on-Stackoverflow-orange)](https://stackoverflow.com/questions/tagged/asgardeo) 5 | [![Discord](https://img.shields.io/badge/Join%20us%20on-Discord-%23e01563.svg)](https://discord.gg/wso2) 6 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/asgardeo/asgardeo-java-saml-sdk/blob/master/LICENSE) 7 | [![Twitter](https://img.shields.io/twitter/follow/wso2.svg?style=social&label=Follow)](https://twitter.com/intent/follow?screen_name=asgardeo) 8 | --- 9 | 10 | The Asgardeo SAML SDK for Java enables software developers to integrate SAML based SSO authentication with Java Web 11 | applications. The SDK is built on top of the OpenSAML library which allows Java developers to develop cross-domain 12 | single sign-on and federated access control solutions with minimum hassle. 13 | 14 | ## Table of Contents 15 | - [Installing the SDK](#installing-the-sdk) 16 | * [Github](#github) 17 | * [Building from the source](#building-from-the-source) 18 | * [Maven](#maven) 19 | - [Contributing](#contributing) 20 | * [Reporting Issues](#reporting-issues) 21 | - [Versioning](#versioning) 22 | - [License](#license) 23 | 24 | ## Installing the SDK 25 | 26 | ### Github 27 | The SDK is hosted on github. You can download it from: 28 | - Latest release: https://github.com/asgardeo/asgardeo-java-saml-sdk/releases/latest 29 | - Master repo: https://github.com/asgardeo/asgardeo-java-saml-sdk/tree/master/ 30 | 31 | ### Building from the source 32 | 33 | If you want to build **identity-agent-sso** from the source code: 34 | 35 | 1. Install Java 8 36 | 2. Install Apache Maven 3.x.x (https://maven.apache.org/download.cgi#) 37 | 3. Get a clone or download the source from this repository (https://github.com/asgardeo/asgardeo-java-saml-sdk.git) 38 | 4. Run the Maven command ``mvn clean install`` from the ``asgardeo-java-saml-sdk`` directory. 39 | 40 | ### Maven 41 | 42 | Install it as a maven dependency: 43 | ``` 44 | 45 | io.asgardeo.java.saml.sdk 46 | io.asgardeo.java.saml.sdk 47 | 0.1.19 48 | 49 | ``` 50 | The SDK is hosted at the WSO2 Internal Repository. Point to the repository as follows: 51 | 52 | 53 | ``` 54 | 55 | 56 | wso2.releases 57 | WSO2 internal Repository 58 | http://maven.wso2.org/nexus/content/repositories/releases/ 59 | 60 | true 61 | daily 62 | ignore 63 | 64 | 65 | 66 | ``` 67 | 68 | ## Contributing 69 | 70 | Please read [Contributing to the Code Base](http://wso2.github.io/) for details on our code of conduct, and the 71 | process for submitting pull requests to us. 72 | 73 | ### Reporting Issues 74 | We encourage you to report issues, improvements, and feature requests creating [git Issues](https://github.com/wso2-extensions/identity-samples-dotnet/issues). 75 | 76 | Important: And please be advised that security issues must be reported to security@wso2.com, not as GitHub issues, 77 | in order to reach the proper audience. We strongly advise following the WSO2 Security Vulnerability Reporting Guidelines 78 | when reporting the security issues. 79 | 80 | ## Versioning 81 | 82 | For the versions available, see the [tags on this repository](https://github.com/asgardeo/asgardeo-java-saml-sdk/tags). 83 | 84 | ## License 85 | 86 | This project is licensed under the Apache License 2.0 under which WSO2 Carbon is distributed. See the [LICENSE 87 | ](LICENSE) file for details. 88 | 89 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/security/SSOAgentKeyStoreCredential.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | * 18 | * 19 | */ 20 | 21 | package io.asgardeo.java.saml.sdk.security; 22 | 23 | import io.asgardeo.java.saml.sdk.exception.SSOAgentException; 24 | import io.asgardeo.java.saml.sdk.util.SSOAgentConfigs; 25 | 26 | import java.security.KeyStore; 27 | import java.security.KeyStoreException; 28 | import java.security.NoSuchAlgorithmException; 29 | import java.security.PrivateKey; 30 | import java.security.PublicKey; 31 | import java.security.UnrecoverableKeyException; 32 | import java.security.cert.X509Certificate; 33 | 34 | public class SSOAgentKeyStoreCredential implements SSOAgentCredential { 35 | 36 | private static PublicKey publicKey = null; 37 | private static PrivateKey privateKey = null; 38 | private static X509Certificate entityCertificate = null; 39 | 40 | private static void readX509Credentials() throws SSOAgentException { 41 | 42 | String privateKeyAlias = SSOAgentConfigs.getPrivateKeyAlias(); 43 | String privateKeyPassword = SSOAgentConfigs.getPrivateKeyPassword(); 44 | String idpCertAlias = SSOAgentConfigs.getIdPCertAlias(); 45 | 46 | KeyStore keyStore = SSOAgentConfigs.getKeyStore(); 47 | X509Certificate cert = null; 48 | PrivateKey privateKey = null; 49 | 50 | try { 51 | 52 | if (privateKeyAlias != null && SSOAgentConfigs.isRequestSigned()) { 53 | privateKey = (PrivateKey) keyStore.getKey(privateKeyAlias, privateKeyPassword.toCharArray()); 54 | 55 | if (privateKey == null) { 56 | throw new SSOAgentException( 57 | "RequestSigning is enabled, but cannot find private key with the alias " + 58 | privateKeyAlias + " in the key store"); 59 | } 60 | } 61 | 62 | cert = (X509Certificate) keyStore.getCertificate(idpCertAlias); 63 | if (cert == null) { 64 | throw new SSOAgentException( 65 | "Cannot find IDP certificate with the alias " + idpCertAlias + " in the trust store"); 66 | } 67 | } catch (KeyStoreException e) { 68 | throw new SSOAgentException("Error when reading keystore", e); 69 | } catch (UnrecoverableKeyException e) { 70 | throw new SSOAgentException("Error when reading keystore", e); 71 | } catch (NoSuchAlgorithmException e) { 72 | throw new SSOAgentException("Error when reading keystore", e); 73 | } 74 | 75 | publicKey = cert.getPublicKey(); 76 | SSOAgentKeyStoreCredential.privateKey = privateKey; 77 | entityCertificate = cert; 78 | } 79 | 80 | @Override 81 | public void init() throws SSOAgentException { 82 | 83 | readX509Credentials(); 84 | } 85 | 86 | @Override 87 | public PublicKey getPublicKey() { 88 | 89 | return publicKey; 90 | } 91 | 92 | @Override 93 | public PrivateKey getPrivateKey() { 94 | 95 | return privateKey; 96 | } 97 | 98 | @Override 99 | public X509Certificate getEntityCertificate() { 100 | 101 | return entityCertificate; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 21 | 22 | 23 | 24 | io.asgardeo.java.saml.sdk 25 | java-saml-sdk 26 | ../pom.xml 27 | 0.1.20-SNAPSHOT 28 | 29 | 30 | 4.0.0 31 | io.asgardeo.java.saml.sdk 32 | jar 33 | Asgardeo - Java SAML SDK 34 | http://asgardeo.io 35 | 36 | 37 | 38 | org.opensaml 39 | opensaml-core 40 | 41 | 42 | org.opensaml 43 | opensaml-saml-impl 44 | 45 | 46 | org.bouncycastle 47 | bcprov-jdk15on 48 | 49 | 50 | javax.servlet 51 | javax.servlet-api 52 | 53 | 54 | com.google.code.gson 55 | gson 56 | 57 | 58 | org.apache.felix 59 | org.apache.felix.scr.ds-annotations 60 | 61 | 62 | commons-lang 63 | commons-lang 64 | 65 | 66 | xerces 67 | xercesImpl 68 | 69 | 70 | org.apache.httpcomponents 71 | httpclient 72 | 73 | 74 | org.owasp.encoder 75 | encoder 76 | 77 | 78 | commons-collections 79 | commons-collections 80 | 81 | 82 | org.jacoco 83 | jacoco-maven-plugin 84 | ${jacoco.version} 85 | 86 | 87 | 88 | 89 | src/main/java 90 | 91 | 92 | org.apache.maven.plugins 93 | maven-compiler-plugin 94 | 2.0 95 | 96 | 1.8 97 | 1.8 98 | 99 | 100 | 101 | org.jacoco 102 | jacoco-maven-plugin 103 | ${jacoco.version} 104 | 105 | 106 | 107 | prepare-agent 108 | 109 | 110 | 111 | report 112 | test 113 | 114 | report 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/bean/SSOAgentSessionBean.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | * 18 | * 19 | */ 20 | 21 | package io.asgardeo.java.saml.sdk.bean; 22 | 23 | import com.google.gson.Gson; 24 | import org.opensaml.saml.saml2.core.Assertion; 25 | import org.opensaml.saml.saml2.core.Response; 26 | 27 | import java.util.Map; 28 | 29 | public class SSOAgentSessionBean { 30 | 31 | private SAMLSSOSessionBean samlssoSessionBean; 32 | 33 | public SAMLSSOSessionBean getSAMLSSOSessionBean() { 34 | 35 | return samlssoSessionBean; 36 | } 37 | 38 | public void setSAMLSSOSessionBean(SAMLSSOSessionBean samlssoSessionBean) { 39 | 40 | this.samlssoSessionBean = samlssoSessionBean; 41 | } 42 | 43 | public static class AccessTokenResponseBean { 44 | 45 | private String access_token; 46 | 47 | private String refresh_token; 48 | 49 | private String token_type; 50 | 51 | private String expires_in; 52 | 53 | public String getAccess_token() { 54 | 55 | return access_token; 56 | } 57 | 58 | public void setAccess_token(String access_token) { 59 | 60 | this.access_token = access_token; 61 | } 62 | 63 | public String getRefresh_token() { 64 | 65 | return refresh_token; 66 | } 67 | 68 | public void setRefresh_token(String refresh_token) { 69 | 70 | this.refresh_token = refresh_token; 71 | } 72 | 73 | public String getToken_type() { 74 | 75 | return token_type; 76 | } 77 | 78 | public void setToken_type(String token_type) { 79 | 80 | this.token_type = token_type; 81 | } 82 | 83 | public String getExpires_in() { 84 | 85 | return expires_in; 86 | } 87 | 88 | public void setExpires_in(String expires_in) { 89 | 90 | this.expires_in = expires_in; 91 | } 92 | 93 | @Override 94 | public String toString() { 95 | 96 | Gson gson = new Gson(); 97 | return gson.toJson(this); 98 | } 99 | } 100 | 101 | public class SAMLSSOSessionBean { 102 | 103 | private String subjectId; 104 | 105 | private Response samlResponse; 106 | 107 | private String samlResponseString; 108 | 109 | private Assertion samlAssertion; 110 | 111 | private String samlAssertionString; 112 | 113 | private AccessTokenResponseBean accessTokenResponseBean; 114 | 115 | private String idPSessionIndex; 116 | 117 | private Map samlSSOAttributes; 118 | 119 | public String getSubjectId() { 120 | 121 | return subjectId; 122 | } 123 | 124 | public void setSubjectId(String subjectId) { 125 | 126 | this.subjectId = subjectId; 127 | } 128 | 129 | public Map getSAMLSSOAttributes() { 130 | 131 | return samlSSOAttributes; 132 | } 133 | 134 | public void setSAMLSSOAttributes(Map samlSSOAttributes) { 135 | 136 | this.samlSSOAttributes = samlSSOAttributes; 137 | } 138 | 139 | public String getIdPSessionIndex() { 140 | 141 | return idPSessionIndex; 142 | } 143 | 144 | public void setIdPSessionIndex(String idPSessionIndex) { 145 | 146 | this.idPSessionIndex = idPSessionIndex; 147 | } 148 | 149 | public Response getSAMLResponse() { 150 | 151 | return samlResponse; 152 | } 153 | 154 | public void setSAMLResponse(Response samlResponse) { 155 | 156 | this.samlResponse = samlResponse; 157 | } 158 | 159 | public String getSAMLResponseString() { 160 | 161 | return samlResponseString; 162 | } 163 | 164 | public void setSAMLResponseString(String samlResponseString) { 165 | 166 | this.samlResponseString = samlResponseString; 167 | } 168 | 169 | public Assertion getSAMLAssertion() { 170 | 171 | return samlAssertion; 172 | } 173 | 174 | public void setSAMLAssertion(Assertion samlAssertion) { 175 | 176 | this.samlAssertion = samlAssertion; 177 | } 178 | 179 | public String getSAMLAssertionString() { 180 | 181 | return samlAssertionString; 182 | } 183 | 184 | public void setSAMLAssertionString(String samlAssertionString) { 185 | 186 | this.samlAssertionString = samlAssertionString; 187 | } 188 | 189 | public AccessTokenResponseBean getAccessTokenResponseBean() { 190 | 191 | return accessTokenResponseBean; 192 | } 193 | 194 | public void setAccessTokenResponseBean(AccessTokenResponseBean accessTokenResponseBean) { 195 | 196 | this.accessTokenResponseBean = accessTokenResponseBean; 197 | } 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/util/SSOAgentConstants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.asgardeo.java.saml.sdk.util; 20 | 21 | public class SSOAgentConstants { 22 | 23 | public static final String KEY_STORE_PASSWORD = "KeyStorePassword"; 24 | public static final String IDP_PUBLIC_CERT_ALIAS = "IdPPublicCertAlias"; 25 | public static final String IDP_PUBLIC_CERT = "IdPPublicCert"; 26 | public static final String PRIVATE_KEY_ALIAS = "PrivateKeyAlias"; 27 | public static final String PRIVATE_KEY_PASSWORD = "PrivateKeyPassword"; 28 | public static final String KEYSTORE = "KeyStore"; 29 | public static final String IDLE_TIME_OUT_IN_MINUTES = "IdleTimeOutInMinutes"; 30 | 31 | public static final String LOGGER_NAME = "org.wso2.carbon.identity.sso.agent"; 32 | 33 | public static final String SESSION_BEAN_NAME = "org.wso2.carbon.identity.sso.agent.LoggedInSessionBean"; 34 | public static final String CONFIG_BEAN_NAME = "org.wso2.carbon.identity.sso.agent.SSOAgentConfig"; 35 | 36 | public static final String SHOULD_GO_TO_WELCOME_PAGE = "shouldGoToWelcomePage"; 37 | public static final String SSO_AGENT_EXCEPTION = "SSOAgentException"; 38 | public static final String PROPERTY_FILE_PARAMETER_NAME = "property-file"; 39 | public static final String CERTIFICATE_FILE_PARAMETER_NAME = "certificate-file"; 40 | public static final String POST_BINDING_REQUEST_PAGE_PARAMETER_NAME = "post-binding-request-page"; 41 | 42 | private SSOAgentConstants() { 43 | 44 | } 45 | 46 | public static class SAML2SSO { 47 | 48 | public static final String HTTP_POST_PARAM_SAML2_AUTH_REQ = "SAMLRequest"; 49 | public static final String HTTP_POST_PARAM_SAML2_RESP = "SAMLResponse"; 50 | public static final String SAML2_ARTIFACT_RESP = "SAMLart"; 51 | public static final String SUCCESS_CODE = "urn:oasis:names:tc:SAML:2.0:status:Success"; 52 | public static final String ID_ATTRIB_LIST_NAME = "SAML2RequestIDs"; 53 | private SAML2SSO() { 54 | 55 | } 56 | } 57 | 58 | public static class SSOAgentConfig { 59 | 60 | public static final String ENABLE_SAML2_SSO_LOGIN = "EnableSAML2SSOLogin"; 61 | public static final String SAML2_SSO_URL = "SAML2SSOURL"; 62 | public static final String SKIP_URIS = "SkipURIs"; 63 | public static final String QUERY_PARAMS = "QueryParams"; 64 | public static final String PASSWORD_FILEPATH = "/conf/password_temp.txt"; 65 | public static final String INDEX_PAGE = "IndexPage"; 66 | public static final String ERROR_PAGE = "ErrorPage"; 67 | 68 | private SSOAgentConfig() { 69 | 70 | } 71 | 72 | public static class SAML2 { 73 | 74 | public static final String HTTP_BINDING = "SAML2.HTTPBinding"; 75 | public static final String SP_ENTITY_ID = "SAML2.SPEntityId"; 76 | public static final String ACS_URL = "SAML2.AssertionConsumerURL"; 77 | public static final String IDP_ENTITY_ID = "SAML2.IdPEntityId"; 78 | public static final String IDP_URL = "SAML2.IdPURL"; 79 | public static final String ATTRIBUTE_CONSUMING_SERVICE_INDEX = 80 | "SAML2.AttributeConsumingServiceIndex"; 81 | public static final String ENABLE_SLO = "SAML2.EnableSLO"; 82 | public static final String SLO_URL = "SAML2.SLOURL"; 83 | public static final String ENABLE_ASSERTION_SIGNING = 84 | "SAML2.EnableAssertionSigning"; 85 | public static final String ENABLE_ASSERTION_ENCRYPTION = 86 | "SAML2.EnableAssertionEncryption"; 87 | public static final String ENABLE_RESPONSE_SIGNING = 88 | "SAML2.EnableResponseSigning"; 89 | public static final String ENABLE_REQUEST_SIGNING = "SAML2.EnableRequestSigning"; 90 | public static final String IS_PASSIVE_AUTHN = "SAML2.IsPassiveAuthn"; 91 | public static final String IS_FORCE_AUTHN = "SAML2.IsForceAuthn"; 92 | public static final String RELAY_STATE = "SAML2.RelayState"; 93 | public static final String POST_BINDING_REQUEST_HTML_PAYLOAD = 94 | "SAML2.PostBindingRequestHTMLPayload"; 95 | public static final String POST_BINDING_REQUEST_HTML_FILE_PATH = 96 | "SAML2.PostBindingRequestHTMLFilePath"; 97 | public static final String SIGNATURE_VALIDATOR = "SAML2.SignatureValidatorImplClass"; 98 | public static final String TIME_STAMP_SKEW = "SAML2.TimestampSkew"; 99 | 100 | public static final String SOAP_ACTION_PARAM_KEY = "SOAPAction"; 101 | public static final String ACCEPT_PARAM_KEY = "Accept"; 102 | public static final String CONTENT_TYPE_PARAM_KEY = "Content-Type"; 103 | public static final String PRAGMA_PARAM_KEY = "Pragma"; 104 | public static final String CACHE_CONTROL_PARAM_KEY = "Cache-Control"; 105 | public static final String IS_ARTIFACT_RESOLVE_REQ_SIGNED = "ISArtifactResolveReqSigned"; 106 | public static final String ARTIFACT_RESOLVE_URL = "SAML2.ArtifactResolveUrl"; 107 | public static final String ENABLE_ARTIFACT_RESOLVE_SIGNING = "SAML2.EnableArtifactResolveSigning"; 108 | 109 | private SAML2() { 110 | 111 | } 112 | } 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/security/SSOAgentX509KeyStoreCredential.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | * 18 | * 19 | */ 20 | 21 | package io.asgardeo.java.saml.sdk.security; 22 | 23 | import io.asgardeo.java.saml.sdk.exception.SSOAgentException; 24 | import org.apache.commons.lang.StringUtils; 25 | import org.apache.commons.logging.Log; 26 | import org.apache.commons.logging.LogFactory; 27 | 28 | import java.io.ByteArrayInputStream; 29 | import java.io.IOException; 30 | import java.io.InputStream; 31 | import java.security.KeyStore; 32 | import java.security.KeyStoreException; 33 | import java.security.NoSuchAlgorithmException; 34 | import java.security.PrivateKey; 35 | import java.security.PublicKey; 36 | import java.security.UnrecoverableKeyException; 37 | import java.security.cert.CertificateException; 38 | import java.security.cert.CertificateFactory; 39 | import java.security.cert.X509Certificate; 40 | import java.util.Base64; 41 | 42 | public class SSOAgentX509KeyStoreCredential implements SSOAgentX509Credential { 43 | 44 | private static final Log log = LogFactory.getLog(SSOAgentX509KeyStoreCredential.class); 45 | private PublicKey publicKey = null; 46 | private PrivateKey privateKey = null; 47 | private X509Certificate entityCertificate = null; 48 | 49 | public SSOAgentX509KeyStoreCredential(KeyStore keyStore, String publicCertAlias, 50 | String privateKeyAlias, char[] privateKeyPassword) 51 | throws SSOAgentException { 52 | 53 | this(keyStore, publicCertAlias, null, privateKeyAlias, privateKeyPassword); 54 | } 55 | 56 | public SSOAgentX509KeyStoreCredential(InputStream keyStoreInputStream, char[] keyStorePassword, 57 | String publicCertAlias, String privateKeyAlias, 58 | char[] privateKeyPassword) 59 | throws SSOAgentException { 60 | 61 | this(keyStoreInputStream, keyStorePassword, publicCertAlias, null, privateKeyAlias, 62 | privateKeyPassword); 63 | } 64 | 65 | public SSOAgentX509KeyStoreCredential(KeyStore keyStore, String publicCertAlias, String publicCertEncoded, 66 | String privateKeyAlias, char[] privateKeyPassword) 67 | throws SSOAgentException { 68 | 69 | readX509Credentials(keyStore, publicCertAlias, publicCertEncoded, privateKeyAlias, privateKeyPassword); 70 | } 71 | 72 | public SSOAgentX509KeyStoreCredential(InputStream keyStoreInputStream, char[] keyStorePassword, 73 | String publicCertAlias, String publicCertEncoded, String privateKeyAlias, 74 | char[] privateKeyPassword) 75 | throws SSOAgentException { 76 | 77 | readX509Credentials(keyStoreInputStream, keyStorePassword, publicCertAlias, publicCertEncoded, 78 | privateKeyAlias, privateKeyPassword); 79 | } 80 | 81 | @Override 82 | public PublicKey getPublicKey() throws SSOAgentException { 83 | 84 | return publicKey; 85 | } 86 | 87 | @Override 88 | public PrivateKey getPrivateKey() throws SSOAgentException { 89 | 90 | return privateKey; 91 | } 92 | 93 | @Override 94 | public X509Certificate getEntityCertificate() throws SSOAgentException { 95 | 96 | return entityCertificate; 97 | } 98 | 99 | protected void readX509Credentials(KeyStore keyStore, String publicCertAlias, String publicCertEncoded, 100 | String privateKeyAlias, char[] privateKeyPassword) 101 | throws SSOAgentException { 102 | 103 | try { 104 | if (StringUtils.isNotEmpty(publicCertEncoded)) { 105 | entityCertificate = inferPublicCertFromEncodedString(publicCertEncoded); 106 | } else if (StringUtils.isNotEmpty(publicCertAlias)) { 107 | entityCertificate = (X509Certificate) keyStore.getCertificate(publicCertAlias); 108 | } 109 | } catch (KeyStoreException e) { 110 | throw new SSOAgentException( 111 | "Error occurred while retrieving public certificate for alias " + 112 | publicCertAlias, e); 113 | } catch (CertificateException e) { 114 | throw new SSOAgentException( 115 | "Error occurred while inferring public certificate from encoded string ", e); 116 | } 117 | publicKey = entityCertificate.getPublicKey(); 118 | try { 119 | privateKey = (PrivateKey) keyStore.getKey(privateKeyAlias, privateKeyPassword); 120 | } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) { 121 | throw new SSOAgentException( 122 | "Error occurred while retrieving private key for alias " + 123 | privateKeyAlias, e); 124 | } 125 | } 126 | 127 | private X509Certificate inferPublicCertFromEncodedString(String encodedCert) throws CertificateException { 128 | 129 | byte[] decoded = Base64.getDecoder().decode(encodedCert); 130 | return (X509Certificate) CertificateFactory.getInstance("X.509") 131 | .generateCertificate(new ByteArrayInputStream(decoded)); 132 | } 133 | 134 | protected void readX509Credentials(InputStream keyStoreInputStream, char[] keyStorePassword, 135 | String publicCertAlias, String publicCertEncoded, String privateKeyAlias, 136 | char[] privateKeyPassword) 137 | throws SSOAgentException { 138 | 139 | try { 140 | KeyStore keyStore = KeyStore.getInstance("JKS"); 141 | keyStore.load(keyStoreInputStream, keyStorePassword); 142 | readX509Credentials(keyStore, publicCertAlias, publicCertEncoded, privateKeyAlias, privateKeyPassword); 143 | } catch (Exception e) { 144 | throw new SSOAgentException("Error while loading key store file", e); 145 | } finally { 146 | if (keyStoreInputStream != null) { 147 | try { 148 | keyStoreInputStream.close(); 149 | } catch (IOException ignored) { 150 | if (log.isDebugEnabled()) { 151 | log.debug("Ignoring IO Exception : ", ignored); 152 | } 153 | throw new SSOAgentException("Error while closing input stream of key store"); 154 | } 155 | } 156 | } 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/artifact/SAMLSSOSoapMessageService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.asgardeo.java.saml.sdk.artifact; 20 | 21 | import org.apache.commons.logging.Log; 22 | import org.apache.commons.logging.LogFactory; 23 | import org.apache.http.HttpResponse; 24 | import org.apache.http.client.HttpClient; 25 | import org.apache.http.client.ResponseHandler; 26 | import org.apache.http.client.methods.HttpPost; 27 | import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 28 | import org.apache.http.conn.ssl.SSLContextBuilder; 29 | import org.apache.http.conn.ssl.TrustSelfSignedStrategy; 30 | import org.apache.http.entity.ContentType; 31 | import org.apache.http.entity.StringEntity; 32 | import org.apache.http.impl.client.BasicResponseHandler; 33 | import org.apache.http.impl.client.CloseableHttpClient; 34 | import org.apache.http.impl.client.HttpClients; 35 | import org.opensaml.core.xml.XMLObjectBuilderFactory; 36 | import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; 37 | import org.opensaml.saml.common.SAMLObject; 38 | import org.opensaml.soap.common.SOAPObjectBuilder; 39 | import org.opensaml.soap.soap11.Body; 40 | import org.opensaml.soap.soap11.Envelope; 41 | import io.asgardeo.java.saml.sdk.exception.ArtifactResolutionException; 42 | import io.asgardeo.java.saml.sdk.util.SSOAgentConstants; 43 | 44 | import java.io.IOException; 45 | import java.net.UnknownHostException; 46 | import java.nio.charset.StandardCharsets; 47 | import java.security.KeyManagementException; 48 | import java.security.KeyStoreException; 49 | import java.security.NoSuchAlgorithmException; 50 | 51 | /** 52 | * This class is used for handling SAML SOAP Binding 53 | */ 54 | public class SAMLSSOSoapMessageService { 55 | 56 | private static final String CONTENT_TYPE = "text/xml; charset=utf-8"; 57 | private static final String MIME_TYPE = "text/xml"; 58 | private static final Log log = LogFactory.getLog(SAMLSSOSoapMessageService.class); 59 | 60 | private static String getResponseBody(HttpResponse response) throws ArtifactResolutionException { 61 | 62 | ResponseHandler responseHandler = new BasicResponseHandler(); 63 | String responseBody; 64 | try { 65 | responseBody = responseHandler.handleResponse(response); 66 | } catch (IOException e) { 67 | throw new ArtifactResolutionException("Error when retrieving the HTTP response body.", e); 68 | } 69 | if (log.isDebugEnabled()) { 70 | log.debug("Response Body:" + responseBody); 71 | } 72 | return responseBody; 73 | } 74 | 75 | /** 76 | * Build a SOAP Message. 77 | * 78 | * @param samlMessage SAMLObject. 79 | * @return Envelope soap envelope 80 | */ 81 | public Envelope buildSOAPMessage(SAMLObject samlMessage) { 82 | 83 | XMLObjectBuilderFactory builderFactory = XMLObjectProviderRegistrySupport.getBuilderFactory(); 84 | 85 | SOAPObjectBuilder envBuilder = (SOAPObjectBuilder) builderFactory.getBuilder( 86 | Envelope.DEFAULT_ELEMENT_NAME); 87 | Envelope envelope = envBuilder.buildObject(); 88 | 89 | SOAPObjectBuilder bodyBuilder = (SOAPObjectBuilder) builderFactory.getBuilder( 90 | Body.DEFAULT_ELEMENT_NAME); 91 | Body body = bodyBuilder.buildObject(); 92 | body.getUnknownXMLObjects().add(samlMessage); 93 | envelope.setBody(body); 94 | return envelope; 95 | } 96 | 97 | /** 98 | * Send SOAP message 99 | * 100 | * @param message message that needs to be send 101 | * @param url url that the artifact resolve request should be sent 102 | * @return response of invoking artifact resolve endpoint 103 | * @throws ArtifactResolutionException 104 | */ 105 | public String sendSOAP(String message, String url) throws ArtifactResolutionException { 106 | 107 | if (message == null) { 108 | throw new ArtifactResolutionException("Cannot send null SOAP message."); 109 | } 110 | if (url == null) { 111 | throw new ArtifactResolutionException("Cannot send SOAP message to null URL."); 112 | } 113 | 114 | if (log.isDebugEnabled()) { 115 | log.debug("Sending SOAP message to the URL: " + url); 116 | } 117 | 118 | StringBuilder soapResponse = new StringBuilder(); 119 | try { 120 | HttpPost httpPost = new HttpPost(url); 121 | setRequestProperties(url, message, httpPost); 122 | HttpClient httpClient = getHttpClient(); 123 | HttpResponse httpResponse = httpClient.execute(httpPost); 124 | 125 | int responseCode = httpResponse.getStatusLine().getStatusCode(); 126 | if (responseCode != 200) { 127 | throw new ArtifactResolutionException("Problem in communicating with: " + url + ". Received response: " 128 | + responseCode); 129 | } else { 130 | log.info("Successful response from the URL: " + url); 131 | soapResponse.append(getResponseBody(httpResponse)); 132 | } 133 | } catch (UnknownHostException e) { 134 | throw new ArtifactResolutionException("Unknown targeted host: " + url, e); 135 | } catch (IOException e) { 136 | throw new ArtifactResolutionException("Could not open connection with host: " + url, e); 137 | } 138 | return soapResponse.toString(); 139 | } 140 | 141 | private void setRequestProperties(String url, String message, HttpPost httpPost) { 142 | 143 | httpPost.addHeader(SSOAgentConstants.SSOAgentConfig.SAML2.CONTENT_TYPE_PARAM_KEY, CONTENT_TYPE); 144 | httpPost.addHeader(SSOAgentConstants.SSOAgentConfig.SAML2.ACCEPT_PARAM_KEY, CONTENT_TYPE); 145 | String sbSOAPAction = "\"" + url + "\""; 146 | httpPost.addHeader(SSOAgentConstants.SSOAgentConfig.SAML2.SOAP_ACTION_PARAM_KEY, sbSOAPAction); 147 | httpPost.addHeader(SSOAgentConstants.SSOAgentConfig.SAML2.PRAGMA_PARAM_KEY, "no-cache"); 148 | httpPost.addHeader(SSOAgentConstants.SSOAgentConfig.SAML2.CACHE_CONTROL_PARAM_KEY, "no-cache, no-store"); 149 | 150 | httpPost.setEntity(new StringEntity(message, ContentType.create(MIME_TYPE, StandardCharsets.UTF_8))); 151 | } 152 | 153 | private HttpClient getHttpClient() throws ArtifactResolutionException { 154 | 155 | CloseableHttpClient httpClient = null; 156 | SSLContextBuilder builder = new SSLContextBuilder(); 157 | try { 158 | builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); 159 | SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( 160 | builder.build()); 161 | httpClient = HttpClients.custom().setSSLSocketFactory( 162 | sslsf).build(); 163 | } catch (NoSuchAlgorithmException | KeyStoreException e) { 164 | throw new ArtifactResolutionException("Error while building trust store.", e); 165 | } catch (KeyManagementException e) { 166 | throw new ArtifactResolutionException("Error while building socket factory.", e); 167 | } 168 | 169 | return httpClient; 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/bean/LoggedInSessionBean.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | * 18 | * 19 | */ 20 | 21 | package io.asgardeo.java.saml.sdk.bean; 22 | 23 | import com.google.gson.Gson; 24 | import com.google.gson.annotations.SerializedName; 25 | import io.asgardeo.java.saml.sdk.util.SSOAgentUtils; 26 | import org.opensaml.saml.saml2.core.Assertion; 27 | import org.opensaml.saml.saml2.core.Response; 28 | import io.asgardeo.java.saml.sdk.exception.SSOAgentException; 29 | 30 | import java.io.IOException; 31 | import java.io.Serializable; 32 | import java.util.Map; 33 | 34 | import javax.xml.bind.annotation.XmlAttribute; 35 | 36 | public class LoggedInSessionBean implements Serializable { 37 | 38 | private static final long serialVersionUID = 7762835859870143767L; 39 | 40 | private SAML2SSO saml2SSO; 41 | 42 | public SAML2SSO getSAML2SSO() { 43 | 44 | return saml2SSO; 45 | } 46 | 47 | public void setSAML2SSO(SAML2SSO saml2SSO) { 48 | 49 | this.saml2SSO = saml2SSO; 50 | } 51 | 52 | public static class AccessTokenResponseBean implements Serializable { 53 | 54 | @XmlAttribute(name = "access_token") 55 | @SerializedName("access_token") 56 | private String accessToken; 57 | 58 | @XmlAttribute(name = "refresh_token") 59 | @SerializedName("refresh_token") 60 | private String refreshToken; 61 | 62 | @XmlAttribute(name = "token_type") 63 | @SerializedName("token_type") 64 | private String tokenType; 65 | 66 | @XmlAttribute(name = "expires_in") 67 | @SerializedName("expires_in") 68 | private String expiresIn; 69 | 70 | public String getAccessToken() { 71 | 72 | return accessToken; 73 | } 74 | 75 | public void setAccessToken(String accessToken) { 76 | 77 | this.accessToken = accessToken; 78 | } 79 | 80 | public String getRefreshToken() { 81 | 82 | return refreshToken; 83 | } 84 | 85 | public void setRefreshToken(String refreshToken) { 86 | 87 | this.refreshToken = refreshToken; 88 | } 89 | 90 | public String getTokenType() { 91 | 92 | return tokenType; 93 | } 94 | 95 | public void setTokenType(String tokenType) { 96 | 97 | this.tokenType = tokenType; 98 | } 99 | 100 | public String getExpiresIn() { 101 | 102 | return expiresIn; 103 | } 104 | 105 | public void setExpiresIn(String expiresIn) { 106 | 107 | this.expiresIn = expiresIn; 108 | } 109 | 110 | @Override 111 | public String toString() { 112 | 113 | Gson gson = new Gson(); 114 | return gson.toJson(this); 115 | } 116 | 117 | public AccessTokenResponseBean deSerialize(String accessTokenResponseBeanString) { 118 | 119 | Gson gson = new Gson(); 120 | return gson.fromJson(accessTokenResponseBeanString, AccessTokenResponseBean.class); 121 | } 122 | } 123 | 124 | public class SAML2SSO implements Serializable { 125 | 126 | public static final String EMPTY_STRING = ""; 127 | private String subjectId; 128 | 129 | private Response response; 130 | 131 | private String responseString; 132 | 133 | private Assertion assertion; 134 | 135 | private String assertionString; 136 | 137 | private AccessTokenResponseBean accessTokenResponseBean; 138 | 139 | private String sessionIndex; 140 | 141 | private Map subjectAttributes; 142 | 143 | private void writeObject(java.io.ObjectOutputStream stream) 144 | throws IOException { 145 | 146 | stream.writeObject(subjectId); 147 | 148 | stream.writeObject(responseString); 149 | 150 | stream.writeObject(assertionString); 151 | 152 | stream.writeObject(sessionIndex); 153 | if (accessTokenResponseBean != null) { 154 | stream.writeObject(accessTokenResponseBean.toString()); 155 | } else { 156 | stream.writeObject(EMPTY_STRING); 157 | } 158 | stream.writeObject(subjectAttributes); 159 | } 160 | 161 | private void readObject(java.io.ObjectInputStream stream) 162 | throws IOException, ClassNotFoundException, SSOAgentException { 163 | 164 | subjectId = (String) stream.readObject(); 165 | 166 | responseString = (String) stream.readObject(); 167 | if (responseString != null && !EMPTY_STRING.equals(responseString)) { 168 | response = (Response) SSOAgentUtils.unmarshall(responseString); 169 | } 170 | 171 | assertionString = (String) stream.readObject(); 172 | if (responseString != null && !EMPTY_STRING.equals(assertionString)) { 173 | assertion = (Assertion) SSOAgentUtils.unmarshall(assertionString); 174 | } 175 | 176 | sessionIndex = (String) stream.readObject(); 177 | String accessTokenResponseBeanString = (String) stream.readObject(); 178 | if (!EMPTY_STRING.equals(accessTokenResponseBeanString)) { 179 | accessTokenResponseBean = accessTokenResponseBean.deSerialize(accessTokenResponseBeanString); 180 | } else { 181 | accessTokenResponseBean = null; 182 | } 183 | subjectAttributes = (Map) stream.readObject(); 184 | } 185 | 186 | public String getSubjectId() { 187 | 188 | return subjectId; 189 | } 190 | 191 | public void setSubjectId(String subjectId) { 192 | 193 | this.subjectId = subjectId; 194 | } 195 | 196 | public Map getSubjectAttributes() { 197 | 198 | return subjectAttributes; 199 | } 200 | 201 | public void setSubjectAttributes(Map samlSSOAttributes) { 202 | 203 | this.subjectAttributes = samlSSOAttributes; 204 | } 205 | 206 | public String getSessionIndex() { 207 | 208 | return sessionIndex; 209 | } 210 | 211 | public void setSessionIndex(String sessionIndex) { 212 | 213 | this.sessionIndex = sessionIndex; 214 | } 215 | 216 | public Response getSAMLResponse() { 217 | 218 | return response; 219 | } 220 | 221 | public void setSAMLResponse(Response samlResponse) { 222 | 223 | this.response = samlResponse; 224 | } 225 | 226 | public String getResponseString() { 227 | 228 | return responseString; 229 | } 230 | 231 | public void setResponseString(String responseString) { 232 | 233 | this.responseString = responseString; 234 | } 235 | 236 | public Assertion getAssertion() { 237 | 238 | return assertion; 239 | } 240 | 241 | public void setAssertion(Assertion samlAssertion) { 242 | 243 | this.assertion = samlAssertion; 244 | } 245 | 246 | public String getAssertionString() { 247 | 248 | return assertionString; 249 | } 250 | 251 | public void setAssertionString(String samlAssertionString) { 252 | 253 | this.assertionString = samlAssertionString; 254 | } 255 | 256 | public AccessTokenResponseBean getAccessTokenResponseBean() { 257 | 258 | return accessTokenResponseBean; 259 | } 260 | 261 | public void setAccessTokenResponseBean(AccessTokenResponseBean accessTokenResponseBean) { 262 | 263 | this.accessTokenResponseBean = accessTokenResponseBean; 264 | } 265 | } 266 | } 267 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/artifact/SAMLSSOArtifactResolutionService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.asgardeo.java.saml.sdk.artifact; 20 | 21 | import org.apache.commons.lang.StringUtils; 22 | import org.apache.commons.logging.Log; 23 | import org.apache.commons.logging.LogFactory; 24 | import org.apache.xml.security.signature.XMLSignature; 25 | import org.joda.time.DateTime; 26 | import org.opensaml.core.xml.XMLObjectBuilderFactory; 27 | import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; 28 | import org.opensaml.saml.common.SAMLObject; 29 | import org.opensaml.saml.common.SAMLObjectBuilder; 30 | import org.opensaml.saml.common.SAMLVersion; 31 | import org.opensaml.saml.common.xml.SAMLConstants; 32 | import org.opensaml.saml.saml2.core.Artifact; 33 | import org.opensaml.saml.saml2.core.ArtifactResolve; 34 | import org.opensaml.saml.saml2.core.ArtifactResponse; 35 | import org.opensaml.saml.saml2.core.Issuer; 36 | import org.opensaml.saml.saml2.core.StatusCode; 37 | import org.opensaml.soap.soap11.Envelope; 38 | import io.asgardeo.java.saml.sdk.bean.SSOAgentConfig; 39 | import io.asgardeo.java.saml.sdk.exception.ArtifactResolutionException; 40 | import io.asgardeo.java.saml.sdk.exception.SSOAgentException; 41 | import io.asgardeo.java.saml.sdk.security.X509CredentialImpl; 42 | import io.asgardeo.java.saml.sdk.util.SSOAgentUtils; 43 | 44 | import java.io.ByteArrayInputStream; 45 | import java.io.IOException; 46 | import java.io.InputStream; 47 | import java.io.StringWriter; 48 | import java.nio.charset.StandardCharsets; 49 | import java.util.Iterator; 50 | import java.util.UUID; 51 | 52 | import javax.xml.soap.MessageFactory; 53 | import javax.xml.soap.MimeHeaders; 54 | import javax.xml.soap.SOAPBody; 55 | import javax.xml.soap.SOAPBodyElement; 56 | import javax.xml.soap.SOAPException; 57 | import javax.xml.soap.SOAPMessage; 58 | import javax.xml.transform.TransformerException; 59 | import javax.xml.transform.TransformerFactory; 60 | import javax.xml.transform.dom.DOMSource; 61 | import javax.xml.transform.stream.StreamResult; 62 | 63 | /** 64 | * This class is used for handling SAML2 Artifact Binding. 65 | */ 66 | public class SAMLSSOArtifactResolutionService { 67 | 68 | private static final Log log = LogFactory.getLog(SAMLSSOArtifactResolutionService.class); 69 | 70 | private SSOAgentConfig ssoAgentConfig; 71 | 72 | public SAMLSSOArtifactResolutionService(SSOAgentConfig ssoAgentConfig) { 73 | 74 | this.ssoAgentConfig = ssoAgentConfig; 75 | } 76 | 77 | /** 78 | * Create a SAML artifactResolveObject based on given samlArt parameter and wrapped into a soapRequest 79 | * Send the soapRequest to the Artifact Resolve Endpoint 80 | * 81 | * @param samlArtReceived SAML Artifact reference needed to get the actual data 82 | * @return ArtifactResponse 83 | */ 84 | public ArtifactResponse getSAMLArtifactResponse(String samlArtReceived) throws ArtifactResolutionException { 85 | 86 | validateArtifactResolveConfig(); 87 | ArtifactResolve artifactResolve = generateArtifactResolveReq(samlArtReceived); 88 | return sendArtifactResolveRequest(artifactResolve); 89 | } 90 | 91 | /** 92 | * Create SAML ArtifactResolve Object and sign 93 | * 94 | * @param samlArtReceived object reference to actual data 95 | * @return SAML ArtifactResolve Object 96 | */ 97 | public ArtifactResolve generateArtifactResolveReq(String samlArtReceived) throws ArtifactResolutionException { 98 | 99 | ArtifactResolve artifactResolve = createArtifactResolveObject(samlArtReceived); 100 | if (ssoAgentConfig.getSAML2().isEnableArtifactResolveSigning()) { 101 | if (log.isDebugEnabled()) { 102 | log.debug("Signing artifact resolve request for the received SAML artifact: " + samlArtReceived); 103 | } 104 | artifactResolve = signArtifactResolveReq(artifactResolve); 105 | } 106 | 107 | if (log.isDebugEnabled()) { 108 | log.debug("Created Artifact Resolve object: " + artifactResolve); 109 | } 110 | 111 | return artifactResolve; 112 | } 113 | 114 | /** 115 | * Send Artifact Resolve Request to Artifact Resolution Service 116 | * 117 | * @param artifactResolve Artifact Resolve Request 118 | * @return ArtifactResponse 119 | * @throws ArtifactResolutionException 120 | */ 121 | public ArtifactResponse sendArtifactResolveRequest(ArtifactResolve artifactResolve) 122 | throws ArtifactResolutionException { 123 | 124 | SAMLSSOSoapMessageService soapMessageService = new SAMLSSOSoapMessageService(); 125 | Envelope envelope = soapMessageService.buildSOAPMessage(artifactResolve); 126 | String envelopeElement; 127 | try { 128 | envelopeElement = SSOAgentUtils.marshall(envelope); 129 | } catch (SSOAgentException e) { 130 | throw new ArtifactResolutionException("Encountered error marshalling SOAP message with artifact " + 131 | "resolve, into its DOM representation", e); 132 | } 133 | 134 | if (log.isDebugEnabled()) { 135 | log.debug("Artifact Resolve Request as a SOAP Message: " + envelopeElement); 136 | } 137 | 138 | String artifactResponseString = soapMessageService.sendSOAP(envelopeElement, 139 | ssoAgentConfig.getSAML2().getArtifactResolveURL()); 140 | if (log.isDebugEnabled()) { 141 | log.debug("Received artifact response string: " + artifactResponseString); 142 | } 143 | ArtifactResponse artifactResponse = extractArtifactResponse(artifactResponseString); 144 | validateArtifactResponse(artifactResolve, artifactResponse); 145 | return artifactResponse; 146 | } 147 | 148 | /** 149 | * Extract Artifact response object from soap message string. Return null if fail. 150 | * 151 | * @param artifactResponseString Response string from artifact resolver. 152 | * @return Extracted artifact response object. 153 | * @throws ArtifactResolutionException 154 | */ 155 | public ArtifactResponse extractArtifactResponse(String artifactResponseString) 156 | throws ArtifactResolutionException { 157 | 158 | ArtifactResponse artifactResponse = null; 159 | InputStream stream = new ByteArrayInputStream(artifactResponseString.getBytes(StandardCharsets.UTF_8)); 160 | try { 161 | MessageFactory messageFactory = MessageFactory.newInstance(); 162 | SOAPMessage soapMessage = messageFactory.createMessage(new MimeHeaders(), stream); 163 | SOAPBody soapBody = soapMessage.getSOAPBody(); 164 | Iterator iterator = soapBody.getChildElements(); 165 | 166 | while (iterator.hasNext()) { 167 | SOAPBodyElement artifactResponseElement = (SOAPBodyElement) iterator.next(); 168 | 169 | if (StringUtils.equals(SAMLConstants.SAML20P_NS, artifactResponseElement.getNamespaceURI()) && 170 | StringUtils.equals(ArtifactResponse.DEFAULT_ELEMENT_LOCAL_NAME, 171 | artifactResponseElement.getLocalName())) { 172 | 173 | DOMSource source = new DOMSource(artifactResponseElement); 174 | StringWriter stringResult = new StringWriter(); 175 | TransformerFactory.newInstance().newTransformer().transform( 176 | source, new StreamResult(stringResult)); 177 | artifactResponse = (ArtifactResponse) SSOAgentUtils.unmarshall(stringResult.toString()); 178 | if (log.isDebugEnabled()) { 179 | log.debug("Extracted Artifact Response: " + stringResult); 180 | } 181 | } else { 182 | throw new ArtifactResolutionException("Received invalid artifact response with nameSpaceURI: " + 183 | artifactResponseElement.getNamespaceURI() + " and localName: " + 184 | artifactResponseElement.getLocalName()); 185 | } 186 | } 187 | } catch (SOAPException | IOException | TransformerException e) { 188 | throw new ArtifactResolutionException("Didn't receive valid artifact response.", e); 189 | } catch (SSOAgentException e) { 190 | throw new ArtifactResolutionException("Encountered error unmarshalling response into SAML2 object", e); 191 | } 192 | return artifactResponse; 193 | } 194 | 195 | private void validateArtifactResponse(ArtifactResolve artifactResolve, ArtifactResponse artifactResponse) 196 | throws ArtifactResolutionException { 197 | 198 | if (artifactResponse == null) { 199 | throw new ArtifactResolutionException("Received artifact response message was null."); 200 | } 201 | 202 | String artifactResolveId = artifactResolve.getID(); 203 | String artifactResponseInResponseTo = artifactResponse.getInResponseTo(); 204 | if (!artifactResolveId.equals(artifactResponseInResponseTo)) { 205 | throw new ArtifactResolutionException("Artifact resolve ID: " + artifactResolveId + " is not equal to " + 206 | "artifact response InResponseTo : " + artifactResponseInResponseTo); 207 | } 208 | 209 | String artifactResponseStatus = artifactResponse.getStatus().getStatusCode().getValue(); 210 | if (!StatusCode.SUCCESS.equals(artifactResponseStatus)) { 211 | throw new ArtifactResolutionException("Unsuccessful artifact response with status: " + 212 | artifactResponseStatus); 213 | } 214 | 215 | SAMLObject message = artifactResponse.getMessage(); 216 | if (message == null) { 217 | throw new ArtifactResolutionException("No SAML response embedded into the artifact response."); 218 | } 219 | } 220 | 221 | private void validateArtifactResolveConfig() throws ArtifactResolutionException { 222 | 223 | if (StringUtils.isEmpty(ssoAgentConfig.getSAML2().getArtifactResolveURL())) { 224 | throw new ArtifactResolutionException("Artifact Resolve Url is not configured."); 225 | } 226 | if (StringUtils.isEmpty(ssoAgentConfig.getSAML2().getSPEntityId())) { 227 | throw new ArtifactResolutionException("Artifact Resolve Issuer is not configured."); 228 | } 229 | } 230 | 231 | private ArtifactResolve createArtifactResolveObject(String samlArtReceived) { 232 | 233 | XMLObjectBuilderFactory builderFactory = XMLObjectProviderRegistrySupport.getBuilderFactory(); 234 | 235 | SAMLObjectBuilder artifactResolveBuilder = 236 | (SAMLObjectBuilder) builderFactory.getBuilder(ArtifactResolve.DEFAULT_ELEMENT_NAME); 237 | ArtifactResolve artifactResolve = artifactResolveBuilder.buildObject(); 238 | artifactResolve.setVersion(SAMLVersion.VERSION_20); 239 | artifactResolve.setID(UUID.randomUUID().toString()); 240 | artifactResolve.setIssueInstant(new DateTime()); 241 | 242 | SAMLObjectBuilder artifactBuilder = 243 | (SAMLObjectBuilder) builderFactory.getBuilder(Artifact.DEFAULT_ELEMENT_NAME); 244 | Artifact artifact = artifactBuilder.buildObject(); 245 | artifact.setArtifact(samlArtReceived); 246 | 247 | SAMLObjectBuilder issuerBuilder = 248 | (SAMLObjectBuilder) builderFactory.getBuilder(Issuer.DEFAULT_ELEMENT_NAME); 249 | Issuer issuer = issuerBuilder.buildObject(); 250 | issuer.setValue(ssoAgentConfig.getSAML2().getSPEntityId()); 251 | 252 | artifactResolve.setIssuer(issuer); 253 | artifactResolve.setArtifact(artifact); 254 | 255 | return artifactResolve; 256 | } 257 | 258 | private ArtifactResolve signArtifactResolveReq(ArtifactResolve artifactResolve) 259 | throws ArtifactResolutionException { 260 | 261 | try { 262 | return SSOAgentUtils.setSignature(artifactResolve, XMLSignature.ALGO_ID_SIGNATURE_RSA, 263 | new X509CredentialImpl(ssoAgentConfig.getSAML2().getSSOAgentX509Credential())); 264 | } catch (SSOAgentException e) { 265 | throw new ArtifactResolutionException("Error in signing the Artifact Resolve request", e); 266 | } 267 | } 268 | } 269 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 21 | 22 | org.wso2 23 | wso2 24 | 1.4 25 | 26 | 27 | io.asgardeo.java.saml.sdk 28 | 4.0.0 29 | java-saml-sdk 30 | 0.1.20-SNAPSHOT 31 | pom 32 | Asgardeo - Java SAML SDK Parent Module 33 | 34 | The asgardeo SAML SDK for Java enables software developers to integrate SAML based SSO authentication with Java 35 | Web applications. The SDK is built on top of the OpenSAML library which allows Java developers to develop 36 | cross-domain single sign-on and federated access control solutions with minimum hassle. 37 | 38 | http://asgardeo.io 39 | 40 | 41 | https://github.com/asgardeo/asgardeo-java-saml-sdk.git 42 | scm:git:https://github.com/asgardeo/asgardeo-java-saml-sdk.git 43 | scm:git:https://github.com/asgardeo/asgardeo-java-saml-sdk.git 44 | HEAD 45 | 46 | 47 | 48 | 49 | 50 | org.opensaml 51 | opensaml-core 52 | ${opensaml.version} 53 | 54 | 55 | commons-collections 56 | commons-collections 57 | 58 | 59 | commons-lang 60 | commons-lang 61 | 62 | 63 | jargs 64 | jargs 65 | 66 | 67 | org.apache.xerces 68 | resolver 69 | 70 | 71 | org.apache.xerces 72 | xml-apis 73 | 74 | 75 | org.apache.xerces 76 | serializer 77 | 78 | 79 | org.apache.xalan 80 | xalan 81 | 82 | 83 | org.apache.xerces 84 | xercesImpl 85 | 86 | 87 | 88 | 89 | org.opensaml 90 | opensaml-saml-impl 91 | ${opensaml.version} 92 | 93 | 94 | commons-collections 95 | commons-collections 96 | 97 | 98 | commons-lang 99 | commons-lang 100 | 101 | 102 | jargs 103 | jargs 104 | 105 | 106 | org.apache.xerces 107 | resolver 108 | 109 | 110 | org.apache.xerces 111 | xml-apis 112 | 113 | 114 | org.apache.xerces 115 | serializer 116 | 117 | 118 | org.apache.xalan 119 | xalan 120 | 121 | 122 | org.apache.xerces 123 | xercesImpl 124 | 125 | 126 | 127 | 128 | org.bouncycastle 129 | bcprov-jdk15on 130 | ${bouncycastle.version} 131 | 132 | 133 | javax.servlet 134 | javax.servlet-api 135 | ${javax.servlet-api.version} 136 | 137 | 138 | com.google.code.gson 139 | gson 140 | ${com.google.code.gson.version} 141 | 142 | 143 | org.apache.felix 144 | org.apache.felix.scr.ds-annotations 145 | ${apache.felix.scr.ds.annotations.version} 146 | 147 | 148 | commons-lang 149 | commons-lang 150 | ${commons.lang.version} 151 | 152 | 153 | xerces 154 | xercesImpl 155 | ${xerces.version} 156 | 157 | 158 | org.apache.httpcomponents 159 | httpclient 160 | ${apache.httpcomponents.version} 161 | 162 | 163 | org.owasp.encoder 164 | encoder 165 | ${owasp.encoder.version} 166 | 167 | 168 | commons-collections 169 | commons-collections 170 | ${commons.collections.version} 171 | 172 | 173 | org.jacoco 174 | jacoco-maven-plugin 175 | ${jacoco.version} 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | org.codehaus.mojo 185 | buildnumber-maven-plugin 186 | ${maven.buildnumber.plugin.version} 187 | 188 | 189 | validate 190 | 191 | create 192 | 193 | 194 | 195 | 196 | false 197 | false 198 | 199 | 200 | 201 | org.jacoco 202 | jacoco-maven-plugin 203 | ${jacoco.version} 204 | 205 | 206 | 207 | prepare-agent 208 | 209 | 210 | 211 | report 212 | test 213 | 214 | report 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | org.apache.maven.plugins 224 | maven-release-plugin 225 | 226 | clean install 227 | true 228 | 229 | 230 | 231 | org.apache.maven.plugins 232 | maven-deploy-plugin 233 | 234 | 235 | maven-compiler-plugin 236 | 2.3.1 237 | true 238 | 239 | UTF-8 240 | 1.8 241 | 1.8 242 | 243 | 244 | 245 | org.codehaus.mojo 246 | buildnumber-maven-plugin 247 | 248 | 249 | org.apache.maven.plugins 250 | maven-javadoc-plugin 251 | 252 | 1.8 253 | 254 | 255 | 256 | attach-javadocs 257 | 258 | jar 259 | 260 | 261 | 262 | none 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 3.3.1 272 | 1.62 273 | 3.1.0 274 | 2.8.5 275 | 1.2.4 276 | 2.6 277 | 2.12.0 278 | 4.5.13 279 | 1.2.3 280 | 3.2.2 281 | 1.4 282 | 283 | 0.8.6 284 | 285 | 286 | 287 | io.asgardeo.java.saml.sdk 288 | 289 | 290 | 291 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/util/SSOAgentConfigs.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | * 18 | * 19 | */ 20 | 21 | package io.asgardeo.java.saml.sdk.util; 22 | 23 | import org.apache.commons.logging.Log; 24 | import org.apache.commons.logging.LogFactory; 25 | import io.asgardeo.java.saml.sdk.exception.SSOAgentException; 26 | 27 | import java.io.FileInputStream; 28 | import java.io.FileNotFoundException; 29 | import java.io.IOException; 30 | import java.io.InputStream; 31 | import java.security.KeyStore; 32 | import java.util.Properties; 33 | import java.util.logging.Logger; 34 | 35 | import javax.servlet.FilterConfig; 36 | 37 | public class SSOAgentConfigs { 38 | 39 | private static final Logger LOGGER = Logger.getLogger("InfoLogging"); 40 | private static final Log log = LogFactory.getLog(SSOAgentConfigs.class); 41 | 42 | private static Boolean samlSSOLoginEnabled; 43 | private static String sessionBeanName; 44 | private static String loginUrl; 45 | private static String samlSSOUrl; 46 | private static String issuerId; 47 | private static String consumerUrl; 48 | private static String idPUrl; 49 | private static String indexPage; 50 | 51 | private static String attributeConsumingServiceIndex; 52 | private static Boolean isSLOEnabled; 53 | private static String logoutUrl; 54 | private static Boolean isResponseSigned; 55 | private static Boolean isAssertionSigned; 56 | private static Boolean isAssertionEncrypted; 57 | private static Boolean isRequestSigned; 58 | private static Boolean isForceAuthn; 59 | private static String ssoAgentCredentialImplClass; 60 | private static InputStream keyStoreStream; 61 | private static String keyStorePassword; 62 | private static KeyStore keyStore; 63 | private static String idPCertAlias; 64 | private static String privateKeyAlias; 65 | private static String privateKeyPassword; 66 | 67 | private static String requestQueryParameters; 68 | private static String addExtension; 69 | 70 | private SSOAgentConfigs() { 71 | 72 | } 73 | 74 | public static void initConfig(FilterConfig fConfigs) throws SSOAgentException { 75 | 76 | Properties properties = new Properties(); 77 | 78 | if (fConfigs.getInitParameter("SSOAgentPropertiesFilePath") != null && 79 | !"".equals(fConfigs.getInitParameter("SSOAgentPropertiesFilePath"))) { 80 | try (FileInputStream fileInputStream = new FileInputStream(fConfigs.getInitParameter 81 | ("SSOAgentPropertiesFilePath"))) { 82 | properties.load(fileInputStream); 83 | initConfig(properties); 84 | } catch (FileNotFoundException e) { 85 | if (log.isDebugEnabled()) { 86 | log.debug("File not found ", e); 87 | } 88 | throw new SSOAgentException("Agent properties file not found"); 89 | 90 | } catch (IOException e) { 91 | 92 | throw new SSOAgentException("Error occurred while reading Agent properties file", e); 93 | } 94 | 95 | } else { 96 | LOGGER.warning("\'SSOAgentPropertiesFilePath\' not configured"); 97 | } 98 | } 99 | 100 | public static void initConfig(String propertiesFilePath) throws SSOAgentException { 101 | 102 | Properties properties = new Properties(); 103 | try (FileInputStream fileInputStream = new FileInputStream(propertiesFilePath)) { 104 | properties.load(fileInputStream); 105 | initConfig(properties); 106 | } catch (FileNotFoundException e) { 107 | 108 | throw new SSOAgentException("Agent properties file not found at " + propertiesFilePath, e); 109 | } catch (IOException e) { 110 | 111 | throw new SSOAgentException("Error reading Agent properties file at " + propertiesFilePath, e); 112 | } 113 | } 114 | 115 | public static void initConfig(Properties properties) throws SSOAgentException { 116 | 117 | if (properties.getProperty("EnableSAMLSSOLogin") != null) { 118 | samlSSOLoginEnabled = Boolean.parseBoolean(properties.getProperty("EnableSAMLSSOLogin")); 119 | } else { 120 | LOGGER.info("\'EnableSAMLSSOLogin\' not configured. Defaulting to \'true\'"); 121 | samlSSOLoginEnabled = true; 122 | } 123 | 124 | if (properties.getProperty("SSOAgentSessionBeanName") != null) { 125 | sessionBeanName = properties.getProperty("SSOAgentSessionBeanName"); 126 | } else { 127 | LOGGER.info("\'SSOAgentSessionBeanName\' not configured. Defaulting to \'SSOAgentSessionBean\'"); 128 | sessionBeanName = "SSOAgentSessionBean"; 129 | } 130 | 131 | loginUrl = properties.getProperty("LoginUrl"); 132 | samlSSOUrl = properties.getProperty("SAMLSSOUrl"); 133 | indexPage = properties.getProperty(SSOAgentConstants.SSOAgentConfig.INDEX_PAGE); 134 | issuerId = properties.getProperty("SAML.IssuerID"); 135 | consumerUrl = properties.getProperty("SAML.ConsumerUrl"); 136 | idPUrl = properties.getProperty("SAML.IdPUrl"); 137 | attributeConsumingServiceIndex = properties.getProperty("SAML.AttributeConsumingServiceIndex"); 138 | 139 | if (properties.getProperty("SAML.EnableSLO") != null) { 140 | isSLOEnabled = Boolean.parseBoolean(properties.getProperty("SAML.EnableSLO")); 141 | } else { 142 | LOGGER.info("\'SAML.EnableSLO\' not configured. Defaulting to \'false\'"); 143 | isSLOEnabled = false; 144 | } 145 | 146 | logoutUrl = properties.getProperty("SAML.LogoutUrl"); 147 | 148 | if (properties.getProperty("SAML.EnableResponseSigning") != null) { 149 | isResponseSigned = Boolean.parseBoolean(properties.getProperty("SAML.EnableResponseSigning")); 150 | } else { 151 | LOGGER.info("\'SAML.EnableResponseSigning\' not configured. Defaulting to \'false\'"); 152 | isResponseSigned = false; 153 | } 154 | 155 | if (properties.getProperty("SAML.EnableAssertionSigning") != null) { 156 | isAssertionSigned = Boolean.parseBoolean(properties.getProperty("SAML.EnableAssertionSigning")); 157 | } else { 158 | LOGGER.info("\'SAML.EnableAssertionSigning\' not configured. Defaulting to \'true\'"); 159 | isAssertionSigned = true; 160 | } 161 | 162 | if (properties.getProperty("SAML.EnableAssertionEncryption") != null) { 163 | isAssertionEncrypted = Boolean.parseBoolean(properties.getProperty("SAML.EnableAssertionEncryption")); 164 | } else { 165 | LOGGER.info("\'SAML.EnableAssertionEncryption\' not configured. Defaulting to \'false\'"); 166 | isAssertionEncrypted = false; 167 | } 168 | 169 | if (properties.getProperty("SAML.EnableRequestSigning") != null) { 170 | isRequestSigned = Boolean.parseBoolean(properties.getProperty("SAML.EnableRequestSigning")); 171 | } else { 172 | LOGGER.info("\'SAML.EnableRequestSigning\' not configured. Defaulting to \'false\'"); 173 | isRequestSigned = false; 174 | } 175 | 176 | if (properties.getProperty("SAML.EnableForceAuthentication") != null) { 177 | isForceAuthn = Boolean.parseBoolean(properties.getProperty("SAML.EnableForceAuthentication")); 178 | } else { 179 | LOGGER.info("\'SAML.EnableForceAuthentication\' not configured. Defaulting to \'false\'"); 180 | isForceAuthn = false; 181 | } 182 | 183 | ssoAgentCredentialImplClass = properties.getProperty("SAML.SSOAgentCredentialImplClass"); 184 | if (properties.getProperty("KeyStore") != null) { 185 | try { 186 | keyStoreStream = new FileInputStream(properties.getProperty("KeyStore")); 187 | } catch (FileNotFoundException e) { 188 | 189 | throw new SSOAgentException("Cannot find file " + properties.getProperty("KeyStore"), e); 190 | } 191 | } 192 | keyStorePassword = properties.getProperty("KeyStorePassword"); 193 | idPCertAlias = properties.getProperty("SAML.IdPCertAlias"); 194 | privateKeyAlias = properties.getProperty("SAML.PrivateKeyAlias"); 195 | privateKeyPassword = properties.getProperty("SAML.PrivateKeyPassword"); 196 | 197 | requestQueryParameters = properties.getProperty("SAML.Request.Query.Param"); 198 | 199 | addExtension = properties.getProperty("SAML.Request.Add.Extension"); 200 | 201 | } 202 | 203 | public static void initCheck() throws SSOAgentException { 204 | 205 | if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.getSAMLSSOUrl() == null) { 206 | throw new SSOAgentException("\'SAMLSSOUrl\' not configured"); 207 | } 208 | 209 | if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.getIssuerId() == null) { 210 | throw new SSOAgentException("\'SAML.IssuerId\' not configured"); 211 | } 212 | 213 | if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.getConsumerUrl() == null) { 214 | throw new SSOAgentException("\'SAML.ConsumerUrl\' not configured"); 215 | } 216 | 217 | if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.getIdPUrl() == null) { 218 | throw new SSOAgentException("\'SAML.IdPUrl\' not configured"); 219 | } 220 | 221 | if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.getAttributeConsumingServiceIndex() == null) { 222 | LOGGER.info("\'SAML.AttributeConsumingServiceIndex\' not configured. " + 223 | "No attributes of the Subject will be requested"); 224 | } 225 | 226 | if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && SSOAgentConfigs.isSLOEnabled() && 227 | SSOAgentConfigs.getLogoutUrl() == null) { 228 | throw new SSOAgentException("Single Logout enabled, but SAML.LogoutUrl not configured"); 229 | } 230 | 231 | if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && 232 | (SSOAgentConfigs.isResponseSigned() || SSOAgentConfigs.isAssertionSigned() || 233 | SSOAgentConfigs.isAssertionEncripted() || SSOAgentConfigs.isRequestSigned()) && 234 | SSOAgentConfigs.getSSOAgentCredentialImplClass() == null) { 235 | LOGGER.info("SAML.SSOAgentCredentialImplClass not configured." + 236 | " Defaulting to \'SSOAgentKeyStoreCredential\'"); 237 | SSOAgentConfigs.setSSOAgentCredentialImplClass( 238 | "SSOAgentKeyStoreCredential"); 239 | } 240 | 241 | if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && 242 | (SSOAgentConfigs.isResponseSigned() || SSOAgentConfigs.isAssertionSigned() || 243 | SSOAgentConfigs.isAssertionEncripted() || SSOAgentConfigs.isRequestSigned()) && 244 | SSOAgentConfigs.getSSOAgentCredentialImplClass() != null && 245 | SSOAgentConfigs.getKeyStoreStream() == null) { 246 | throw new SSOAgentException("KeyStore not configured"); 247 | } 248 | 249 | if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && 250 | (SSOAgentConfigs.isResponseSigned() || SSOAgentConfigs.isAssertionSigned() || 251 | SSOAgentConfigs.isAssertionEncripted() || SSOAgentConfigs.isRequestSigned()) && 252 | SSOAgentConfigs.getSSOAgentCredentialImplClass() != null && 253 | SSOAgentConfigs.getKeyStoreStream() != null && 254 | SSOAgentConfigs.getKeyStorePassword() == null) { 255 | LOGGER.info("KeyStorePassword not configured." + 256 | " Defaulting to \'wso2carbon\'"); 257 | SSOAgentConfigs.setKeyStorePassword("wso2carbon"); 258 | } 259 | 260 | if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && 261 | (SSOAgentConfigs.isResponseSigned() || SSOAgentConfigs.isAssertionSigned()) && 262 | SSOAgentConfigs.getSSOAgentCredentialImplClass() != null && SSOAgentConfigs.getIdPCertAlias() == null) { 263 | LOGGER.info("\'SAML.IdPCertAlias\' not configured. Defaulting to \'wso2carbon\'"); 264 | } 265 | 266 | if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && 267 | (SSOAgentConfigs.isRequestSigned() || SSOAgentConfigs.isAssertionEncripted()) && 268 | SSOAgentConfigs.getSSOAgentCredentialImplClass() != null && 269 | SSOAgentConfigs.getPrivateKeyAlias() == null) { 270 | LOGGER.info("SAML.PrivateKeyAlias not configured. Defaulting to \'wso2carbon\'"); 271 | SSOAgentConfigs.setPrivateKeyAlias("wso2carbon"); 272 | } 273 | 274 | if (SSOAgentConfigs.isSAMLSSOLoginEnabled() && 275 | (SSOAgentConfigs.isRequestSigned() || SSOAgentConfigs.isAssertionEncripted()) && 276 | SSOAgentConfigs.getSSOAgentCredentialImplClass() != null && 277 | SSOAgentConfigs.getPrivateKeyPassword() == null) { 278 | LOGGER.info("SAML.PrivateKeyPassword not configured. Defaulting to \'wso2carbon\'"); 279 | SSOAgentConfigs.setPrivateKeyPassword("wso2carbon"); 280 | } 281 | } 282 | 283 | public static boolean isSAMLSSOLoginEnabled() { 284 | 285 | return samlSSOLoginEnabled; 286 | } 287 | 288 | public static void setSAMLSSOLoginEnabled(Boolean samlSSOLoginEnabled) { 289 | 290 | SSOAgentConfigs.samlSSOLoginEnabled = samlSSOLoginEnabled; 291 | } 292 | 293 | public static String getSessionBeanName() { 294 | 295 | return sessionBeanName; 296 | } 297 | 298 | public static void setSessionBeanName(String sessionBeanName) { 299 | 300 | SSOAgentConfigs.sessionBeanName = sessionBeanName; 301 | } 302 | 303 | public static String getLoginUrl() { 304 | 305 | return loginUrl; 306 | } 307 | 308 | public static void setLoginUrl(String loginUrl) { 309 | 310 | SSOAgentConfigs.loginUrl = loginUrl; 311 | } 312 | 313 | public static String getSAMLSSOUrl() { 314 | 315 | return samlSSOUrl; 316 | } 317 | 318 | public static void setSAMLSSOUrl(String samlSSOUrl) { 319 | 320 | SSOAgentConfigs.samlSSOUrl = samlSSOUrl; 321 | } 322 | 323 | public static String getIssuerId() { 324 | 325 | return issuerId; 326 | } 327 | 328 | public static void setIssuerId(String issuerId) { 329 | 330 | SSOAgentConfigs.issuerId = issuerId; 331 | } 332 | 333 | public static String getConsumerUrl() { 334 | 335 | return consumerUrl; 336 | } 337 | 338 | public static void setConsumerUrl(String consumerUrl) { 339 | 340 | SSOAgentConfigs.consumerUrl = consumerUrl; 341 | } 342 | 343 | public static String getIdPUrl() { 344 | 345 | return idPUrl; 346 | } 347 | 348 | public static void setIdPUrl(String idPUrl) { 349 | 350 | SSOAgentConfigs.idPUrl = idPUrl; 351 | } 352 | 353 | public static String getAttributeConsumingServiceIndex() { 354 | 355 | return attributeConsumingServiceIndex; 356 | } 357 | 358 | public static void setAttributeConsumingServiceIndex(String attributeConsumingServiceIndex) { 359 | 360 | SSOAgentConfigs.attributeConsumingServiceIndex = attributeConsumingServiceIndex; 361 | } 362 | 363 | public static boolean isSLOEnabled() { 364 | 365 | return isSLOEnabled; 366 | } 367 | 368 | public static void setSLOEnabled(Boolean SLOEnabled) { 369 | 370 | isSLOEnabled = SLOEnabled; 371 | } 372 | 373 | public static String getLogoutUrl() { 374 | 375 | return logoutUrl; 376 | } 377 | 378 | public static void setLogoutUrl(String logoutUrl) { 379 | 380 | SSOAgentConfigs.logoutUrl = logoutUrl; 381 | } 382 | 383 | public static boolean isResponseSigned() { 384 | 385 | return isResponseSigned; 386 | } 387 | 388 | public static void setResponseSigned(Boolean responseSigned) { 389 | 390 | isResponseSigned = responseSigned; 391 | } 392 | 393 | public static boolean isAssertionSigned() { 394 | 395 | return isAssertionSigned; 396 | } 397 | 398 | public static void setAssertionSigned(Boolean assertionSigned) { 399 | 400 | isAssertionSigned = assertionSigned; 401 | } 402 | 403 | public static boolean isAssertionEncripted() { 404 | 405 | return isAssertionEncrypted; 406 | } 407 | 408 | public static boolean isRequestSigned() { 409 | 410 | return isRequestSigned; 411 | } 412 | 413 | public static void setRequestSigned(Boolean requestSigned) { 414 | 415 | isRequestSigned = requestSigned; 416 | } 417 | 418 | public static boolean isForceAuthn() { 419 | 420 | return isForceAuthn; 421 | } 422 | 423 | public static void setForceAuthn(Boolean forceAuthn) { 424 | 425 | isForceAuthn = forceAuthn; 426 | } 427 | 428 | public static String getSSOAgentCredentialImplClass() { 429 | 430 | return ssoAgentCredentialImplClass; 431 | } 432 | 433 | public static void setSSOAgentCredentialImplClass(String ssoAgentCredentialImplClass) { 434 | 435 | SSOAgentConfigs.ssoAgentCredentialImplClass = ssoAgentCredentialImplClass; 436 | } 437 | 438 | private static InputStream getKeyStoreStream() { 439 | 440 | return keyStoreStream; 441 | } 442 | 443 | public static void setKeyStoreStream(InputStream keyStoreStream) { 444 | 445 | if (SSOAgentConfigs.keyStoreStream == null) { 446 | SSOAgentConfigs.keyStoreStream = keyStoreStream; 447 | } 448 | } 449 | 450 | public static void setKeyStoreStream(String keyStore) throws SSOAgentException { 451 | 452 | try { 453 | SSOAgentConfigs.keyStoreStream = new FileInputStream(keyStore); 454 | } catch (FileNotFoundException e) { 455 | if (log.isDebugEnabled()) { 456 | log.debug("File not found : ", e); 457 | } 458 | 459 | throw new SSOAgentException("Cannot find file " + keyStore); 460 | } 461 | } 462 | 463 | private static String getKeyStorePassword() { 464 | 465 | return keyStorePassword; 466 | } 467 | 468 | public static void setKeyStorePassword(String keyStorePassword) { 469 | 470 | SSOAgentConfigs.keyStorePassword = keyStorePassword; 471 | } 472 | 473 | public static KeyStore getKeyStore() throws SSOAgentException { 474 | 475 | if (keyStore == null) { 476 | setKeyStore(readKeyStore(getKeyStoreStream(), getKeyStorePassword())); 477 | } 478 | return keyStore; 479 | } 480 | 481 | public static void setKeyStore(KeyStore keyStore) { 482 | 483 | SSOAgentConfigs.keyStore = keyStore; 484 | } 485 | 486 | public static String getIdPCertAlias() { 487 | 488 | return idPCertAlias; 489 | } 490 | 491 | public static void setIdPCertAlias(String idPCertAlias) { 492 | 493 | SSOAgentConfigs.idPCertAlias = idPCertAlias; 494 | } 495 | 496 | public static String getPrivateKeyAlias() { 497 | 498 | return privateKeyAlias; 499 | } 500 | 501 | public static void setPrivateKeyAlias(String privateKeyAlias) { 502 | 503 | SSOAgentConfigs.privateKeyAlias = privateKeyAlias; 504 | } 505 | 506 | public static String getPrivateKeyPassword() { 507 | 508 | return privateKeyPassword; 509 | } 510 | 511 | public static void setPrivateKeyPassword(String privateKeyPassword) { 512 | 513 | SSOAgentConfigs.privateKeyPassword = privateKeyPassword; 514 | } 515 | 516 | public static void setAssertionEncrypted(Boolean assertionEncrypted) { 517 | 518 | isAssertionEncrypted = assertionEncrypted; 519 | } 520 | 521 | public static String getRequestQueryParameters() { 522 | 523 | return requestQueryParameters; 524 | } 525 | 526 | public static String getAddExtension() { 527 | 528 | return addExtension; 529 | } 530 | 531 | public static void setAddExtension(String addExtension) { 532 | 533 | SSOAgentConfigs.addExtension = addExtension; 534 | } 535 | 536 | /** 537 | * get the key store instance 538 | * 539 | * @param is KeyStore InputStream 540 | * @param storePassword password of key store 541 | * @return KeyStore instant 542 | * @throws SSOAgentException if fails to load key store 543 | */ 544 | private static KeyStore readKeyStore(InputStream is, String storePassword) throws SSOAgentException { 545 | 546 | if (storePassword == null) { 547 | throw new SSOAgentException("KeyStore password can not be null"); 548 | } 549 | 550 | try { 551 | KeyStore keyStore = KeyStore.getInstance("JKS"); 552 | keyStore.load(is, storePassword.toCharArray()); 553 | return keyStore; 554 | } catch (Exception e) { 555 | 556 | throw new SSOAgentException("Error while loading key store file", e); 557 | } finally { 558 | if (is != null) { 559 | try { 560 | is.close(); 561 | } catch (IOException ignored) { 562 | 563 | throw new SSOAgentException("Error while closing input stream of key store", ignored); 564 | } 565 | } 566 | } 567 | } 568 | } 569 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/util/SSOAgentUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | * 18 | * 19 | */ 20 | 21 | package io.asgardeo.java.saml.sdk.util; 22 | 23 | import net.shibboleth.utilities.java.support.codec.Base64Support; 24 | import org.apache.commons.lang.StringUtils; 25 | import org.apache.xerces.impl.Constants; 26 | import org.apache.xerces.util.SecurityManager; 27 | import org.apache.xml.security.c14n.Canonicalizer; 28 | import org.apache.xml.security.signature.XMLSignature; 29 | import org.opensaml.core.config.InitializationException; 30 | import org.opensaml.core.config.InitializationService; 31 | import org.opensaml.core.xml.XMLObject; 32 | import org.opensaml.core.xml.XMLObjectBuilder; 33 | import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; 34 | import org.opensaml.core.xml.io.Marshaller; 35 | import org.opensaml.core.xml.io.MarshallerFactory; 36 | import org.opensaml.core.xml.io.Unmarshaller; 37 | import org.opensaml.core.xml.io.UnmarshallerFactory; 38 | import org.opensaml.core.xml.io.UnmarshallingException; 39 | import org.opensaml.saml.saml2.core.ArtifactResolve; 40 | import org.opensaml.saml.saml2.core.AuthnRequest; 41 | import org.opensaml.saml.saml2.core.LogoutRequest; 42 | import org.opensaml.security.x509.X509Credential; 43 | import org.opensaml.xmlsec.signature.KeyInfo; 44 | import org.opensaml.xmlsec.signature.SignableXMLObject; 45 | import org.opensaml.xmlsec.signature.Signature; 46 | import org.opensaml.xmlsec.signature.X509Data; 47 | import org.opensaml.xmlsec.signature.support.Signer; 48 | import org.opensaml.saml.config.SAMLConfigurationInitializer; 49 | import org.opensaml.core.xml.config.GlobalParserPoolInitializer; 50 | import org.opensaml.xmlsec.config.JavaCryptoValidationInitializer; 51 | import org.opensaml.xmlsec.config.ApacheXMLSecurityInitializer; 52 | import org.opensaml.xmlsec.config.GlobalSecurityConfigurationInitializer; 53 | import org.opensaml.xmlsec.config.GlobalAlgorithmRegistryInitializer; 54 | 55 | import org.w3c.dom.Document; 56 | import org.w3c.dom.Element; 57 | import org.w3c.dom.NodeList; 58 | import org.w3c.dom.bootstrap.DOMImplementationRegistry; 59 | import org.w3c.dom.ls.DOMImplementationLS; 60 | import org.w3c.dom.ls.LSOutput; 61 | import org.w3c.dom.ls.LSSerializer; 62 | import io.asgardeo.java.saml.sdk.exception.SSOAgentException; 63 | import org.xml.sax.SAXException; 64 | 65 | import java.io.ByteArrayInputStream; 66 | import java.io.ByteArrayOutputStream; 67 | import java.io.IOException; 68 | import java.io.Writer; 69 | import java.net.URLEncoder; 70 | import java.nio.charset.Charset; 71 | import java.security.cert.CertificateEncodingException; 72 | import java.util.ArrayList; 73 | import java.util.List; 74 | import java.util.Random; 75 | import java.util.logging.Level; 76 | import java.util.logging.Logger; 77 | 78 | import javax.servlet.http.HttpServletRequest; 79 | import javax.servlet.http.HttpServletResponse; 80 | import javax.xml.XMLConstants; 81 | import javax.xml.namespace.QName; 82 | import javax.xml.parsers.DocumentBuilder; 83 | import javax.xml.parsers.DocumentBuilderFactory; 84 | import javax.xml.parsers.ParserConfigurationException; 85 | import javax.xml.xpath.XPath; 86 | import javax.xml.xpath.XPathConstants; 87 | import javax.xml.xpath.XPathExpressionException; 88 | import javax.xml.xpath.XPathFactory; 89 | 90 | public class SSOAgentUtils { 91 | 92 | private static final int ENTITY_EXPANSION_LIMIT = 0; 93 | private static Logger LOGGER = Logger.getLogger(SSOAgentConstants.LOGGER_NAME); 94 | private static boolean isBootStrapped = false; 95 | private static Random random = new Random(); 96 | 97 | private SSOAgentUtils() { 98 | 99 | } 100 | 101 | /** 102 | * Generates a unique Id for Authentication Requests 103 | * 104 | * @return generated unique ID 105 | */ 106 | 107 | public static String createID() { 108 | 109 | byte[] bytes = new byte[20]; // 160 bit 110 | 111 | random.nextBytes(bytes); 112 | 113 | char[] charMapping = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'}; 114 | 115 | char[] chars = new char[40]; 116 | 117 | for (int i = 0; i < bytes.length; i++) { 118 | int left = (bytes[i] >> 4) & 0x0f; 119 | int right = bytes[i] & 0x0f; 120 | chars[i * 2] = charMapping[left]; 121 | chars[i * 2 + 1] = charMapping[right]; 122 | } 123 | 124 | return String.valueOf(chars); 125 | } 126 | 127 | public static void doBootstrap() throws SSOAgentException { 128 | if (!isBootStrapped) { 129 | Thread thread = Thread.currentThread(); 130 | ClassLoader originalClassLoader = thread.getContextClassLoader(); 131 | thread.setContextClassLoader(InitializationService.class.getClassLoader()); 132 | 133 | try { 134 | 135 | InitializationService.initialize(); 136 | 137 | SAMLConfigurationInitializer samlConfigurationInitializer = new SAMLConfigurationInitializer(); 138 | samlConfigurationInitializer.init(); 139 | 140 | org.opensaml.saml.config.XMLObjectProviderInitializer samlXMLObjectProviderInitializer = new org.opensaml.saml.config.XMLObjectProviderInitializer(); 141 | samlXMLObjectProviderInitializer.init(); 142 | 143 | org.opensaml.core.xml.config.XMLObjectProviderInitializer coreXMLObjectProviderInitializer = new org.opensaml.core.xml.config.XMLObjectProviderInitializer(); 144 | coreXMLObjectProviderInitializer.init(); 145 | 146 | GlobalParserPoolInitializer globalParserPoolInitializer = new GlobalParserPoolInitializer(); 147 | globalParserPoolInitializer.init(); 148 | 149 | JavaCryptoValidationInitializer javaCryptoValidationInitializer = new JavaCryptoValidationInitializer(); 150 | javaCryptoValidationInitializer.init(); 151 | 152 | org.opensaml.xmlsec.config.XMLObjectProviderInitializer xmlsecXMLObjectProviderInitializer = new org.opensaml.xmlsec.config.XMLObjectProviderInitializer(); 153 | xmlsecXMLObjectProviderInitializer.init(); 154 | 155 | ApacheXMLSecurityInitializer apacheXMLSecurityInitializer = new ApacheXMLSecurityInitializer(); 156 | apacheXMLSecurityInitializer.init(); 157 | 158 | GlobalSecurityConfigurationInitializer globalSecurityConfigurationInitializer = new GlobalSecurityConfigurationInitializer(); 159 | globalSecurityConfigurationInitializer.init(); 160 | 161 | GlobalAlgorithmRegistryInitializer globalAlgorithmRegistryInitializer = new GlobalAlgorithmRegistryInitializer(); 162 | globalAlgorithmRegistryInitializer.init(); 163 | 164 | org.opensaml.soap.config.XMLObjectProviderInitializer soapXMLObjectProviderInitializer = new org.opensaml 165 | .soap.config.XMLObjectProviderInitializer(); 166 | soapXMLObjectProviderInitializer.init(); 167 | isBootStrapped = true; 168 | } catch (InitializationException e) { 169 | throw new SSOAgentException("Error in bootstrapping the OpenSAML3 library", e); 170 | } finally { 171 | thread.setContextClassLoader(originalClassLoader); 172 | } 173 | } 174 | } 175 | 176 | /** 177 | * Sign the SAML AuthnRequest message 178 | * 179 | * @param authnRequest 180 | * @param signatureAlgorithm 181 | * @param cred 182 | * @return 183 | * @throws SSOAgentException 184 | */ 185 | public static AuthnRequest setSignature(AuthnRequest authnRequest, String signatureAlgorithm, 186 | X509Credential cred) throws SSOAgentException { 187 | 188 | doBootstrap(); 189 | return setSignatureValue(authnRequest, signatureAlgorithm, cred); 190 | } 191 | 192 | /** 193 | * Sign the SAML AuthnRequest message 194 | * 195 | * @param logoutRequest 196 | * @param signatureAlgorithm 197 | * @param cred 198 | * @return 199 | * @throws SSOAgentException 200 | */ 201 | public static LogoutRequest setSignature(LogoutRequest logoutRequest, String signatureAlgorithm, 202 | X509Credential cred) throws SSOAgentException { 203 | 204 | return setSignatureValue(logoutRequest, signatureAlgorithm, cred); 205 | } 206 | 207 | /** 208 | * Sign SAML2 Artifact Resolve. 209 | * 210 | * @param artifactResolve ArtifactResolve object to be signed. 211 | * @param signatureAlgorithm Signature algorithm. 212 | * @param cred X509 Credential. 213 | * @return Signed Artifact Resolve object. 214 | * @throws SSOAgentException 215 | */ 216 | public static ArtifactResolve setSignature(ArtifactResolve artifactResolve, String signatureAlgorithm, 217 | X509Credential cred) throws SSOAgentException { 218 | 219 | return setSignatureValue(artifactResolve, signatureAlgorithm, cred); 220 | } 221 | 222 | /** 223 | * Add signature to any singable XML object. 224 | * 225 | * @param xmlObject Singable xml object. 226 | * @param signatureAlgorithm Signature algorithm to be used. 227 | * @param cred X509 Credentials. 228 | * @param Singable XML object with signature. 229 | * @return Singable XML object with signature. 230 | * @throws SSOAgentException If error occurred. 231 | */ 232 | public static T setSignatureValue(T xmlObject, String signatureAlgorithm, 233 | X509Credential cred) 234 | throws SSOAgentException { 235 | 236 | try { 237 | Signature signature = setSignatureRaw(signatureAlgorithm, cred); 238 | xmlObject.setSignature(signature); 239 | 240 | List signatureList = new ArrayList<>(); 241 | signatureList.add(signature); 242 | 243 | // Marshall and Sign 244 | MarshallerFactory marshallerFactory = 245 | XMLObjectProviderRegistrySupport.getMarshallerFactory(); 246 | Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject); 247 | 248 | marshaller.marshall(xmlObject); 249 | 250 | org.apache.xml.security.Init.init(); 251 | Signer.signObjects(signatureList); 252 | return xmlObject; 253 | } catch (Exception e) { 254 | throw new SSOAgentException("Error while signing the SAML Request message", e); 255 | } 256 | } 257 | 258 | private static Signature setSignatureRaw(String signatureAlgorithm, X509Credential cred) throws SSOAgentException { 259 | 260 | Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME); 261 | signature.setSigningCredential(cred); 262 | signature.setSignatureAlgorithm(signatureAlgorithm); 263 | signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); 264 | 265 | try { 266 | KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME); 267 | X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME); 268 | org.opensaml.xmlsec.signature.X509Certificate cert = 269 | (org.opensaml.xmlsec.signature.X509Certificate) buildXMLObject( 270 | org.opensaml.xmlsec.signature.X509Certificate.DEFAULT_ELEMENT_NAME); 271 | String value = 272 | org.apache.xml.security.utils.Base64.encode(cred.getEntityCertificate().getEncoded()); 273 | cert.setValue(value); 274 | data.getX509Certificates().add(cert); 275 | keyInfo.getX509Datas().add(data); 276 | signature.setKeyInfo(keyInfo); 277 | return signature; 278 | 279 | } catch (CertificateEncodingException e) { 280 | throw new SSOAgentException("Error getting certificate", e); 281 | } 282 | } 283 | 284 | public static void addDeflateSignatureToHTTPQueryString(StringBuilder httpQueryString, 285 | X509Credential cred) throws SSOAgentException { 286 | 287 | doBootstrap(); 288 | try { 289 | httpQueryString.append("&SigAlg=" 290 | + URLEncoder.encode(XMLSignature.ALGO_ID_SIGNATURE_RSA, "UTF-8").trim()); 291 | 292 | java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA"); 293 | signature.initSign(cred.getPrivateKey()); 294 | signature.update(httpQueryString.toString().getBytes(Charset.forName("UTF-8"))); 295 | byte[] signatureByteArray = signature.sign(); 296 | 297 | String signatureBase64encodedString = Base64Support.encode(signatureByteArray, 298 | Base64Support.UNCHUNKED); 299 | httpQueryString.append("&Signature=" 300 | + URLEncoder.encode(signatureBase64encodedString, "UTF-8").trim()); 301 | } catch (Exception e) { 302 | throw new SSOAgentException("Error applying SAML2 Redirect Binding signature", e); 303 | } 304 | } 305 | 306 | /** 307 | * Builds SAML Elements 308 | * 309 | * @param objectQName 310 | * @return 311 | * @throws SSOAgentException 312 | */ 313 | private static XMLObject buildXMLObject(QName objectQName) throws SSOAgentException { 314 | 315 | doBootstrap(); 316 | XMLObjectBuilder builder = 317 | XMLObjectProviderRegistrySupport.getBuilderFactory() 318 | .getBuilder(objectQName); 319 | if (builder == null) { 320 | throw new SSOAgentException("Unable to retrieve builder for object QName " + 321 | objectQName); 322 | } 323 | return builder.buildObject(objectQName.getNamespaceURI(), objectQName.getLocalPart(), 324 | objectQName.getPrefix()); 325 | } 326 | 327 | public static void sendPostResponse(HttpServletRequest request, HttpServletResponse response, 328 | String htmlPayload) 329 | throws SSOAgentException { 330 | 331 | Writer writer = null; 332 | try { 333 | writer = response.getWriter(); 334 | writer.write(htmlPayload); 335 | response.flushBuffer(); 336 | } catch (IOException e) { 337 | throw new SSOAgentException("Error occurred while writing to HttpServletResponse", e); 338 | } finally { 339 | if (writer != null) { 340 | try { 341 | writer.close(); 342 | } catch (IOException e) { 343 | LOGGER.log(Level.WARNING, "Error occurred while closing Writer", e); 344 | } 345 | } 346 | } 347 | } 348 | 349 | /** 350 | * Serializing a SAML2 object into a String. 351 | * 352 | * @param xmlObject object that needs to serialized. 353 | * @return serialized object 354 | * @throws SSOAgentException 355 | */ 356 | public static String marshall(XMLObject xmlObject) throws SSOAgentException { 357 | 358 | try { 359 | MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport 360 | .getMarshallerFactory(); 361 | Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject); 362 | Element element = marshaller.marshall(xmlObject); 363 | 364 | ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream(); 365 | DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); 366 | DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); 367 | LSSerializer writer = impl.createLSSerializer(); 368 | LSOutput output = impl.createLSOutput(); 369 | output.setByteStream(byteArrayOutputStrm); 370 | writer.write(element, output); 371 | return byteArrayOutputStrm.toString(); 372 | } catch (Exception e) { 373 | throw new SSOAgentException("Error Serializing the SAML Response", e); 374 | } 375 | } 376 | 377 | public static XMLObject unmarshall(String saml2SSOString) throws SSOAgentException { 378 | 379 | doBootstrap(); 380 | 381 | DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 382 | documentBuilderFactory.setNamespaceAware(true); 383 | documentBuilderFactory.setXIncludeAware(false); 384 | documentBuilderFactory.setExpandEntityReferences(false); 385 | try { 386 | documentBuilderFactory 387 | .setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false); 388 | documentBuilderFactory 389 | .setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false); 390 | documentBuilderFactory 391 | .setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false); 392 | documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); 393 | 394 | } catch (ParserConfigurationException e) { 395 | LOGGER.log(Level.SEVERE, 396 | "Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE + " or " + 397 | Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or " + 398 | Constants.LOAD_EXTERNAL_DTD_FEATURE + 399 | " or secure-processing."); 400 | } 401 | 402 | org.apache.xerces.util.SecurityManager securityManager = new SecurityManager(); 403 | securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT); 404 | documentBuilderFactory 405 | .setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager); 406 | 407 | try { 408 | documentBuilderFactory.setIgnoringComments(true); 409 | Document document = getDocument(documentBuilderFactory, saml2SSOString); 410 | if (isSignedWithComments(document)) { 411 | documentBuilderFactory.setIgnoringComments(false); 412 | document = getDocument(documentBuilderFactory, saml2SSOString); 413 | } 414 | Element element = document.getDocumentElement(); 415 | UnmarshallerFactory unmarshallerFactory = XMLObjectProviderRegistrySupport.getUnmarshallerFactory(); 416 | Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element); 417 | return unmarshaller.unmarshall(element); 418 | } catch (ParserConfigurationException e) { 419 | throw new SSOAgentException("Error in unmarshalling SAML2SSO Request from the encoded String", e); 420 | } catch (UnmarshallingException e) { 421 | throw new SSOAgentException("Error in unmarshalling SAML2SSO Request from the encoded String", e); 422 | } catch (SAXException e) { 423 | throw new SSOAgentException("Error in unmarshalling SAML2SSO Request from the encoded String", e); 424 | } catch (IOException e) { 425 | throw new SSOAgentException("Error in unmarshalling SAML2SSO Request from the encoded String", e); 426 | } 427 | 428 | } 429 | 430 | /** 431 | * Return whether SAML Assertion has the canonicalization method 432 | * set to 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments'. 433 | * 434 | * @param document 435 | * @return true if canonicalization method equals to 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments' 436 | */ 437 | private static boolean isSignedWithComments(Document document) { 438 | 439 | XPath xPath = XPathFactory.newInstance().newXPath(); 440 | try { 441 | String assertionId = (String) xPath.compile("//*[local-name()='Assertion']/@ID") 442 | .evaluate(document, XPathConstants.STRING); 443 | 444 | if (StringUtils.isBlank(assertionId)) { 445 | return false; 446 | } 447 | 448 | NodeList nodeList = ((NodeList) xPath.compile( 449 | "//*[local-name()='Assertion']" + 450 | "/*[local-name()='Signature']" + 451 | "/*[local-name()='SignedInfo']" + 452 | "/*[local-name()='Reference'][@URI='#" + assertionId + "']" + 453 | "/*[local-name()='Transforms']" + 454 | "/*[local-name()='Transform']" + 455 | "[@Algorithm='http://www.w3.org/2001/10/xml-exc-c14n#WithComments']") 456 | .evaluate(document, XPathConstants.NODESET)); 457 | return nodeList != null && nodeList.getLength() > 0; 458 | } catch (XPathExpressionException e) { 459 | String message = "Failed to find the canonicalization algorithm of the assertion. Defaulting to: " + 460 | "http://www.w3.org/2001/10/xml-exc-c14n#"; 461 | LOGGER.log(Level.WARNING, message); 462 | return false; 463 | } 464 | } 465 | 466 | private static Document getDocument(DocumentBuilderFactory documentBuilderFactory, String samlString) 467 | throws IOException, SAXException, ParserConfigurationException { 468 | 469 | DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder(); 470 | ByteArrayInputStream inputStream = new ByteArrayInputStream(samlString.getBytes()); 471 | return docBuilder.parse(inputStream); 472 | } 473 | } 474 | -------------------------------------------------------------------------------- /io.asgardeo.java.saml.sdk/src/main/java/io/asgardeo/java/saml/sdk/bean/SSOAgentConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | * 18 | * 19 | */ 20 | 21 | package io.asgardeo.java.saml.sdk.bean; 22 | 23 | import io.asgardeo.java.saml.sdk.AESDecryptor; 24 | import io.asgardeo.java.saml.sdk.exception.SSOAgentException; 25 | import io.asgardeo.java.saml.sdk.request.SAML2IdleRequestCleanupTask; 26 | import io.asgardeo.java.saml.sdk.security.SSOAgentX509Credential; 27 | import io.asgardeo.java.saml.sdk.util.SSOAgentConstants; 28 | import org.apache.commons.lang.ArrayUtils; 29 | import org.apache.commons.lang.StringUtils; 30 | import org.apache.http.client.utils.URIBuilder; 31 | import org.opensaml.saml.common.xml.SAMLConstants; 32 | 33 | import java.io.BufferedReader; 34 | import java.io.FileInputStream; 35 | import java.io.FileNotFoundException; 36 | import java.io.IOException; 37 | import java.io.InputStream; 38 | import java.net.URISyntaxException; 39 | import java.nio.charset.Charset; 40 | import java.nio.file.Files; 41 | import java.nio.file.Path; 42 | import java.nio.file.Paths; 43 | import java.security.KeyStore; 44 | import java.util.ArrayList; 45 | import java.util.Arrays; 46 | import java.util.HashMap; 47 | import java.util.HashSet; 48 | import java.util.List; 49 | import java.util.Map; 50 | import java.util.Properties; 51 | import java.util.Set; 52 | import java.util.concurrent.Executors; 53 | import java.util.concurrent.ScheduledExecutorService; 54 | import java.util.concurrent.TimeUnit; 55 | import java.util.logging.Level; 56 | import java.util.logging.Logger; 57 | import javax.net.ssl.HostnameVerifier; 58 | import javax.net.ssl.HttpsURLConnection; 59 | import javax.net.ssl.SSLContext; 60 | import javax.net.ssl.SSLSession; 61 | import javax.net.ssl.SSLSocketFactory; 62 | import javax.net.ssl.TrustManager; 63 | import javax.net.ssl.TrustManagerFactory; 64 | import javax.net.ssl.X509TrustManager; 65 | 66 | public class SSOAgentConfig { 67 | 68 | private static final Logger LOGGER = Logger.getLogger(SSOAgentConstants.LOGGER_NAME); 69 | private static final String ARGUMENT = "sun.java.command"; 70 | 71 | private Boolean isSAML2SSOLoginEnabled = false; 72 | 73 | private String saml2SSOURL = null; 74 | private Set skipURIs = new HashSet(); 75 | private String indexPage; 76 | private String errorPage; 77 | private boolean skipKeystoreConfigs; 78 | 79 | private Map queryParams = new HashMap(); 80 | 81 | private SAML2 saml2 = new SAML2(); 82 | private String requestQueryParameters; 83 | private Boolean enableHostNameVerification = false; 84 | private Boolean enableSSLVerification = false; 85 | private InputStream keyStoreStream; 86 | private String keyStorePassword; 87 | private KeyStore keyStore; 88 | private String privateKeyPassword; 89 | private String privateKeyAlias; 90 | private String idpPublicCertAlias; 91 | private int idleTimeOutInMinutes; 92 | 93 | public Boolean getEnableHostNameVerification() { 94 | 95 | return enableHostNameVerification; 96 | } 97 | 98 | public Boolean getEnableSSLVerification() { 99 | 100 | return enableSSLVerification; 101 | } 102 | 103 | public String getRequestQueryParameters() { 104 | 105 | return requestQueryParameters; 106 | } 107 | 108 | public Boolean isSAML2SSOLoginEnabled() { 109 | 110 | return isSAML2SSOLoginEnabled; 111 | } 112 | 113 | public String getSAML2SSOURL() { 114 | 115 | return saml2SSOURL; 116 | } 117 | 118 | public void setSAML2SSOURL(String saml2SSOURL) { 119 | 120 | this.saml2SSOURL = saml2SSOURL; 121 | } 122 | 123 | public Set getSkipURIs() { 124 | 125 | return skipURIs; 126 | } 127 | 128 | public void setSkipURIs(Set skipURIs) { 129 | 130 | this.skipURIs = skipURIs; 131 | } 132 | 133 | public String getIndexPage() { 134 | 135 | return indexPage; 136 | } 137 | 138 | public void setIndexPage(String indexPage) { 139 | 140 | this.indexPage = indexPage; 141 | } 142 | 143 | public String getErrorPage() { 144 | 145 | return errorPage; 146 | } 147 | 148 | public void setErrorPage(String errorPage) { 149 | 150 | this.errorPage = errorPage; 151 | } 152 | 153 | public Map getQueryParams() { 154 | 155 | return queryParams; 156 | } 157 | 158 | public void setQueryParams(Map queryParams) { 159 | 160 | this.queryParams = queryParams; 161 | } 162 | 163 | public SAML2 getSAML2() { 164 | 165 | return saml2; 166 | } 167 | 168 | public void setSAML2SSOLoginEnabled(Boolean isSAML2SSOLoginEnabled) { 169 | 170 | this.isSAML2SSOLoginEnabled = isSAML2SSOLoginEnabled; 171 | } 172 | 173 | private InputStream getKeyStoreStream() { 174 | 175 | return keyStoreStream; 176 | } 177 | 178 | public void setKeyStoreStream(InputStream keyStoreStream) { 179 | 180 | if (this.keyStoreStream == null) { 181 | this.keyStoreStream = keyStoreStream; 182 | } 183 | } 184 | 185 | public String getPrivateKeyPassword() { 186 | 187 | return privateKeyPassword; 188 | } 189 | 190 | public String getPrivateKeyAlias() { 191 | 192 | return privateKeyAlias; 193 | } 194 | 195 | public String getIdPPublicCertAlias() { 196 | 197 | return idpPublicCertAlias; 198 | } 199 | 200 | public String getKeyStorePassword() { 201 | 202 | return keyStorePassword; 203 | } 204 | 205 | public void setKeyStorePassword(String keyStorePassword) { 206 | 207 | this.keyStorePassword = keyStorePassword; 208 | } 209 | 210 | public KeyStore getKeyStore() throws SSOAgentException { 211 | 212 | if (keyStore == null) { 213 | setKeyStore(readKeyStore(getKeyStoreStream(), getKeyStorePassword())); 214 | } 215 | return keyStore; 216 | } 217 | 218 | public void setKeyStore(KeyStore keyStore) { 219 | 220 | this.keyStore = keyStore; 221 | } 222 | 223 | public int getIdleTimeOutInMinutes() { 224 | 225 | return idleTimeOutInMinutes; 226 | } 227 | 228 | public void setIdleTimeOutInMinutes(int idleTimeOutInMinutes) { 229 | 230 | this.idleTimeOutInMinutes = idleTimeOutInMinutes; 231 | } 232 | 233 | public void initConfig(Properties properties) throws SSOAgentException { 234 | 235 | String decodedPassword; 236 | boolean isReadpassword = false; 237 | char[] password = null; 238 | 239 | // Get copy of properties for looping in order to avoid ConcurrentModificationException. 240 | Properties copyOfProperties = new Properties(); 241 | copyOfProperties.putAll(properties); 242 | 243 | // Path of the password file. 244 | String filePath = System.getProperty("catalina.home") + SSOAgentConstants.SSOAgentConfig.PASSWORD_FILEPATH; 245 | 246 | // Looping through properties to check the encrypted property value by checking the prefix Enc:. 247 | for (Map.Entry entry : copyOfProperties.entrySet()) { 248 | if (String.valueOf(entry.getValue()).startsWith("Enc:")) { 249 | if (!System.getProperty(ARGUMENT).contains("password")) { 250 | 251 | // Check whether the password has been already read. 252 | if (!isReadpassword) { 253 | Path path = Paths.get(filePath); 254 | try (BufferedReader reader = Files.newBufferedReader(path, Charset.forName("UTF-8"))) { 255 | StringBuilder currentLine = new StringBuilder(); 256 | 257 | // Read the password from the password file. 258 | currentLine.append(reader.readLine()); 259 | if (currentLine.length() > 0) { 260 | password = new char[currentLine.length()]; 261 | currentLine.getChars(0, currentLine.length(), password, 0); 262 | currentLine = null; 263 | } 264 | isReadpassword = true; 265 | if (Files.deleteIfExists(path)) { 266 | LOGGER.info("Deleted the temporary password file at " + path); 267 | } 268 | } catch (IOException ex) { 269 | throw new SSOAgentException("Error while reading the file ", ex); 270 | } 271 | } 272 | } else if (!isReadpassword) { 273 | 274 | // Read password from the console. 275 | System.out.print("Enter password for decryption:"); 276 | password = System.console().readPassword(); 277 | isReadpassword = true; 278 | } 279 | if (ArrayUtils.isEmpty(password)) { 280 | LOGGER.log(Level.SEVERE, "Can't find the password to decrypt the encrypted values."); 281 | return; 282 | } 283 | 284 | // Get the encrypted property value. 285 | String encryptedValue = String.valueOf(entry.getValue()); 286 | 287 | // Remove the Enc: prefix and get the actual encrypted value. 288 | if (encryptedValue.split(":").length > 1) { 289 | decodedPassword = AESDecryptor.decrypt(String.valueOf(entry.getValue()).split 290 | (":")[1].trim(), password); 291 | 292 | // Remove the encrypted property value and replace with decrypted property value (plain text) 293 | properties.remove(String.valueOf(entry.getKey())); 294 | properties.setProperty(String.valueOf(entry.getKey()), decodedPassword); 295 | } else { 296 | LOGGER.log(Level.SEVERE, "Encrypted value is not in the correct format. Encrypted value " + 297 | "must contain the encrypted value with Enc: as prefix."); 298 | return; 299 | } 300 | } 301 | } 302 | 303 | // Delete the stored password from memory by filling with zeros. 304 | if (password != null) { 305 | Arrays.fill(password, (char) 0); 306 | } 307 | privateKeyPassword = getKeystoreConfig(SSOAgentConstants.PRIVATE_KEY_PASSWORD, properties); 308 | privateKeyAlias = getKeystoreConfig(SSOAgentConstants.PRIVATE_KEY_ALIAS, properties); 309 | idpPublicCertAlias = getKeystoreConfig(SSOAgentConstants.IDP_PUBLIC_CERT_ALIAS, properties); 310 | requestQueryParameters = properties.getProperty("SAML.Request.Query.Param"); 311 | if (properties.getProperty("SSL.EnableSSLVerification") != null) { 312 | enableSSLVerification = Boolean.parseBoolean(properties.getProperty("SSL.EnableSSLVerification")); 313 | } 314 | if (properties.getProperty("SSL.EnableSSLHostNameVerification") != null) { 315 | enableHostNameVerification = 316 | Boolean.parseBoolean(properties.getProperty("SSL.EnableSSLHostNameVerification")); 317 | } 318 | String isSAML2SSOLoginEnabledString = properties.getProperty( 319 | SSOAgentConstants.SSOAgentConfig.ENABLE_SAML2_SSO_LOGIN); 320 | if (isSAML2SSOLoginEnabledString != null) { 321 | isSAML2SSOLoginEnabled = Boolean.parseBoolean(isSAML2SSOLoginEnabledString); 322 | } else { 323 | LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.ENABLE_SAML2_SSO_LOGIN + 324 | " not configured. Defaulting to \'false\'"); 325 | isSAML2SSOLoginEnabled = false; 326 | } 327 | 328 | saml2SSOURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2_SSO_URL); 329 | 330 | String skipURIsString = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SKIP_URIS); 331 | if (!StringUtils.isBlank(skipURIsString)) { 332 | String[] skipURIArray = skipURIsString.split(","); 333 | for (String skipURI : skipURIArray) { 334 | skipURIs.add(skipURI); 335 | } 336 | } 337 | if (!StringUtils.isBlank(properties.getProperty(SSOAgentConstants.SSOAgentConfig.INDEX_PAGE))) { 338 | setIndexPage(properties.getProperty(SSOAgentConstants.SSOAgentConfig.INDEX_PAGE)); 339 | skipURIs.add(indexPage); 340 | } else { 341 | try { 342 | setIndexPage(buildIndexPageURL(properties)); 343 | } catch (URISyntaxException e) { 344 | throw new SSOAgentException("Error while fetching index page URL.", e); 345 | } 346 | } 347 | 348 | if (StringUtils.isNotBlank(properties.getProperty(SSOAgentConstants.SSOAgentConfig.ERROR_PAGE))) { 349 | setErrorPage(properties.getProperty(SSOAgentConstants.SSOAgentConfig.ERROR_PAGE)); 350 | skipURIs.add(errorPage); 351 | } else { 352 | setErrorPage(indexPage); 353 | } 354 | 355 | String queryParamsString = properties.getProperty(SSOAgentConstants.SSOAgentConfig.QUERY_PARAMS); 356 | if (!StringUtils.isBlank(queryParamsString)) { 357 | String[] queryParamsArray = queryParamsString.split("&"); 358 | Map> queryParamMap = new HashMap>(); 359 | if (queryParamsArray.length > 0) { 360 | for (String queryParam : queryParamsArray) { 361 | String[] splitParam = queryParam.split("="); 362 | if (splitParam.length == 2) { 363 | if (queryParamMap.get(splitParam[0]) != null) { 364 | queryParamMap.get(splitParam[0]).add(splitParam[1]); 365 | } else { 366 | List newList = new ArrayList(); 367 | newList.add(splitParam[1]); 368 | queryParamMap.put(splitParam[0], newList); 369 | } 370 | } 371 | 372 | } 373 | for (Map.Entry> entry : queryParamMap.entrySet()) { 374 | String[] valueArray = entry.getValue().toArray(new String[entry.getValue().size()]); 375 | queryParams.put(entry.getKey(), valueArray); 376 | } 377 | } 378 | } 379 | 380 | if (StringUtils.isNotBlank(properties.getProperty(SSOAgentConstants.IDLE_TIME_OUT_IN_MINUTES))) { 381 | try { 382 | idleTimeOutInMinutes = Integer.parseInt(properties.getProperty(SSOAgentConstants.IDLE_TIME_OUT_IN_MINUTES)); 383 | } catch (NumberFormatException e) { 384 | idleTimeOutInMinutes = 1440; 385 | LOGGER.info("\'IdleTimeOutInMinutes\' value is invalid. Defaulting to \'1440\' (One day)."); 386 | } 387 | } 388 | 389 | if (idleTimeOutInMinutes <= 0) { 390 | idleTimeOutInMinutes = 1440; 391 | LOGGER.info("\'IdleTimeOutInMinutes\' value is not configured or invalid. Defaulting to \'1440\' " 392 | + "(One day)."); 393 | } 394 | 395 | // Schedule invalid request cleanup task. 396 | scheduleIdleRequestCleanupTask(idleTimeOutInMinutes); 397 | 398 | saml2.httpBinding = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.HTTP_BINDING); 399 | if (saml2.httpBinding == null || saml2.httpBinding.isEmpty()) { 400 | LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.SAML2.HTTP_BINDING + 401 | " not configured. Defaulting to \'" + SAMLConstants.SAML2_POST_BINDING_URI + "\'"); 402 | saml2.httpBinding = SAMLConstants.SAML2_POST_BINDING_URI; 403 | } 404 | saml2.spEntityId = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.SP_ENTITY_ID); 405 | saml2.acsURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ACS_URL); 406 | saml2.idPEntityId = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.IDP_ENTITY_ID); 407 | saml2.idPURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.IDP_URL); 408 | saml2.attributeConsumingServiceIndex = properties.getProperty( 409 | SSOAgentConstants.SSOAgentConfig.SAML2.ATTRIBUTE_CONSUMING_SERVICE_INDEX); 410 | 411 | String isSLOEnabledString = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_SLO); 412 | if (StringUtils.isNotBlank(isSLOEnabledString)) { 413 | saml2.isSLOEnabled = Boolean.parseBoolean(isSLOEnabledString); 414 | } else { 415 | LOGGER.info("\'" + SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_SLO + 416 | "\' not configured. Defaulting to \'false\'"); 417 | saml2.isSLOEnabled = false; 418 | } 419 | saml2.sloURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.SLO_URL); 420 | 421 | String isAssertionSignedString = 422 | properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_ASSERTION_SIGNING); 423 | if (StringUtils.isNotBlank(isAssertionSignedString) && !skipKeystoreConfigs) { 424 | saml2.isAssertionSigned = Boolean.parseBoolean(isAssertionSignedString); 425 | } else { 426 | LOGGER.log(Level.WARNING, SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_ASSERTION_SIGNING + 427 | " not configured or keystore properties not included. Defaulting to \'false\'"); 428 | saml2.isAssertionSigned = false; 429 | } 430 | 431 | String isAssertionEncryptedString = 432 | properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_ASSERTION_ENCRYPTION); 433 | if (StringUtils.isNotBlank(isAssertionEncryptedString) && !skipKeystoreConfigs) { 434 | saml2.isAssertionEncrypted = Boolean.parseBoolean(isAssertionEncryptedString); 435 | } else { 436 | LOGGER.log(Level.WARNING, SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_ASSERTION_ENCRYPTION + 437 | " not configured or keystore properties not included. Defaulting to \'false\'"); 438 | saml2.isAssertionEncrypted = false; 439 | } 440 | 441 | String isResponseSignedString = 442 | properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_RESPONSE_SIGNING); 443 | if (StringUtils.isNotBlank(isResponseSignedString) && !skipKeystoreConfigs) { 444 | saml2.isResponseSigned = Boolean.parseBoolean(isResponseSignedString); 445 | } else { 446 | LOGGER.log(Level.WARNING, SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_RESPONSE_SIGNING + 447 | " not configured or keystore properties not included. Defaulting to \'false\'"); 448 | saml2.isResponseSigned = false; 449 | } 450 | 451 | if (saml2.isResponseSigned() || saml2.isAssertionSigned()) { 452 | String signatureValidatorImplClass = properties.getProperty( 453 | SSOAgentConstants.SSOAgentConfig.SAML2.SIGNATURE_VALIDATOR); 454 | if (StringUtils.isNotBlank(signatureValidatorImplClass)) { 455 | saml2.signatureValidatorImplClass = signatureValidatorImplClass; 456 | } else { 457 | LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.SAML2.SIGNATURE_VALIDATOR + 458 | " not configured."); 459 | } 460 | } 461 | 462 | String isRequestSignedString = 463 | properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_REQUEST_SIGNING); 464 | if (StringUtils.isNotBlank(isRequestSignedString) && !skipKeystoreConfigs) { 465 | saml2.isRequestSigned = Boolean.parseBoolean(isRequestSignedString); 466 | } else { 467 | LOGGER.log(Level.WARNING, SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_REQUEST_SIGNING + 468 | " not configured or keystore properties not included. Defaulting to \'false\'"); 469 | saml2.isRequestSigned = false; 470 | } 471 | 472 | String isPassiveAuthnString = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.IS_PASSIVE_AUTHN); 473 | if (StringUtils.isNotBlank(isPassiveAuthnString)) { 474 | saml2.isPassiveAuthn = Boolean.parseBoolean(isPassiveAuthnString); 475 | } else { 476 | LOGGER.log(Level.FINE, "\'" + SSOAgentConstants.SSOAgentConfig.SAML2.IS_PASSIVE_AUTHN + 477 | "\' not configured. Defaulting to \'false\'"); 478 | saml2.isPassiveAuthn = false; 479 | } 480 | 481 | String isForceAuthnString = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.IS_FORCE_AUTHN); 482 | if (StringUtils.isNotBlank(isForceAuthnString)) { 483 | saml2.isForceAuthn = Boolean.parseBoolean(isForceAuthnString); 484 | } else { 485 | LOGGER.log(Level.FINE, "\'" + SSOAgentConstants.SSOAgentConfig.SAML2.IS_FORCE_AUTHN + 486 | "\' not configured. Defaulting to \'false\'"); 487 | saml2.isForceAuthn = false; 488 | } 489 | 490 | saml2.relayState = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.RELAY_STATE); 491 | saml2.postBindingRequestHTMLPayload = properties.getProperty( 492 | SSOAgentConstants.SSOAgentConfig.SAML2.POST_BINDING_REQUEST_HTML_PAYLOAD); 493 | saml2.artifactResolveURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ARTIFACT_RESOLVE_URL); 494 | saml2.enableArtifactResolveSigning = StringUtils.equals( 495 | properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_ARTIFACT_RESOLVE_SIGNING), "true"); 496 | 497 | if (StringUtils.isNotBlank(properties.getProperty(SSOAgentConstants.KEYSTORE))) { 498 | try { 499 | keyStoreStream = new FileInputStream(properties.getProperty(SSOAgentConstants.KEYSTORE)); 500 | } catch (FileNotFoundException e) { 501 | throw new SSOAgentException("Cannot find file " + properties.getProperty(SSOAgentConstants.KEYSTORE), e); 502 | } 503 | } 504 | keyStorePassword = getKeystoreConfig(SSOAgentConstants.KEY_STORE_PASSWORD, properties); 505 | 506 | // Check if the assertion validity timeStampSkew is set in config file 507 | // If that is set, use that as the timeskewperiod 508 | String timeStampSkew = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.TIME_STAMP_SKEW); 509 | if (timeStampSkew != null) { 510 | saml2.timeStampSkewInSeconds = Integer.parseInt(timeStampSkew); 511 | } else { 512 | LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.SAML2.TIME_STAMP_SKEW + 513 | " not configured. Defaulting to 300s"); 514 | } 515 | 516 | SSLContext sc; 517 | try { 518 | // Get SSL context 519 | sc = SSLContext.getInstance("SSL"); 520 | doHostNameVerification(); 521 | TrustManager[] trustManagers = doSSLVerification(); 522 | 523 | sc.init(null, trustManagers, new java.security.SecureRandom()); 524 | SSLSocketFactory sslSocketFactory = sc.getSocketFactory(); 525 | HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory); 526 | 527 | } catch (Exception e) { 528 | throw new SSOAgentException("An error in initializing SSL Context"); 529 | } 530 | } 531 | 532 | public void verifyConfig() throws SSOAgentException { 533 | 534 | if (isSAML2SSOLoginEnabled && saml2SSOURL == null) { 535 | throw new SSOAgentException("\'" + 536 | SSOAgentConstants.SSOAgentConfig.SAML2_SSO_URL + "\' not configured"); 537 | } 538 | 539 | if (isSAML2SSOLoginEnabled && saml2.spEntityId == null) { 540 | throw new SSOAgentException("\'" + 541 | SSOAgentConstants.SSOAgentConfig.SAML2.SP_ENTITY_ID + "\' not configured"); 542 | } 543 | 544 | if (isSAML2SSOLoginEnabled && saml2.acsURL == null) { 545 | throw new SSOAgentException("\'" + 546 | SSOAgentConstants.SSOAgentConfig.SAML2.ACS_URL + "\' not configured"); 547 | } 548 | 549 | if (isSAML2SSOLoginEnabled && saml2.idPEntityId == null) { 550 | throw new SSOAgentException("\'" + 551 | SSOAgentConstants.SSOAgentConfig.SAML2.IDP_ENTITY_ID + "\' not configured"); 552 | } 553 | 554 | if (isSAML2SSOLoginEnabled && saml2.idPURL == null) { 555 | throw new SSOAgentException("\'" + 556 | SSOAgentConstants.SSOAgentConfig.SAML2.IDP_URL + "\' not configured"); 557 | } 558 | 559 | if (isSAML2SSOLoginEnabled && saml2.attributeConsumingServiceIndex == null) { 560 | LOGGER.log(Level.FINE, 561 | "\'" + SSOAgentConstants.SSOAgentConfig.SAML2.ATTRIBUTE_CONSUMING_SERVICE_INDEX + 562 | "\' not configured. " + "No attributes of the Subject will be requested"); 563 | } 564 | 565 | if (isSAML2SSOLoginEnabled && saml2.isSLOEnabled && saml2.sloURL == null) { 566 | throw new SSOAgentException("Single Logout enabled, but SLO URL not configured"); 567 | } 568 | 569 | if (isSAML2SSOLoginEnabled && 570 | (saml2.isAssertionSigned || saml2.isAssertionEncrypted || saml2.isResponseSigned || 571 | saml2.isRequestSigned) && saml2.ssoAgentX509Credential == null) { 572 | throw new SSOAgentException("\'SSOAgentX509Credential\' not configured"); 573 | } 574 | 575 | if (isSAML2SSOLoginEnabled && 576 | (saml2.isAssertionSigned || saml2.isResponseSigned) && 577 | saml2.ssoAgentX509Credential.getEntityCertificate() == null) { 578 | throw new SSOAgentException("Public certificate of IdP not configured"); 579 | } 580 | 581 | if (isSAML2SSOLoginEnabled && 582 | (saml2.isRequestSigned || saml2.isAssertionEncrypted) && 583 | saml2.ssoAgentX509Credential.getPrivateKey() == null) { 584 | throw new SSOAgentException("Private key of SP not configured"); 585 | } 586 | } 587 | 588 | private static void scheduleIdleRequestCleanupTask(int idleTimeOutInMinutes) { 589 | 590 | ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); 591 | scheduler.scheduleAtFixedRate(new SAML2IdleRequestCleanupTask(idleTimeOutInMinutes), 6, 6, TimeUnit.HOURS); 592 | } 593 | 594 | /** 595 | * get the key store instance 596 | * 597 | * @param is KeyStore InputStream 598 | * @param storePassword password of key store 599 | * @return KeyStore instant 600 | * @throws SSOAgentException if fails to load key store 601 | */ 602 | private KeyStore readKeyStore(InputStream is, String storePassword) throws 603 | SSOAgentException { 604 | 605 | if (StringUtils.isBlank(storePassword)) { 606 | throw new SSOAgentException( 607 | "KeyStore password can not be null"); 608 | } 609 | 610 | try { 611 | KeyStore keyStore = KeyStore.getInstance("JKS"); 612 | keyStore.load(is, storePassword.toCharArray()); 613 | return keyStore; 614 | } catch (Exception e) { 615 | 616 | throw new SSOAgentException( 617 | "Error while loading key store file", e); 618 | } finally { 619 | if (is != null) { 620 | try { 621 | is.close(); 622 | } catch (IOException ignored) { 623 | 624 | throw new SSOAgentException( 625 | "Error while closing input stream of key store", ignored); 626 | } 627 | } 628 | } 629 | } 630 | 631 | private String buildIndexPageURL(Properties properties) throws URISyntaxException { 632 | 633 | String httpBinding; 634 | if (!StringUtils.isBlank(properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.HTTP_BINDING))) { 635 | httpBinding = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.HTTP_BINDING); 636 | } else { 637 | // Set default http binding to HTTP-POST. 638 | httpBinding = "HTTP-POST"; 639 | } 640 | 641 | return new URIBuilder(properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2_SSO_URL)) 642 | .addParameter(SSOAgentConstants.SSOAgentConfig.SAML2.HTTP_BINDING, httpBinding) 643 | .build() 644 | .toString(); 645 | } 646 | 647 | private void doHostNameVerification() { 648 | 649 | if (!this.getEnableHostNameVerification()) { 650 | // Create empty HostnameVerifier 651 | HostnameVerifier hv = new HostnameVerifier() { 652 | public boolean verify(String urlHostName, SSLSession session) { 653 | 654 | return true; 655 | } 656 | }; 657 | HttpsURLConnection.setDefaultHostnameVerifier(hv); 658 | } 659 | } 660 | 661 | private TrustManager[] doSSLVerification() throws Exception { 662 | 663 | TrustManager[] trustManagers = null; 664 | if (this.getEnableSSLVerification()) { 665 | TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); 666 | tmf.init(this.getKeyStore()); 667 | trustManagers = tmf.getTrustManagers(); 668 | } else { 669 | // Create a trust manager that does not validate certificate chains 670 | trustManagers = new TrustManager[]{new X509TrustManager() { 671 | public java.security.cert.X509Certificate[] getAcceptedIssuers() { 672 | 673 | return null; 674 | } 675 | 676 | public void checkClientTrusted(java.security.cert.X509Certificate[] certs, 677 | String authType) { 678 | 679 | } 680 | 681 | public void checkServerTrusted(java.security.cert.X509Certificate[] certs, 682 | String authType) { 683 | 684 | } 685 | }}; 686 | } 687 | return trustManagers; 688 | } 689 | 690 | private String getKeystoreConfig(String property, Properties properties) { 691 | 692 | if (StringUtils.isNotBlank(properties.getProperty(property))) { 693 | return properties.getProperty(property); 694 | } 695 | skipKeystoreConfigs = true; 696 | return null; 697 | } 698 | 699 | public class SAML2 { 700 | 701 | private String httpBinding = null; 702 | private String spEntityId = null; 703 | private String acsURL = null; 704 | private String idPEntityId = null; 705 | private String idPURL = null; 706 | private Boolean isSLOEnabled = false; 707 | private String sloURL = null; 708 | private String attributeConsumingServiceIndex = null; 709 | private SSOAgentX509Credential ssoAgentX509Credential = null; 710 | private Boolean isAssertionSigned = false; 711 | private Boolean isAssertionEncrypted = false; 712 | private Boolean isResponseSigned = false; 713 | private Boolean isRequestSigned = false; 714 | private Boolean isPassiveAuthn = false; 715 | private Boolean isForceAuthn = false; 716 | private String relayState = null; 717 | private String signatureValidatorImplClass = null; 718 | private int timeStampSkewInSeconds = 300; 719 | private String artifactResolveURL = null; 720 | private boolean enableArtifactResolveSigning; 721 | /** 722 | * The html page that will auto-submit the SAML2 to the IdP. 723 | * This should be in valid HTML syntax, with following section within the 724 | * auto-submit form. 725 | * "<!--$saml_params-->" 726 | * This section will be replaced by the SAML2 parameters. 727 | *

728 | * If the parameter value is empty, null or doesn't have the above 729 | * section, the default page will be shown 730 | */ 731 | private String postBindingRequestHTMLPayload = null; 732 | 733 | public String getArtifactResolveURL() { 734 | 735 | return artifactResolveURL; 736 | } 737 | 738 | public void setArtifactResolveURL(String artifactResolveURL) { 739 | 740 | this.artifactResolveURL = artifactResolveURL; 741 | } 742 | 743 | public boolean isEnableArtifactResolveSigning() { 744 | 745 | return enableArtifactResolveSigning; 746 | } 747 | 748 | public void setEnableArtifactResolveSigning(boolean enableArtifactResolveSigning) { 749 | 750 | this.enableArtifactResolveSigning = enableArtifactResolveSigning; 751 | } 752 | 753 | public String getHttpBinding() { 754 | 755 | return httpBinding; 756 | } 757 | 758 | public void setHttpBinding(String httpBinding) { 759 | 760 | this.httpBinding = httpBinding; 761 | } 762 | 763 | public String getSPEntityId() { 764 | 765 | return spEntityId; 766 | } 767 | 768 | public void setSPEntityId(String spEntityId) { 769 | 770 | this.spEntityId = spEntityId; 771 | } 772 | 773 | public String getACSURL() { 774 | 775 | return acsURL; 776 | } 777 | 778 | public void setACSURL(String acsURL) { 779 | 780 | this.acsURL = acsURL; 781 | } 782 | 783 | public String getIdPEntityId() { 784 | 785 | return idPEntityId; 786 | } 787 | 788 | public void setIdPEntityId(String idPEntityId) { 789 | 790 | this.idPEntityId = idPEntityId; 791 | } 792 | 793 | public String getIdPURL() { 794 | 795 | return idPURL; 796 | } 797 | 798 | public void setIdPURL(String idPURL) { 799 | 800 | this.idPURL = idPURL; 801 | } 802 | 803 | public Boolean isSLOEnabled() { 804 | 805 | return isSLOEnabled; 806 | } 807 | 808 | public String getSLOURL() { 809 | 810 | return sloURL; 811 | } 812 | 813 | public void setSLOURL(String sloURL) { 814 | 815 | this.sloURL = sloURL; 816 | } 817 | 818 | public String getAttributeConsumingServiceIndex() { 819 | 820 | return attributeConsumingServiceIndex; 821 | } 822 | 823 | public void setAttributeConsumingServiceIndex(String attributeConsumingServiceIndex) { 824 | 825 | this.attributeConsumingServiceIndex = attributeConsumingServiceIndex; 826 | } 827 | 828 | public SSOAgentX509Credential getSSOAgentX509Credential() { 829 | 830 | return ssoAgentX509Credential; 831 | } 832 | 833 | public void setSSOAgentX509Credential(SSOAgentX509Credential ssoAgentX509Credential) { 834 | 835 | this.ssoAgentX509Credential = ssoAgentX509Credential; 836 | } 837 | 838 | public Boolean isAssertionSigned() { 839 | 840 | return isAssertionSigned; 841 | } 842 | 843 | public Boolean isAssertionEncrypted() { 844 | 845 | return isAssertionEncrypted; 846 | } 847 | 848 | public Boolean isResponseSigned() { 849 | 850 | return isResponseSigned; 851 | } 852 | 853 | public Boolean isRequestSigned() { 854 | 855 | return isRequestSigned; 856 | } 857 | 858 | public Boolean isPassiveAuthn() { 859 | 860 | return isPassiveAuthn; 861 | } 862 | 863 | public Boolean isForceAuthn() { 864 | 865 | return isForceAuthn; 866 | } 867 | 868 | public String getRelayState() { 869 | 870 | return relayState; 871 | } 872 | 873 | public void setRelayState(String relayState) { 874 | 875 | this.relayState = relayState; 876 | } 877 | 878 | public String getPostBindingRequestHTMLPayload() { 879 | 880 | return postBindingRequestHTMLPayload; 881 | } 882 | 883 | public void setPostBindingRequestHTMLPayload(String postBindingRequestHTMLPayload) { 884 | 885 | this.postBindingRequestHTMLPayload = postBindingRequestHTMLPayload; 886 | } 887 | 888 | public void setSLOEnabled(Boolean isSLOEnabled) { 889 | 890 | this.isSLOEnabled = isSLOEnabled; 891 | } 892 | 893 | public void setAssertionSigned(Boolean isAssertionSigned) { 894 | 895 | this.isAssertionSigned = isAssertionSigned; 896 | } 897 | 898 | public void setAssertionEncrypted(Boolean isAssertionEncrypted) { 899 | 900 | this.isAssertionEncrypted = isAssertionEncrypted; 901 | } 902 | 903 | public void setResponseSigned(Boolean isResponseSigned) { 904 | 905 | this.isResponseSigned = isResponseSigned; 906 | } 907 | 908 | public void setRequestSigned(Boolean isRequestSigned) { 909 | 910 | this.isRequestSigned = isRequestSigned; 911 | } 912 | 913 | public void setPassiveAuthn(Boolean isPassiveAuthn) { 914 | 915 | this.isPassiveAuthn = isPassiveAuthn; 916 | } 917 | 918 | public void setForceAuthn(Boolean isForceAuthn) { 919 | 920 | this.isForceAuthn = isForceAuthn; 921 | } 922 | 923 | public String getSignatureValidatorImplClass() { 924 | 925 | return signatureValidatorImplClass; 926 | } 927 | 928 | public int getTimeStampSkewInSeconds() { 929 | 930 | return timeStampSkewInSeconds; 931 | } 932 | } 933 | } 934 | --------------------------------------------------------------------------------