├── .travis.yml ├── .github ├── ISSUE_TEMPLATE │ ├── config.yml │ ├── feature_request.md │ ├── improvement.md │ ├── doc_issues.md │ └── bug_report.md └── workflows │ └── pr-builder.yml ├── codecov.yml ├── .gitignore ├── issue_template.md ├── io.asgardeo.java.oidc.sdk ├── src │ ├── test │ │ ├── resources │ │ │ ├── oidc-sample-app.properties │ │ │ └── testng.xml │ │ └── java │ │ │ └── io │ │ │ └── asgardeo │ │ │ └── java │ │ │ └── oidc │ │ │ └── sdk │ │ │ ├── bean │ │ │ ├── UserTest.java │ │ │ └── AuthenticationInfoTest.java │ │ │ ├── config │ │ │ ├── FileBasedOIDCConfigProviderTest.java │ │ │ └── model │ │ │ │ └── OIDCAgentConfigTest.java │ │ │ ├── request │ │ │ ├── OIDCRequestBuilderTest.java │ │ │ └── OIDCRequestResolverTest.java │ │ │ ├── HTTPSessionBasedOIDCProcessorTest.java │ │ │ ├── DefaultOIDCManagerTest.java │ │ │ └── validators │ │ │ └── IDTokenValidatorTest.java │ └── main │ │ └── java │ │ └── io │ │ └── asgardeo │ │ └── java │ │ └── oidc │ │ └── sdk │ │ ├── config │ │ ├── OIDCConfigProvider.java │ │ ├── FileBasedOIDCConfigProvider.java │ │ └── model │ │ │ └── OIDCAgentConfig.java │ │ ├── DefaultOIDCManagerFactory.java │ │ ├── bean │ │ ├── User.java │ │ ├── RequestContext.java │ │ └── SessionContext.java │ │ ├── request │ │ ├── model │ │ │ ├── LogoutRequest.java │ │ │ └── AuthenticationRequest.java │ │ ├── OIDCRequestResolver.java │ │ └── OIDCRequestBuilder.java │ │ ├── exception │ │ ├── SSOAgentClientException.java │ │ ├── SSOAgentServerException.java │ │ └── SSOAgentException.java │ │ ├── OIDCManager.java │ │ ├── SSOAgentConstants.java │ │ ├── validators │ │ └── IDTokenValidator.java │ │ ├── HTTPSessionBasedOIDCProcessor.java │ │ └── DefaultOIDCManager.java └── pom.xml ├── .azure └── asgardeo-java-oidc-sdk-sca-scan.yaml ├── pull_request_template.md ├── pom.xml ├── README.md └── LICENSE /.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 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # IDE 14 | .idea/ 15 | *.iml 16 | 17 | # Package Files # 18 | *.jar 19 | *.war 20 | *.nar 21 | *.ear 22 | *.zip 23 | *.tar.gz 24 | *.rar 25 | 26 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 27 | hs_err_pid* 28 | 29 | # Ignore everything in this directory 30 | target 31 | 32 | # Mac OS 33 | *.DS_Store 34 | -------------------------------------------------------------------------------- /.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.oidc.sdk/src/test/resources/oidc-sample-app.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2020, 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 | consumerKey=KE4OYeY_gfYwzQbJa9tGhj1hZJMa 19 | consumerSecret=_ebDU3prFV99JYgtbnknB0z0dXoa 20 | skipURIs=/oidc-sample-app/index.html 21 | indexPage= 22 | logoutURL=logout 23 | callBackURL=http://localhost:8080/oidc-sample-app/oauth2client 24 | scope=openid,internal_application_mgt_view 25 | authorizeEndpoint=https://localhost:9443/oauth2/authorize 26 | logoutEndpoint=https://localhost:9443/oidc/logout 27 | tokenEndpoint=https://localhost:9443/oauth2/token 28 | issuer=https://localhost:9443/oauth2/token 29 | jwksEndpoint=https://localhost:9443/oauth2/jwks 30 | postLogoutRedirectURI=http://localhost:8080/oidc-sample-app/index.html 31 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/config/OIDCConfigProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.config; 20 | 21 | import io.asgardeo.java.oidc.sdk.config.model.OIDCAgentConfig; 22 | 23 | /** 24 | * A "provider" interface for the {@link OIDCAgentConfig} model. 25 | * 26 | * @see FileBasedOIDCConfigProvider 27 | */ 28 | public interface OIDCConfigProvider { 29 | 30 | /** 31 | * Retrieves the {@code OIDCAgentConfig} object with the agent specific configurations. 32 | * 33 | * @return {@link OIDCAgentConfig} Object containing the agent specific configurations. 34 | */ 35 | OIDCAgentConfig getOidcAgentConfig(); 36 | } 37 | -------------------------------------------------------------------------------- /.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 11 23 | uses: actions/setup-java@v2 24 | with: 25 | java-version: "11" 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.oidc.sdk/src/test/java/io/asgardeo/java/oidc/sdk/bean/UserTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.bean; 20 | 21 | import org.testng.annotations.Test; 22 | 23 | import java.util.HashMap; 24 | import java.util.Map; 25 | 26 | import static org.testng.Assert.assertEquals; 27 | 28 | /** 29 | * Unit tests for User model. 30 | */ 31 | public class UserTest { 32 | 33 | Map attributes = new HashMap<>(); 34 | String subject = "subject"; 35 | User user = new User(subject, attributes); 36 | 37 | @Test 38 | public void testGetSubject() { 39 | 40 | assertEquals(user.getSubject(), subject); 41 | } 42 | 43 | @Test 44 | public void testGetAttributes() { 45 | 46 | assertEquals(user.getAttributes(), attributes); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/DefaultOIDCManagerFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk; 20 | 21 | import io.asgardeo.java.oidc.sdk.config.model.OIDCAgentConfig; 22 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentClientException; 23 | 24 | /** 25 | * A factory to create Default OIDC Manger objects based on a OIDCAgentConfig. 26 | */ 27 | public class DefaultOIDCManagerFactory { 28 | 29 | /** 30 | * Creates a new {@link DefaultOIDCManager} object. 31 | * 32 | * @param oidcAgentConfig The {@link OIDCAgentConfig} object containing the client specific details. 33 | * @return The DefaultOIDCManager instance. 34 | * @throws SSOAgentClientException If the OIDCAgentConfig validation is unsuccessful. 35 | */ 36 | public static OIDCManager createOIDCManager(OIDCAgentConfig oidcAgentConfig) throws SSOAgentClientException { 37 | 38 | return new DefaultOIDCManager(oidcAgentConfig); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/bean/User.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.bean; 20 | 21 | import java.io.Serializable; 22 | import java.util.Map; 23 | 24 | /** 25 | * A data model class to define the User element. 26 | */ 27 | public class User implements Serializable { 28 | 29 | private static final long serialVersionUID = -2609465712885072108L; 30 | 31 | private String subject; 32 | private Map attributes; 33 | 34 | public User(String subject, Map attributes) { 35 | 36 | this.subject = subject; 37 | this.attributes = attributes; 38 | } 39 | 40 | /** 41 | * Returns the subject identifier of the user. 42 | * 43 | * @return The subject identifier. 44 | */ 45 | public String getSubject() { 46 | 47 | return subject; 48 | } 49 | 50 | /** 51 | * Returns the attributes of the user. 52 | * 53 | * @return {@code Map} of the user attributes. 54 | */ 55 | public Map getAttributes() { 56 | 57 | return attributes; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/test/resources/testng.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/request/model/LogoutRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.request.model; 20 | 21 | import io.asgardeo.java.oidc.sdk.bean.RequestContext; 22 | 23 | import java.io.Serializable; 24 | import java.net.URI; 25 | 26 | /** 27 | * A data model class to define the Logout Request element. 28 | */ 29 | public class LogoutRequest implements Serializable { 30 | 31 | private static final long serialVersionUID = 6184960293632714833L; 32 | 33 | private URI logoutRequestURI; 34 | private RequestContext requestContext; 35 | 36 | public LogoutRequest(URI logoutRequestURI, RequestContext requestContext) { 37 | 38 | this.logoutRequestURI = logoutRequestURI; 39 | this.requestContext = requestContext; 40 | } 41 | 42 | public URI getLogoutRequestURI() { 43 | 44 | return logoutRequestURI; 45 | } 46 | 47 | public void setLogoutRequestURI(URI logoutRequestURI) { 48 | 49 | this.logoutRequestURI = logoutRequestURI; 50 | } 51 | 52 | public RequestContext getRequestContext() { 53 | 54 | return requestContext; 55 | } 56 | 57 | public void setRequestContext(RequestContext requestContext) { 58 | 59 | this.requestContext = requestContext; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /.azure/asgardeo-java-oidc-sdk-sca-scan.yaml: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------- 2 | # 3 | # Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). All Rights Reserved. 4 | # 5 | # This software is the property of WSO2 LLC. and its suppliers, if any. 6 | # Dissemination of any information or reproduction of any material contained 7 | # herein in any form is strictly forbidden, unless permitted by WSO2 expressly. 8 | # You may not alter or remove any copyright or other notice from copies of this content. 9 | # 10 | # -------------------------------------------------------------------------------------- 11 | 12 | schedules: 13 | - cron: "0 0 * * *" 14 | displayName: Daily midnight SCA build 15 | branches: 16 | include: 17 | - master 18 | 19 | trigger: 20 | - none 21 | 22 | pr: 23 | branches: 24 | include: 25 | - master 26 | 27 | variables: 28 | - group: asgardeo-common-secrets 29 | 30 | pool: 'asgardeo-shared-scale-set-agents' 31 | 32 | resources: 33 | repositories: 34 | - repository: templates 35 | type: github 36 | name: wso2-enterprise/azure-pipeline-templates 37 | ref: refs/tags/v1.4.15 38 | endpoint: asgardeo-github-sca-scan 39 | 40 | jobs: 41 | - job: sca_scan 42 | displayName: SCA scan 43 | steps: 44 | - powershell: | 45 | $branchName = "$(Build.SourceBranch)".Replace("refs/heads/", "") 46 | Write-Host "##vso[task.setvariable variable=simpleBranchName]$branchName" 47 | displayName: 'Extract branch name' 48 | - template: ci-pipelines/templates/sca-scan-jfrog.yaml@templates 49 | parameters: 50 | PROJECT_TYPE: mvn 51 | GITHUB_CONNECTION: asgardeo-github-sca-scan 52 | ACCESS_TOKEN: $(JFROG-ACCESS-TOKEN) # JFrog access token 53 | - template: ci-pipelines/templates/sca-scan.yaml@templates 54 | parameters: 55 | API_KEY: $(FOSSA-API-KEY) 56 | BRANCH: $(simpleBranchName) 57 | REPO_NAME: 'asgardeo-java-oidc-sdk' 58 | GITHUB_ORG: 'asgardeo' 59 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/request/model/AuthenticationRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.request.model; 20 | 21 | import io.asgardeo.java.oidc.sdk.bean.RequestContext; 22 | 23 | import java.io.Serializable; 24 | import java.net.URI; 25 | 26 | /** 27 | * A data model class to define the Authentication Request element. 28 | */ 29 | public class AuthenticationRequest implements Serializable { 30 | 31 | private static final long serialVersionUID = 7931793096680065576L; 32 | 33 | private URI authenticationRequestURI; 34 | private RequestContext requestContext; 35 | 36 | public AuthenticationRequest(URI authenticationRequestURI, RequestContext requestContext) { 37 | 38 | this.authenticationRequestURI = authenticationRequestURI; 39 | this.requestContext = requestContext; 40 | } 41 | 42 | public URI getAuthenticationRequestURI() { 43 | 44 | return authenticationRequestURI; 45 | } 46 | 47 | public void setAuthenticationRequestURI(URI authenticationRequestURI) { 48 | 49 | this.authenticationRequestURI = authenticationRequestURI; 50 | } 51 | 52 | public RequestContext getRequestContext() { 53 | 54 | return requestContext; 55 | } 56 | 57 | public void setRequestContext(RequestContext requestContext) { 58 | 59 | this.requestContext = requestContext; 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. -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/test/java/io/asgardeo/java/oidc/sdk/bean/AuthenticationInfoTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.bean; 20 | 21 | import com.nimbusds.jwt.JWT; 22 | import com.nimbusds.jwt.JWTParser; 23 | import com.nimbusds.oauth2.sdk.token.AccessToken; 24 | import com.nimbusds.oauth2.sdk.token.AccessTokenType; 25 | import com.nimbusds.oauth2.sdk.token.RefreshToken; 26 | import org.testng.annotations.Test; 27 | 28 | import java.text.ParseException; 29 | import java.util.HashMap; 30 | import java.util.Map; 31 | 32 | import static org.testng.Assert.assertEquals; 33 | 34 | /** 35 | * Unit tests for AuthenticationInfo model. 36 | */ 37 | public class AuthenticationInfoTest { 38 | 39 | SessionContext authenticationInfo = new SessionContext(); 40 | 41 | @Test 42 | public void testGetUser() { 43 | 44 | Map attributes = new HashMap<>(); 45 | User user = new User("subject", attributes); 46 | authenticationInfo.setUser(user); 47 | assertEquals(authenticationInfo.getUser(), user); 48 | } 49 | 50 | @Test 51 | public void testGetAccessToken() { 52 | 53 | AccessToken accessToken = new AccessToken(AccessTokenType.BEARER) { 54 | @Override 55 | public String toAuthorizationHeader() { 56 | 57 | return null; 58 | } 59 | }; 60 | authenticationInfo.setAccessToken(accessToken.toJSONString()); 61 | assertEquals(authenticationInfo.getAccessToken(), accessToken.toJSONString()); 62 | } 63 | 64 | @Test 65 | public void testGetRefreshToken() { 66 | 67 | RefreshToken refreshToken = new RefreshToken(); 68 | authenticationInfo.setRefreshToken(refreshToken.getValue()); 69 | assertEquals(authenticationInfo.getRefreshToken(), refreshToken.getValue()); 70 | } 71 | 72 | @Test 73 | public void testGetIdToken() { 74 | 75 | try { 76 | JWT idToken = JWTParser.parse("sample"); 77 | authenticationInfo.setIdToken(idToken.getParsedString()); 78 | assertEquals(authenticationInfo.getIdToken(), idToken.getParsedString()); 79 | } catch (ParseException e) { 80 | //Test behaviour. Hence ignored. 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/exception/SSOAgentClientException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.exception; 20 | 21 | /** 22 | * Client exception class for the Java OIDC SDK. 23 | * It is extended from the base class, {@link SSOAgentException}. 24 | */ 25 | public class SSOAgentClientException extends SSOAgentException { 26 | 27 | private static final long serialVersionUID = 7038967084217855809L; 28 | 29 | /** 30 | * Constructs a SSOAgentClientException with the specified detail 31 | * message. A detail message is a String that describes this 32 | * particular exception. 33 | * 34 | * @param message The detail message. 35 | */ 36 | public SSOAgentClientException(String message) { 37 | 38 | super(message); 39 | } 40 | 41 | /** 42 | * Creates a {@code SSOAgentClientException} with the specified 43 | * detail message and cause. 44 | * 45 | * @param message the detail message (which is saved for later retrieval 46 | * by the {@link #getMessage()} method). 47 | * @param errorCode The error code (which is saved for later retrieval by the 48 | * {@link #getErrorCode()} method). 49 | * @param cause the cause (which is saved for later retrieval by the 50 | * {@link #getCause()} method). 51 | */ 52 | public SSOAgentClientException(String message, String errorCode, Throwable cause) { 53 | 54 | super(message, errorCode, cause); 55 | } 56 | 57 | /** 58 | * Creates a {@code SSOAgentClientException} with the specified 59 | * detail message and cause. 60 | * 61 | * @param message The detail message (which is saved for later retrieval 62 | * by the {@link #getMessage()} method). 63 | * @param cause The cause (which is saved for later retrieval by the 64 | * {@link #getCause()} method). 65 | */ 66 | public SSOAgentClientException(String message, Throwable cause) { 67 | 68 | super(message, cause); 69 | } 70 | 71 | /** 72 | * Creates a {@code SSOAgentClientException} with the specified 73 | * detail message and cause. 74 | * 75 | * @param message The detail message (which is saved for later retrieval 76 | * by the {@link #getMessage()} method). 77 | * @param errorCode The error code (which is saved for later retrieval by the 78 | * {@link #getErrorCode()} method). 79 | */ 80 | public SSOAgentClientException(String message, String errorCode) { 81 | 82 | super(message, errorCode); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/exception/SSOAgentServerException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.exception; 20 | 21 | /** 22 | * Server exception class for the Java OIDC SDK. 23 | * It is extended from the base class, {@link SSOAgentException}. 24 | */ 25 | public class SSOAgentServerException extends SSOAgentException { 26 | 27 | private static final long serialVersionUID = 4776260071061676883L; 28 | 29 | /** 30 | * Constructs a SSOAgentServerException with the specified detail 31 | * message. A detail message is a String that describes this 32 | * particular exception. 33 | * 34 | * @param message The detail message. 35 | */ 36 | public SSOAgentServerException(String message) { 37 | 38 | super(message); 39 | } 40 | 41 | /** 42 | * Creates a {@code SSOAgentServerException} with the specified 43 | * detail message and cause. 44 | * 45 | * @param message the detail message (which is saved for later retrieval 46 | * by the {@link #getMessage()} method). 47 | * @param errorCode The error code (which is saved for later retrieval by the 48 | * {@link #getErrorCode()} method). 49 | * @param cause the cause (which is saved for later retrieval by the 50 | * {@link #getCause()} method). 51 | */ 52 | public SSOAgentServerException(String message, String errorCode, Throwable cause) { 53 | 54 | super(message, errorCode, cause); 55 | } 56 | 57 | /** 58 | * Creates a {@code SSOAgentServerException} with the specified 59 | * detail message and cause. 60 | * 61 | * @param message The detail message (which is saved for later retrieval 62 | * by the {@link #getMessage()} method). 63 | * @param cause The cause (which is saved for later retrieval by the 64 | * {@link #getCause()} method). 65 | */ 66 | public SSOAgentServerException(String message, Throwable cause) { 67 | 68 | super(message, cause); 69 | } 70 | 71 | /** 72 | * Creates a {@code SSOAgentServerException} with the specified 73 | * detail message and cause. 74 | * 75 | * @param message the detail message (which is saved for later retrieval 76 | * by the {@link #getMessage()} method). 77 | * @param errorCode The error code (which is saved for later retrieval by the 78 | * {@link #getErrorCode()} method). 79 | */ 80 | public SSOAgentServerException(String message, String errorCode) { 81 | 82 | super(message, errorCode); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/OIDCManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk; 20 | 21 | import io.asgardeo.java.oidc.sdk.bean.RequestContext; 22 | import io.asgardeo.java.oidc.sdk.bean.SessionContext; 23 | import io.asgardeo.java.oidc.sdk.bean.User; 24 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentException; 25 | import io.asgardeo.java.oidc.sdk.request.model.AuthenticationRequest; 26 | 27 | import javax.servlet.http.HttpServletRequest; 28 | import javax.servlet.http.HttpServletResponse; 29 | 30 | /** 31 | * OIDC manager service interface. 32 | */ 33 | public interface OIDCManager { 34 | 35 | /** 36 | * Builds an authentication request and redirects. 37 | * 38 | * @param request Incoming {@link HttpServletRequest}. 39 | * @param response Outgoing {@link HttpServletResponse} 40 | * @return {@link RequestContext} Object containing details regarding the state ID, nonce value for the 41 | * {@link AuthenticationRequest}. 42 | * @throws SSOAgentException 43 | */ 44 | RequestContext sendForLogin(HttpServletRequest request, HttpServletResponse response) 45 | throws SSOAgentException; 46 | 47 | /** 48 | * Processes the OIDC callback response and extract the authorization code, builds a token request, sends the 49 | * token request and parse the token response where the authenticated user info and tokens would be added to the 50 | * {@link SessionContext} object and returned. 51 | * 52 | * @param request Incoming {@link HttpServletRequest}. 53 | * @param response Outgoing {@link HttpServletResponse}. 54 | * @param requestContext {@link RequestContext} object containing the authentication request related information. 55 | * @return {@link SessionContext} Object containing the authenticated {@link User}, AccessToken, RefreshToken 56 | * and IDToken. 57 | * @throws SSOAgentException Upon failed authentication. 58 | */ 59 | SessionContext handleOIDCCallback(HttpServletRequest request, HttpServletResponse response, 60 | RequestContext requestContext) throws SSOAgentException; 61 | 62 | /** 63 | * Builds a logout request and redirects. 64 | * 65 | * @param sessionContext {@link SessionContext} of the logged in session. 66 | * @param response Outgoing {@link HttpServletResponse} 67 | * @return {@link RequestContext} Object containing details regarding the state ID and other parameters of the 68 | * {@link io.asgardeo.java.oidc.sdk.request.model.LogoutRequest}. 69 | * @throws SSOAgentException 70 | */ 71 | RequestContext logout(SessionContext sessionContext, HttpServletResponse response) throws SSOAgentException; 72 | } 73 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/test/java/io/asgardeo/java/oidc/sdk/config/FileBasedOIDCConfigProviderTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.config; 20 | 21 | import io.asgardeo.java.oidc.sdk.config.model.OIDCAgentConfig; 22 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentClientException; 23 | import org.testng.annotations.BeforeMethod; 24 | import org.testng.annotations.Test; 25 | 26 | import java.io.File; 27 | import java.io.FileInputStream; 28 | import java.io.FileNotFoundException; 29 | import java.io.InputStream; 30 | 31 | import static org.testng.Assert.assertEquals; 32 | import static org.testng.Assert.assertTrue; 33 | 34 | public class FileBasedOIDCConfigProviderTest { 35 | 36 | InputStream inputStream; 37 | 38 | @BeforeMethod 39 | public void setUp() { 40 | 41 | File file = new File("src/test/resources/oidc-sample-app.properties"); 42 | try { 43 | inputStream = new FileInputStream(file); 44 | } catch (FileNotFoundException e) { 45 | //Mock behaviour. Hence ignored. 46 | } 47 | } 48 | 49 | @Test 50 | public void testGetOidcAgentConfig() throws SSOAgentClientException { 51 | 52 | FileBasedOIDCConfigProvider configProvider = new FileBasedOIDCConfigProvider(inputStream); 53 | OIDCAgentConfig oidcAgentConfig = configProvider.getOidcAgentConfig(); 54 | 55 | assertEquals(oidcAgentConfig.getConsumerKey().getValue(), "KE4OYeY_gfYwzQbJa9tGhj1hZJMa"); 56 | assertEquals(oidcAgentConfig.getConsumerSecret().getValue(), "_ebDU3prFV99JYgtbnknB0z0dXoa"); 57 | assertTrue(oidcAgentConfig.getSkipURIs().contains("/oidc-sample-app/index.html")); 58 | assertEquals(oidcAgentConfig.getIndexPage(), ""); 59 | assertEquals(oidcAgentConfig.getLogoutURL(), "logout"); 60 | assertEquals(oidcAgentConfig.getCallbackUrl().toString(), "http://localhost:8080/oidc-sample-app/oauth2client"); 61 | assertTrue(oidcAgentConfig.getScope().contains("openid")); 62 | assertTrue(oidcAgentConfig.getScope().contains("internal_application_mgt_view")); 63 | assertEquals(oidcAgentConfig.getAuthorizeEndpoint().toString(), "https://localhost:9443/oauth2/authorize"); 64 | assertEquals(oidcAgentConfig.getLogoutEndpoint().toString(), "https://localhost:9443/oidc/logout"); 65 | assertEquals(oidcAgentConfig.getTokenEndpoint().toString(), "https://localhost:9443/oauth2/token"); 66 | assertEquals(oidcAgentConfig.getIssuer().toString(), "https://localhost:9443/oauth2/token"); 67 | assertEquals(oidcAgentConfig.getJwksEndpoint().toString(), "https://localhost:9443/oauth2/jwks"); 68 | assertEquals(oidcAgentConfig.getPostLogoutRedirectURI().toString(), 69 | "http://localhost:8080/oidc-sample-app/index.html"); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/bean/RequestContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.bean; 20 | 21 | import com.nimbusds.oauth2.sdk.id.State; 22 | import com.nimbusds.openid.connect.sdk.Nonce; 23 | 24 | import java.io.Serializable; 25 | import java.util.HashMap; 26 | import java.util.Map; 27 | 28 | /** 29 | * A data model class to define the Request Context element. The Request Context object 30 | * should be used to hold the attributes regarding the authentication flow. These include the attributes: 31 | *
    32 | *
  • The state parameter 33 | *
  • The nonce value 34 | *
  • Additional custom parameters 35 | *
36 | *

37 | * The Request Context and its attributes would be used from the initiation of the authentication 38 | * request until the authentication completion of the user. 39 | */ 40 | public class RequestContext implements Serializable { 41 | 42 | private static final long serialVersionUID = -3980859739213942559L; 43 | 44 | private State state; 45 | private Nonce nonce; 46 | private Map additionalParams = new HashMap<>(); 47 | 48 | public RequestContext(State state, Nonce nonce) { 49 | 50 | this.state = state; 51 | this.nonce = nonce; 52 | } 53 | 54 | public RequestContext() { 55 | 56 | } 57 | 58 | /** 59 | * Returns the state. 60 | * 61 | * @return {@link State} object for the request. 62 | */ 63 | public State getState() { 64 | 65 | return state; 66 | } 67 | 68 | /** 69 | * Sets the state. 70 | * 71 | * @param state The state object. 72 | */ 73 | public void setState(State state) { 74 | 75 | this.state = state; 76 | } 77 | 78 | /** 79 | * Returns the nonce. 80 | * 81 | * @return {@link Nonce} object for the request. 82 | */ 83 | public Nonce getNonce() { 84 | 85 | return nonce; 86 | } 87 | 88 | /** 89 | * Sets the nonce. 90 | * 91 | * @param nonce The nonce object. 92 | */ 93 | public void setNonce(Nonce nonce) { 94 | 95 | this.nonce = nonce; 96 | } 97 | 98 | /** 99 | * Returns the object for the particular key. 100 | * 101 | * @param key The String value of the key. 102 | * @return The additional parameter object in the request for the particular key. 103 | */ 104 | public Object getParameter(String key) { 105 | 106 | return additionalParams.get(key); 107 | } 108 | 109 | /** 110 | * Sets additional parameter to the Request Context. 111 | * 112 | * @param key The key of the parameter. 113 | * @param value The value of the parameter. 114 | */ 115 | public void setParameter(String key, Object value) { 116 | 117 | additionalParams.put(key, value); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/bean/SessionContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.bean; 20 | 21 | import java.io.Serializable; 22 | import java.util.HashMap; 23 | import java.util.Map; 24 | 25 | /** 26 | * A data model class to define the Session Context element. The Session Context object should be used to hold the 27 | * attributes of the logged in user session. These include the attributes: 28 | *

    29 | *
  • The Authenticated User 30 | *
  • Access Token 31 | *
  • Refresh Token 32 | *
  • ID Token 33 | *
34 | *

35 | */ 36 | public class SessionContext implements Serializable { 37 | 38 | private static final long serialVersionUID = 976008884476935474L; 39 | 40 | private User user; 41 | private String accessToken; 42 | private String refreshToken; 43 | private String idToken; 44 | private Map additionalParams = new HashMap<>(); 45 | 46 | /** 47 | * Returns the authenticated user. 48 | * 49 | * @return {@link User} object for the authenticated user. 50 | */ 51 | public User getUser() { 52 | 53 | return user; 54 | } 55 | 56 | /** 57 | * Sets the user of the authentication. 58 | * 59 | * @param user The user for the authentication. 60 | */ 61 | public void setUser(User user) { 62 | 63 | this.user = user; 64 | } 65 | 66 | /** 67 | * Returns the access token. 68 | * 69 | * @return The access token string. 70 | */ 71 | public String getAccessToken() { 72 | 73 | return accessToken; 74 | } 75 | 76 | /** 77 | * Sets the access token. 78 | * 79 | * @param accessToken The access token. 80 | */ 81 | public void setAccessToken(String accessToken) { 82 | 83 | this.accessToken = accessToken; 84 | } 85 | 86 | /** 87 | * Returns the refresh token. 88 | * 89 | * @return The refresh token string. 90 | */ 91 | public String getRefreshToken() { 92 | 93 | return refreshToken; 94 | } 95 | 96 | /** 97 | * Sets the refresh token. 98 | * 99 | * @param refreshToken The refresh token. 100 | */ 101 | public void setRefreshToken(String refreshToken) { 102 | 103 | this.refreshToken = refreshToken; 104 | } 105 | 106 | /** 107 | * Returns the id token. 108 | * 109 | * @return The Id token string. 110 | */ 111 | public String getIdToken() { 112 | 113 | return idToken; 114 | } 115 | 116 | /** 117 | * Sets the id token. 118 | * 119 | * @param idToken The id token. 120 | */ 121 | public void setIdToken(String idToken) { 122 | 123 | this.idToken = idToken; 124 | } 125 | 126 | /** 127 | * Returns the additional query params. 128 | * 129 | * @return Additional query params map. 130 | */ 131 | public Map getAdditionalParams() { 132 | 133 | return additionalParams; 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/exception/SSOAgentException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.exception; 20 | 21 | import io.asgardeo.java.oidc.sdk.SSOAgentConstants; 22 | 23 | import javax.servlet.ServletException; 24 | 25 | /** 26 | * The {@code SSOAgentException} class is a generic 27 | * OIDC SDK exception class that provides type safety for all the 28 | * SDK-related exception classes that extend from it. 29 | * It is an implementation of the base class, {@link ServletException}. 30 | */ 31 | public class SSOAgentException extends ServletException { 32 | 33 | private static final long serialVersionUID = 2427874190311733363L; 34 | private String errorCode; 35 | 36 | public SSOAgentException() { 37 | 38 | super(); 39 | } 40 | 41 | /** 42 | * Constructs a SSOAgentException with the specified detail 43 | * message. A detail message is a String that describes this 44 | * particular exception. 45 | * 46 | * @param message The detail message. 47 | */ 48 | public SSOAgentException(String message) { 49 | 50 | super(message); 51 | } 52 | 53 | /** 54 | * Creates a {@code SSOAgentException} with the specified 55 | * detail message and cause. 56 | * 57 | * @param message the detail message (which is saved for later retrieval 58 | * by the {@link #getMessage()} method). 59 | * @param errorCode The error code (which is saved for later retrieval by the 60 | * {@link #getErrorCode()} method). 61 | */ 62 | public SSOAgentException(String message, String errorCode) { 63 | 64 | super(message); 65 | this.errorCode = errorCode; 66 | } 67 | 68 | /** 69 | * Creates a {@code SSOAgentException} with the specified cause 70 | * and a detail message of {@code (cause==null ? null : cause.toString())} 71 | * (which typically contains the class and detail message of 72 | * {@code cause}). 73 | * 74 | * @param cause The cause (which is saved for later retrieval by the 75 | * {@link #getCause()} method). 76 | */ 77 | public SSOAgentException(Throwable cause) { 78 | 79 | super(cause); 80 | } 81 | 82 | /** 83 | * Creates a {@code SSOAgentException} with the specified 84 | * detail message and cause. 85 | * 86 | * @param message the detail message (which is saved for later retrieval 87 | * by the {@link #getMessage()} method). 88 | * @param cause the cause (which is saved for later retrieval by the 89 | * {@link #getCause()} method). 90 | */ 91 | public SSOAgentException(String message, Throwable cause) { 92 | 93 | super(message, cause); 94 | } 95 | 96 | /** 97 | * Creates a {@code SSOAgentException} with the specified 98 | * detail message and cause. 99 | * 100 | * @param message the detail message (which is saved for later retrieval 101 | * by the {@link #getMessage()} method). 102 | * @param errorCode The error code (which is saved for later retrieval by the 103 | * {@link #getErrorCode()} method). 104 | * @param cause the cause (which is saved for later retrieval by the 105 | * {@link #getCause()} method). 106 | */ 107 | public SSOAgentException(String message, String errorCode, Throwable cause) { 108 | 109 | super(message, cause); 110 | this.errorCode = errorCode; 111 | } 112 | 113 | /** 114 | * Returns a {@code errorCode} for the exception as defined 115 | * in {@link SSOAgentConstants.ErrorMessages}. 116 | */ 117 | public String getErrorCode() { 118 | 119 | return errorCode; 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/test/java/io/asgardeo/java/oidc/sdk/config/model/OIDCAgentConfigTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.config.model; 20 | 21 | import com.nimbusds.oauth2.sdk.Scope; 22 | import com.nimbusds.oauth2.sdk.auth.Secret; 23 | import com.nimbusds.oauth2.sdk.id.ClientID; 24 | import com.nimbusds.oauth2.sdk.id.Issuer; 25 | import org.testng.annotations.Test; 26 | 27 | import java.net.URI; 28 | import java.net.URISyntaxException; 29 | import java.util.HashSet; 30 | import java.util.Set; 31 | 32 | import static org.testng.Assert.assertEquals; 33 | 34 | public class OIDCAgentConfigTest { 35 | 36 | OIDCAgentConfig oidcAgentConfig = new OIDCAgentConfig(); 37 | 38 | @Test 39 | public void testGetConsumerKey() { 40 | 41 | ClientID clientID = new ClientID("sampleClientId"); 42 | oidcAgentConfig.setConsumerKey(clientID); 43 | assertEquals(oidcAgentConfig.getConsumerKey(), clientID); 44 | } 45 | 46 | @Test 47 | public void testGetConsumerSecret() { 48 | 49 | Secret clientSecret = new Secret("sampleClientSecret"); 50 | oidcAgentConfig.setConsumerSecret(clientSecret); 51 | assertEquals(oidcAgentConfig.getConsumerSecret(), clientSecret); 52 | } 53 | 54 | @Test 55 | public void testGetIndexPage() { 56 | 57 | String indexPage = "/sample/indexPage"; 58 | oidcAgentConfig.setIndexPage(indexPage); 59 | assertEquals(oidcAgentConfig.getIndexPage(), indexPage); 60 | } 61 | 62 | @Test 63 | public void testGetLogoutURL() { 64 | 65 | String logoutURL = "/sample/logout"; 66 | oidcAgentConfig.setLogoutURL(logoutURL); 67 | assertEquals(oidcAgentConfig.getLogoutURL(), logoutURL); 68 | } 69 | 70 | @Test 71 | public void testGetCallbackUrl() throws URISyntaxException { 72 | 73 | URI callbackURL = new URI("http://test/sampleCallback"); 74 | oidcAgentConfig.setCallbackUrl(callbackURL); 75 | assertEquals(oidcAgentConfig.getCallbackUrl(), callbackURL); 76 | } 77 | 78 | @Test 79 | public void testGetScope() { 80 | 81 | Scope scope = new Scope("sampleScope1", "sampleScope2"); 82 | oidcAgentConfig.setScope(scope); 83 | assertEquals(oidcAgentConfig.getScope(), scope); 84 | } 85 | 86 | @Test 87 | public void testGetAuthorizeEndpoint() throws URISyntaxException { 88 | 89 | URI authorizeURL = new URI("http://test/sampleAuthzEP"); 90 | oidcAgentConfig.setAuthorizeEndpoint(authorizeURL); 91 | assertEquals(oidcAgentConfig.getAuthorizeEndpoint(), authorizeURL); 92 | } 93 | 94 | @Test 95 | public void testGetLogoutEndpoint() throws URISyntaxException { 96 | 97 | URI logoutEPURI = new URI("http://test/sampleLogoutEP"); 98 | oidcAgentConfig.setLogoutEndpoint(logoutEPURI); 99 | assertEquals(oidcAgentConfig.getLogoutEndpoint(), logoutEPURI); 100 | } 101 | 102 | @Test 103 | public void testGetTokenEndpoint() throws URISyntaxException { 104 | 105 | URI tokenEPURI = new URI("http://test/sampleTokenEP"); 106 | oidcAgentConfig.setTokenEndpoint(tokenEPURI); 107 | assertEquals(oidcAgentConfig.getTokenEndpoint(), tokenEPURI); 108 | } 109 | 110 | @Test 111 | public void testGetIssuer() { 112 | 113 | Issuer issuer = new Issuer("issuer"); 114 | oidcAgentConfig.setIssuer(issuer); 115 | assertEquals(oidcAgentConfig.getIssuer(), issuer); 116 | } 117 | 118 | @Test 119 | public void testGetJwksEndpoint() throws URISyntaxException { 120 | 121 | URI jwksEPURI = new URI("http://test/sampleJwksEP"); 122 | oidcAgentConfig.setJwksEndpoint(jwksEPURI); 123 | assertEquals(oidcAgentConfig.getJwksEndpoint(), jwksEPURI); 124 | } 125 | 126 | @Test 127 | public void testGetPostLogoutRedirectURI() throws URISyntaxException { 128 | 129 | URI redirectURI = new URI("http://test/sampleLogoutRedirect"); 130 | oidcAgentConfig.setPostLogoutRedirectURI(redirectURI); 131 | assertEquals(oidcAgentConfig.getPostLogoutRedirectURI(), redirectURI); 132 | } 133 | 134 | @Test 135 | public void testGetSkipURIs() { 136 | 137 | Set skipURIs = new HashSet(); 138 | skipURIs.add("sampleSkipURI1"); 139 | skipURIs.add("sampleSkipURI2"); 140 | oidcAgentConfig.setSkipURIs(skipURIs); 141 | assertEquals(oidcAgentConfig.getSkipURIs(), skipURIs); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/test/java/io/asgardeo/java/oidc/sdk/request/OIDCRequestBuilderTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2020-2024, WSO2 LLC. (https://www.wso2.com). 3 | * 4 | * WSO2 LLC. 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.oidc.sdk.request; 20 | 21 | import com.nimbusds.jwt.JWT; 22 | import com.nimbusds.jwt.JWTParser; 23 | import com.nimbusds.oauth2.sdk.Scope; 24 | import com.nimbusds.oauth2.sdk.id.ClientID; 25 | import io.asgardeo.java.oidc.sdk.bean.RequestContext; 26 | import io.asgardeo.java.oidc.sdk.bean.SessionContext; 27 | import io.asgardeo.java.oidc.sdk.config.model.OIDCAgentConfig; 28 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentServerException; 29 | import io.asgardeo.java.oidc.sdk.request.model.AuthenticationRequest; 30 | import io.asgardeo.java.oidc.sdk.request.model.LogoutRequest; 31 | import org.mockito.Mock; 32 | import org.powermock.core.classloader.annotations.PrepareForTest; 33 | import org.powermock.modules.testng.PowerMockTestCase; 34 | import org.testng.annotations.BeforeMethod; 35 | import org.testng.annotations.Test; 36 | 37 | import java.net.URI; 38 | import java.net.URISyntaxException; 39 | import java.text.ParseException; 40 | 41 | import static org.mockito.Mockito.mock; 42 | import static org.mockito.Mockito.when; 43 | import static org.testng.Assert.assertEquals; 44 | 45 | @PrepareForTest({OIDCAgentConfig.class, SessionContext.class}) 46 | public class OIDCRequestBuilderTest extends PowerMockTestCase { 47 | 48 | @Mock 49 | OIDCAgentConfig oidcAgentConfig; 50 | 51 | @Mock 52 | SessionContext sessionContext; 53 | 54 | @BeforeMethod 55 | public void setUp() throws URISyntaxException, ParseException { 56 | 57 | ClientID clientID = new ClientID("sampleClientId"); 58 | Scope scope = new Scope("sampleScope1", "openid"); 59 | URI callbackURI = new URI("http://test/sampleCallbackURL"); 60 | URI authorizationEndpoint = new URI("http://test/sampleAuthzEP"); 61 | URI logoutEP = new URI("http://test/sampleLogoutEP"); 62 | URI redirectionURI = new URI("http://test/sampleRedirectionURL"); 63 | JWT idToken = JWTParser 64 | .parse("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwia" + 65 | "WF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"); 66 | 67 | oidcAgentConfig = mock(OIDCAgentConfig.class); 68 | sessionContext = mock(SessionContext.class); 69 | 70 | when(oidcAgentConfig.getConsumerKey()).thenReturn(clientID); 71 | when(oidcAgentConfig.getScope()).thenReturn(scope); 72 | when(oidcAgentConfig.getCallbackUrl()).thenReturn(callbackURI); 73 | when(oidcAgentConfig.getAuthorizeEndpoint()).thenReturn(authorizationEndpoint); 74 | when(oidcAgentConfig.getLogoutEndpoint()).thenReturn(logoutEP); 75 | when(oidcAgentConfig.getPostLogoutRedirectURI()).thenReturn(redirectionURI); 76 | when(sessionContext.getIdToken()).thenReturn(idToken.getParsedString()); 77 | } 78 | 79 | @Test 80 | public void testBuildAuthorizationRequest() { 81 | 82 | AuthenticationRequest authenticationRequest = 83 | new OIDCRequestBuilder(oidcAgentConfig).buildAuthenticationRequest(); 84 | RequestContext requestContext = authenticationRequest.getRequestContext(); 85 | String nonce = requestContext.getNonce().getValue(); 86 | String state = requestContext.getState().getValue(); 87 | 88 | assertEquals(authenticationRequest.getAuthenticationRequestURI().toString(), 89 | "http://test/sampleAuthzEP?scope=sampleScope1+openid&response_type=code&redirect_uri=http" + 90 | "%3A%2F%2Ftest%2FsampleCallbackURL&state=" + state + "&nonce=" + nonce + "&client_id" + 91 | "=sampleClientId"); 92 | } 93 | 94 | @Test 95 | public void testBuildLogoutRequest() throws SSOAgentServerException { 96 | 97 | LogoutRequest logoutRequest = new OIDCRequestBuilder(oidcAgentConfig).buildLogoutRequest(sessionContext); 98 | RequestContext requestContext = logoutRequest.getRequestContext(); 99 | String state = requestContext.getState().getValue(); 100 | assertEquals(logoutRequest.getLogoutRequestURI().toString(), "http://test/sampleLogoutEP?state=" + state + 101 | "&post_logout_redirect_uri=http%3A%2F%2Ftest%2FsampleRedirectionURL&id_token_hint=eyJhbGciOiJIUzI1NiI" + 102 | "sInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwR" + 103 | "JSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/test/java/io/asgardeo/java/oidc/sdk/request/OIDCRequestResolverTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2020-2024, WSO2 LLC. (https://www.wso2.com). 3 | * 4 | * WSO2 LLC. 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.oidc.sdk.request; 20 | 21 | import com.nimbusds.oauth2.sdk.AuthorizationCode; 22 | import com.nimbusds.oauth2.sdk.AuthorizationResponse; 23 | import com.nimbusds.oauth2.sdk.AuthorizationSuccessResponse; 24 | import com.nimbusds.oauth2.sdk.ParseException; 25 | import com.nimbusds.oauth2.sdk.http.HTTPRequest; 26 | import com.nimbusds.oauth2.sdk.http.ServletUtils; 27 | import io.asgardeo.java.oidc.sdk.SSOAgentConstants; 28 | import io.asgardeo.java.oidc.sdk.config.model.OIDCAgentConfig; 29 | import org.mockito.Mock; 30 | import org.mockito.MockedStatic; 31 | import org.powermock.core.classloader.annotations.PrepareForTest; 32 | import org.powermock.modules.testng.PowerMockTestCase; 33 | import org.testng.annotations.AfterMethod; 34 | import org.testng.annotations.BeforeMethod; 35 | import org.testng.annotations.Test; 36 | 37 | import java.io.IOException; 38 | import java.net.URI; 39 | import java.net.URISyntaxException; 40 | import java.util.HashSet; 41 | import java.util.Set; 42 | 43 | import javax.servlet.http.HttpServletRequest; 44 | 45 | import static org.mockito.Mockito.mock; 46 | import static org.mockito.Mockito.mockStatic; 47 | import static org.mockito.Mockito.when; 48 | import static org.testng.Assert.assertTrue; 49 | 50 | @PrepareForTest({AuthorizationResponse.class}) 51 | public class OIDCRequestResolverTest extends PowerMockTestCase { 52 | 53 | @Mock 54 | OIDCAgentConfig oidcAgentConfig; 55 | 56 | @Mock 57 | HttpServletRequest request; 58 | 59 | @BeforeMethod 60 | public void setUp() { 61 | 62 | oidcAgentConfig = mock(OIDCAgentConfig.class); 63 | request = mock(HttpServletRequest.class); 64 | } 65 | 66 | @Test 67 | public void testIsError() { 68 | 69 | when(request.getParameter(SSOAgentConstants.ERROR)).thenReturn("error"); 70 | OIDCRequestResolver resolver = new OIDCRequestResolver(request, oidcAgentConfig); 71 | assertTrue(resolver.isError()); 72 | } 73 | 74 | @Test 75 | public void testIsAuthorizationCodeResponse() throws IOException, ParseException, URISyntaxException { 76 | 77 | MockedStatic mockedAuthorizationResponse = mockStatic(AuthorizationResponse.class); 78 | MockedStatic mockedServletUtils = mockStatic(ServletUtils.class); 79 | HTTPRequest httpRequest = mock(HTTPRequest.class); 80 | AuthorizationResponse authorizationResponse = mock(AuthorizationResponse.class); 81 | AuthorizationSuccessResponse authorizationSuccessResponse = mock(AuthorizationSuccessResponse.class); 82 | AuthorizationCode authzCode = new AuthorizationCode("auth-code"); 83 | 84 | when(ServletUtils.createHTTPRequest(request)).thenReturn(httpRequest); 85 | when(AuthorizationResponse.parse(httpRequest)).thenReturn(authorizationResponse); 86 | when(authorizationResponse.indicatesSuccess()).thenReturn(true); 87 | when(authorizationResponse.toSuccessResponse()).thenReturn(authorizationSuccessResponse); 88 | when(authorizationSuccessResponse.getAuthorizationCode()).thenReturn(authzCode); 89 | 90 | OIDCRequestResolver resolver = new OIDCRequestResolver(request, oidcAgentConfig); 91 | assertTrue(resolver.isAuthorizationCodeResponse()); 92 | mockedAuthorizationResponse.close(); 93 | mockedServletUtils.close(); 94 | } 95 | 96 | @Test 97 | public void testIsLogoutURL() { 98 | 99 | OIDCAgentConfig config = new OIDCAgentConfig(); 100 | config.setLogoutURL("logout"); 101 | when(request.getRequestURI()).thenReturn("sampleContext/logout"); 102 | 103 | OIDCRequestResolver resolver = new OIDCRequestResolver(request, config); 104 | assertTrue(resolver.isLogoutURL()); 105 | } 106 | 107 | @Test 108 | public void testIsSkipURI() { 109 | 110 | OIDCAgentConfig config = new OIDCAgentConfig(); 111 | Set skipURIs = new HashSet(); 112 | skipURIs.add("sampleSkipURI1"); 113 | skipURIs.add("sampleSkipURI2"); 114 | config.setSkipURIs(skipURIs); 115 | when(request.getRequestURI()).thenReturn("sampleSkipURI1"); 116 | 117 | OIDCRequestResolver resolver = new OIDCRequestResolver(request, config); 118 | assertTrue(resolver.isSkipURI()); 119 | } 120 | 121 | @Test 122 | public void testIsCallbackResponse() throws URISyntaxException { 123 | 124 | OIDCAgentConfig config = new OIDCAgentConfig(); 125 | URI callbackURL = new URI("http://test/sampleCallback"); 126 | config.setCallbackUrl(callbackURL); 127 | when(request.getRequestURI()).thenReturn("sampleContext/sampleCallback"); 128 | 129 | OIDCRequestResolver resolver = new OIDCRequestResolver(request, config); 130 | assertTrue(resolver.isCallbackResponse()); 131 | } 132 | 133 | @AfterMethod 134 | public void tearDown() { 135 | 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/test/java/io/asgardeo/java/oidc/sdk/HTTPSessionBasedOIDCProcessorTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2020-2024, WSO2 LLC. (https://www.wso2.com). 3 | * 4 | * WSO2 LLC. 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.oidc.sdk; 20 | 21 | import com.nimbusds.oauth2.sdk.id.State; 22 | import com.nimbusds.openid.connect.sdk.Nonce; 23 | import io.asgardeo.java.oidc.sdk.bean.RequestContext; 24 | import io.asgardeo.java.oidc.sdk.bean.SessionContext; 25 | import io.asgardeo.java.oidc.sdk.config.model.OIDCAgentConfig; 26 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentException; 27 | import org.mockito.Mock; 28 | import org.mockito.MockedStatic; 29 | import org.powermock.core.classloader.annotations.PrepareForTest; 30 | import org.powermock.modules.testng.PowerMockTestCase; 31 | import org.testng.annotations.AfterMethod; 32 | import org.testng.annotations.BeforeMethod; 33 | import org.testng.annotations.Test; 34 | 35 | import javax.servlet.http.HttpServletRequest; 36 | import javax.servlet.http.HttpServletResponse; 37 | import javax.servlet.http.HttpSession; 38 | 39 | import static org.mockito.Mockito.mock; 40 | import static org.mockito.Mockito.mockStatic; 41 | import static org.mockito.Mockito.verify; 42 | import static org.mockito.Mockito.when; 43 | 44 | @PrepareForTest({DefaultOIDCManager.class, DefaultOIDCManagerFactory.class}) 45 | public class HTTPSessionBasedOIDCProcessorTest extends PowerMockTestCase { 46 | 47 | @Mock 48 | DefaultOIDCManager defaultOIDCManager; 49 | 50 | @Mock 51 | HttpServletRequest request; 52 | 53 | @Mock 54 | HttpServletResponse response; 55 | 56 | OIDCAgentConfig oidcAgentConfig = new OIDCAgentConfig(); 57 | 58 | private static MockedStatic mockedOIDCManagerFactory; 59 | 60 | @BeforeMethod 61 | public void setUp() throws Exception { 62 | 63 | defaultOIDCManager = mock(DefaultOIDCManager.class); 64 | request = mock(HttpServletRequest.class); 65 | response = mock(HttpServletResponse.class); 66 | } 67 | 68 | @AfterMethod 69 | public void tearDown() { 70 | 71 | mockedOIDCManagerFactory.close(); 72 | } 73 | 74 | @Test 75 | public void testSendForLogin() throws Exception { 76 | 77 | Nonce nonce = new Nonce(); 78 | State state = new State("SampleState"); 79 | RequestContext requestContext = new RequestContext(state, nonce); 80 | 81 | HttpSession session = mock(HttpSession.class); 82 | mockedOIDCManagerFactory = mockStatic(DefaultOIDCManagerFactory.class); 83 | when(DefaultOIDCManagerFactory.createOIDCManager(oidcAgentConfig)).thenReturn(defaultOIDCManager); 84 | when(request.getSession()).thenReturn(session); 85 | when(defaultOIDCManager.sendForLogin(request, response)).thenReturn(requestContext); 86 | 87 | HTTPSessionBasedOIDCProcessor provider = new HTTPSessionBasedOIDCProcessor(oidcAgentConfig); 88 | provider.sendForLogin(request, response); 89 | 90 | verify(session).setAttribute(SSOAgentConstants.REQUEST_CONTEXT, requestContext); 91 | } 92 | 93 | @Test 94 | public void testHandleOIDCCallback() throws SSOAgentException { 95 | 96 | SessionContext sessionContext = new SessionContext(); 97 | RequestContext requestContext = new RequestContext(); 98 | 99 | HttpSession session = mock(HttpSession.class); 100 | mockedOIDCManagerFactory = mockStatic(DefaultOIDCManagerFactory.class); 101 | when(DefaultOIDCManagerFactory.createOIDCManager(oidcAgentConfig)).thenReturn(defaultOIDCManager); 102 | when(request.getSession()).thenReturn(session); 103 | when(request.getSession(false)).thenReturn(session); 104 | when(session.getAttribute(SSOAgentConstants.REQUEST_CONTEXT)).thenReturn(requestContext); 105 | when(defaultOIDCManager.handleOIDCCallback(request, response, requestContext)).thenReturn(sessionContext); 106 | 107 | HTTPSessionBasedOIDCProcessor provider = new HTTPSessionBasedOIDCProcessor(oidcAgentConfig); 108 | provider.handleOIDCCallback(request, response); 109 | 110 | verify(session).setAttribute(SSOAgentConstants.SESSION_CONTEXT, sessionContext); 111 | } 112 | 113 | @Test 114 | public void testLogout() throws SSOAgentException { 115 | 116 | RequestContext requestContext = new RequestContext(); 117 | SessionContext sessionContext = new SessionContext(); 118 | 119 | HttpSession session = mock(HttpSession.class); 120 | mockedOIDCManagerFactory = mockStatic(DefaultOIDCManagerFactory.class); 121 | when(DefaultOIDCManagerFactory.createOIDCManager(oidcAgentConfig)).thenReturn(defaultOIDCManager); 122 | when(request.getSession()).thenReturn(session); 123 | when(request.getSession(false)).thenReturn(session); 124 | when(session.getAttribute(SSOAgentConstants.SESSION_CONTEXT)).thenReturn(sessionContext); 125 | when(defaultOIDCManager.logout(sessionContext, response)).thenReturn(requestContext); 126 | 127 | HTTPSessionBasedOIDCProcessor provider = new HTTPSessionBasedOIDCProcessor(oidcAgentConfig); 128 | provider.logout(request, response); 129 | 130 | verify(session).setAttribute(SSOAgentConstants.REQUEST_CONTEXT, requestContext); 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 21 | 22 | java-oidc-sdk 23 | io.asgardeo.java.oidc.sdk 24 | 0.1.31-SNAPSHOT 25 | ../pom.xml 26 | 27 | 28 | 4.0.0 29 | io.asgardeo.java.oidc.sdk 30 | jar 31 | Asgardeo - Java OIDC SDK 32 | http://asgardeo.io 33 | 34 | 35 | 36 | commons-lang.wso2 37 | commons-lang 38 | 39 | 40 | javax.servlet 41 | javax.servlet-api 42 | 43 | 44 | com.nimbusds 45 | nimbus-jose-jwt 46 | 47 | 48 | com.nimbusds 49 | oauth2-oidc-sdk 50 | 51 | 52 | org.wso2.apache.httpcomponents 53 | httpclient 54 | 55 | 56 | org.apache.logging.log4j 57 | log4j-api 58 | 59 | 60 | org.apache.logging.log4j 61 | log4j-core 62 | 63 | 64 | 65 | org.testng 66 | testng 67 | test 68 | 69 | 70 | org.powermock 71 | powermock-module-testng 72 | test 73 | 74 | 75 | org.mockito 76 | mockito-core 77 | test 78 | 79 | 80 | org.mockito 81 | mockito-inline 82 | test 83 | 84 | 85 | org.powermock 86 | powermock-api-mockito2 87 | test 88 | 89 | 90 | org.wiremock 91 | wiremock 92 | test 93 | 94 | 95 | org.eclipse.jetty 96 | jetty-server 97 | test 98 | 99 | 100 | org.eclipse.jetty 101 | jetty-servlet 102 | test 103 | 104 | 105 | org.eclipse.jetty 106 | jetty-util 107 | test 108 | 109 | 110 | org.jacoco 111 | jacoco-maven-plugin 112 | ${jacoco.version} 113 | 114 | 115 | 116 | 117 | src/main/java 118 | 119 | 120 | org.apache.maven.plugins 121 | maven-compiler-plugin 122 | 2.0 123 | 124 | 1.8 125 | 1.8 126 | 127 | 128 | 129 | org.jacoco 130 | jacoco-maven-plugin 131 | ${jacoco.version} 132 | 133 | 134 | 135 | prepare-agent 136 | 137 | 138 | 139 | report 140 | test 141 | 142 | report 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/request/OIDCRequestResolver.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.request; 20 | 21 | import com.nimbusds.oauth2.sdk.AuthorizationErrorResponse; 22 | import com.nimbusds.oauth2.sdk.AuthorizationResponse; 23 | import com.nimbusds.oauth2.sdk.AuthorizationSuccessResponse; 24 | import com.nimbusds.oauth2.sdk.http.ServletUtils; 25 | import io.asgardeo.java.oidc.sdk.SSOAgentConstants; 26 | import io.asgardeo.java.oidc.sdk.config.model.OIDCAgentConfig; 27 | import net.minidev.json.JSONObject; 28 | import org.apache.commons.lang.StringUtils; 29 | import org.apache.logging.log4j.Level; 30 | import org.apache.logging.log4j.LogManager; 31 | import org.apache.logging.log4j.Logger; 32 | 33 | import java.io.IOException; 34 | 35 | import javax.servlet.http.HttpServletRequest; 36 | 37 | /** 38 | * OIDCRequestResolver is the class responsible for resolving requests 39 | * based on the {@link OIDCAgentConfig} and the request parameters. 40 | *

41 | * OIDCRequestResolver verifies if: 42 | *

    43 | *
  • The request is a URL to skip 44 | *
  • The request is a Logout request 45 | *
  • The request is an error 46 | *
  • The request contains an authorization code response 47 | *
  • The request is a callback response 48 | *
49 | *

50 | * and returns boolean values. 51 | */ 52 | public class OIDCRequestResolver { 53 | 54 | private static final Logger logger = LogManager.getLogger(OIDCRequestResolver.class); 55 | 56 | OIDCAgentConfig oidcAgentConfig; 57 | HttpServletRequest request; 58 | 59 | public OIDCRequestResolver(HttpServletRequest request, OIDCAgentConfig oidcAgentConfig) { 60 | 61 | this.request = request; 62 | this.oidcAgentConfig = oidcAgentConfig; 63 | } 64 | 65 | /** 66 | * Checks if the request contains a parameter, "error". 67 | * 68 | * @return True if the request contains an "error" parameter, false otherwise. 69 | */ 70 | public boolean isError() { 71 | 72 | String error = request.getParameter(SSOAgentConstants.ERROR); 73 | return StringUtils.isNotBlank(error); 74 | } 75 | 76 | /** 77 | * Checks if the request is an Authorization Code response. 78 | * 79 | * @return True if the request is parsed as a valid Authorization response, false otherwise. 80 | */ 81 | public boolean isAuthorizationCodeResponse() { 82 | 83 | AuthorizationResponse authorizationResponse; 84 | AuthorizationSuccessResponse authorizationSuccessResponse; 85 | 86 | try { 87 | authorizationResponse = AuthorizationResponse.parse(ServletUtils.createHTTPRequest(request)); 88 | } catch (com.nimbusds.oauth2.sdk.ParseException | IOException e) { 89 | logger.log(Level.ERROR, "Error occurred while parsing the authorization response.", e); 90 | return false; 91 | } 92 | if (!authorizationResponse.indicatesSuccess()) { 93 | logErrorAuthorizationResponse(authorizationResponse); 94 | return false; 95 | } 96 | authorizationSuccessResponse = authorizationResponse.toSuccessResponse(); 97 | if (authorizationSuccessResponse.getAuthorizationCode() == null) { 98 | return false; 99 | } 100 | return true; 101 | } 102 | 103 | /** 104 | * Checks if the request is a logout request. 105 | * 106 | * @return True if the request ends with the logout URL configured in the {@link OIDCAgentConfig}, false otherwise. 107 | */ 108 | public boolean isLogoutURL() { 109 | 110 | return request.getRequestURI().endsWith(oidcAgentConfig.getLogoutURL()); 111 | } 112 | 113 | /** 114 | * Checks if the request is a URI to skip. 115 | * 116 | * @return True if the request is a URL configured in the {@link OIDCAgentConfig} as skipURIs, false otherwise. 117 | */ 118 | public boolean isSkipURI() { 119 | 120 | return oidcAgentConfig.getSkipURIs().contains(request.getRequestURI()); 121 | } 122 | 123 | /** 124 | * Checks if the request contains is_logout parameter. 125 | * 126 | * @return True if the request contains a parameter called is_logout and its value is true, false otherwise. 127 | */ 128 | public boolean isLogout() { 129 | 130 | if (request.getAttribute(SSOAgentConstants.IS_LOGOUT) != null) { 131 | return (boolean) request.getAttribute(SSOAgentConstants.IS_LOGOUT); 132 | } 133 | return false; 134 | } 135 | 136 | /** 137 | * Checks if the request is a callback response. 138 | * 139 | * @return True if the request contains the path of the callback URL configured in the {@link OIDCAgentConfig}, 140 | * false otherwise. 141 | */ 142 | public boolean isCallbackResponse() { 143 | 144 | String callbackContext = oidcAgentConfig.getCallbackUrl().getPath(); 145 | 146 | return request.getRequestURI().contains(callbackContext); 147 | } 148 | 149 | private void logErrorAuthorizationResponse(AuthorizationResponse authzResponse) { 150 | 151 | AuthorizationErrorResponse errorResponse = authzResponse.toErrorResponse(); 152 | JSONObject responseObject = errorResponse.getErrorObject().toJSONObject(); 153 | 154 | logger.log(Level.INFO, "Error response object: ", responseObject); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/request/OIDCRequestBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.request; 20 | 21 | import com.nimbusds.jwt.JWT; 22 | import com.nimbusds.jwt.JWTParser; 23 | import com.nimbusds.oauth2.sdk.ResponseType; 24 | import com.nimbusds.oauth2.sdk.Scope; 25 | import com.nimbusds.oauth2.sdk.id.ClientID; 26 | import com.nimbusds.oauth2.sdk.id.State; 27 | import com.nimbusds.openid.connect.sdk.AuthenticationRequest; 28 | import com.nimbusds.openid.connect.sdk.LogoutRequest; 29 | import com.nimbusds.openid.connect.sdk.Nonce; 30 | import io.asgardeo.java.oidc.sdk.OIDCManager; 31 | import io.asgardeo.java.oidc.sdk.bean.RequestContext; 32 | import io.asgardeo.java.oidc.sdk.bean.SessionContext; 33 | import io.asgardeo.java.oidc.sdk.config.model.OIDCAgentConfig; 34 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentServerException; 35 | import org.apache.commons.lang.StringUtils; 36 | import org.apache.logging.log4j.LogManager; 37 | import org.apache.logging.log4j.Logger; 38 | 39 | import java.net.URI; 40 | import java.text.ParseException; 41 | import java.util.Map; 42 | import java.util.UUID; 43 | 44 | /** 45 | * OIDCRequestBuilder is the class responsible for building requests 46 | * for the {@link OIDCManager} based on the {@link OIDCAgentConfig}. 47 | *

48 | * OIDCRequestBuilder can build: 49 | *

    50 | *
  • Authorization requests 51 | *
  • Logout requests 52 | *
53 | *

54 | * and return the String values of the generated requests. 55 | */ 56 | public class OIDCRequestBuilder { 57 | 58 | private static final Logger logger = LogManager.getLogger(OIDCRequestResolver.class); 59 | 60 | OIDCAgentConfig oidcAgentConfig; 61 | 62 | public OIDCRequestBuilder(OIDCAgentConfig oidcAgentConfig) { 63 | 64 | this.oidcAgentConfig = oidcAgentConfig; 65 | } 66 | 67 | /** 68 | * Returns {@link io.asgardeo.java.oidc.sdk.request.model.AuthenticationRequest} Authentication request. 69 | * To build the authentication request, {@link OIDCAgentConfig} should contain: 70 | *

    71 | *
  • The client ID 72 | *
  • The scope 73 | *
  • The callback URI 74 | *
  • The authorization endpoint URI 75 | *
76 | * 77 | * @return Authentication request. 78 | */ 79 | public io.asgardeo.java.oidc.sdk.request.model.AuthenticationRequest buildAuthenticationRequest() { 80 | 81 | ResponseType responseType = new ResponseType(ResponseType.Value.CODE); 82 | ClientID clientID = oidcAgentConfig.getConsumerKey(); 83 | Scope authScope = oidcAgentConfig.getScope(); 84 | URI callBackURI = oidcAgentConfig.getCallbackUrl(); 85 | URI authorizationEndpoint = oidcAgentConfig.getAuthorizeEndpoint(); 86 | Map additionalParamsForAuthzEndpoint = 87 | oidcAgentConfig.getAdditionalParamsForAuthorizeEndpoint(); 88 | State state = resolveState(); 89 | Nonce nonce = new Nonce(); 90 | RequestContext requestContext = new RequestContext(state, nonce); 91 | 92 | AuthenticationRequest.Builder authenticationRequestBuilder = 93 | new AuthenticationRequest.Builder(responseType, authScope, 94 | clientID, callBackURI) 95 | .state(state) 96 | .endpointURI(authorizationEndpoint) 97 | .nonce(nonce); 98 | // Add additional query params to authentication endpoint and request context. 99 | if (additionalParamsForAuthzEndpoint != null) { 100 | additionalParamsForAuthzEndpoint.forEach((key, value) -> { 101 | authenticationRequestBuilder.customParameter(key, value); 102 | requestContext.setParameter(key, value); 103 | }); 104 | } 105 | 106 | // Build authenticationRequest. 107 | AuthenticationRequest authenticationRequest = authenticationRequestBuilder.build(); 108 | 109 | io.asgardeo.java.oidc.sdk.request.model.AuthenticationRequest authRequest = 110 | new io.asgardeo.java.oidc.sdk.request.model.AuthenticationRequest(authenticationRequest.toURI(), 111 | requestContext); 112 | 113 | return authRequest; 114 | } 115 | 116 | /** 117 | * Returns {@link io.asgardeo.java.oidc.sdk.request.model.LogoutRequest} Logout request. To build the logout request, 118 | * {@link OIDCAgentConfig} should contain: 119 | *
    120 | *
  • The logout endpoint URI 121 | *
  • The post logout redirection URI 122 | *
123 | * 124 | * @param sessionContext {@link SessionContext} object with information of the current LoggedIn session. 125 | * It must include a valid ID token. 126 | * @return Logout request. 127 | */ 128 | public io.asgardeo.java.oidc.sdk.request.model.LogoutRequest buildLogoutRequest(SessionContext sessionContext) 129 | throws SSOAgentServerException { 130 | 131 | URI logoutEP = oidcAgentConfig.getLogoutEndpoint(); 132 | URI redirectionURI = oidcAgentConfig.getPostLogoutRedirectURI(); 133 | JWT jwtIdToken = null; 134 | try { 135 | jwtIdToken = JWTParser.parse(sessionContext.getIdToken()); 136 | } catch (ParseException e) { 137 | throw new SSOAgentServerException(e.getMessage(), e); 138 | } 139 | State state = generateStateParameter(); 140 | RequestContext requestContext = new RequestContext(); 141 | 142 | requestContext.setState(state); 143 | URI logoutRequestURI; 144 | 145 | try { 146 | logoutRequestURI = new LogoutRequest(logoutEP, jwtIdToken, redirectionURI, state).toURI(); 147 | } catch (Exception e) { 148 | throw new SSOAgentServerException(e.getMessage(), e); 149 | } 150 | 151 | return new io.asgardeo.java.oidc.sdk.request.model.LogoutRequest(logoutRequestURI, requestContext); 152 | } 153 | 154 | private State resolveState() { 155 | 156 | String stateParam = oidcAgentConfig.getState(); 157 | if (StringUtils.isBlank(stateParam)) { 158 | return generateStateParameter(); 159 | } 160 | return new State(stateParam); 161 | } 162 | 163 | private State generateStateParameter() { 164 | 165 | UUID uuid = UUID.randomUUID(); 166 | return new State(uuid.toString()); 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/SSOAgentConstants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk; 20 | 21 | import java.util.Arrays; 22 | import java.util.HashSet; 23 | import java.util.Set; 24 | 25 | /** 26 | * This class holds the constants used in the module, io.asgardeo.java.oidc.sdk. 27 | */ 28 | public class SSOAgentConstants { 29 | 30 | public static final String CONFIG_BEAN_NAME = "io.asgardeo.java.oidc.sdk.config.model.OIDCAgentConfig"; 31 | 32 | // Oauth response parameters and session attributes. 33 | public static final String ERROR = "error"; 34 | public static final String ACCESS_TOKEN = "access_token"; 35 | public static final String ID_TOKEN = "id_token"; 36 | public static final String SESSION_STATE = "session_state"; 37 | public static final String USER = "user"; 38 | public static final String REQUEST_CONTEXT = "request_context"; 39 | public static final String SESSION_CONTEXT = "session_context"; 40 | public static final String DEFAULT_CONTEXT_ROOT = "/"; 41 | public static final String IS_LOGOUT = "isLogout"; 42 | 43 | // Keystore file properties. 44 | public static final String KEYSTORE_NAME = "keystorename"; 45 | public static final String KEYSTORE_PASSWORD = "keystorepassword"; 46 | 47 | // Application specific request parameters and session attributes. 48 | public static final String CONSUMER_KEY = "consumerKey"; 49 | public static final String CONSUMER_SECRET = "consumerSecret"; 50 | public static final String CALL_BACK_URL = "callBackURL"; 51 | public static final String SKIP_URIS = "skipURIs"; 52 | public static final String REDIRECT_URI_KEY = "redirectURI"; 53 | public static final String INDEX_PAGE = "indexPage"; 54 | public static final String ERROR_PAGE = "errorPage"; 55 | public static final String HOME_PAGE = "homePage"; 56 | public static final String LOGOUT_URL = "logoutURL"; 57 | public static final String SCOPE = "scope"; 58 | public static final String OAUTH2_GRANT_TYPE = "grantType"; 59 | public static final String OAUTH2_AUTHZ_ENDPOINT = "authorizeEndpoint"; 60 | public static final String OIDC_LOGOUT_ENDPOINT = "logoutEndpoint"; 61 | public static final String OIDC_SESSION_IFRAME_ENDPOINT = "sessionIFrameEndpoint"; 62 | public static final String OIDC_TOKEN_ENDPOINT = "tokenEndpoint"; 63 | public static final String OIDC_ISSUER = "issuer"; 64 | public static final String OIDC_JWKS_ENDPOINT = "jwksEndpoint"; 65 | public static final String POST_LOGOUT_REDIRECTION_URI = "postLogoutRedirectURI"; 66 | public static final String AUTHENTICATED = "authenticated"; 67 | public static final String OIDC_OPENID = "openid"; 68 | public static final String AZP = "azp"; 69 | public static final String TRUSTED_AUDIENCE = "trustedAudience"; 70 | public static final String ID_TOKEN_SIGN_ALG = "signatureAlgorithm"; 71 | public static final String NONCE = "nonce"; 72 | public static final String AGENT_EXCEPTION = "AgentException"; 73 | public static final String HTTP_CONNECT_TIMEOUT = "httpConnectTimeout"; 74 | public static final String HTTP_READ_TIMEOUT = "httpReadTimeout"; 75 | public static final String HTTP_SIZE_LIMIT = "httpSizeLimit"; 76 | public static final String STATE_PARAM = "state"; 77 | public static final String ADDITIONAL_PARAMS_FOR_AUTHZ_EP = "additionalParamsForAuthorizeEndpoint"; 78 | public static final String ERROR_DESCRIPTION = "error_description"; 79 | 80 | // Request headers. 81 | public static final String REFERER = "referer"; 82 | 83 | // Context params. 84 | public static final String APP_PROPERTY_FILE_PARAMETER_NAME = "app-property-file"; 85 | public static final String JKS_PROPERTY_FILE_PARAMETER_NAME = "jks-property-file"; 86 | 87 | // Response types. 88 | public static final String CODE = "code"; 89 | public static final String TOKEN = "token"; 90 | 91 | // Resource Retriever params. 92 | /** 93 | * The default HTTP connect timeout in milliseconds. Set to 2000 milliseconds. 94 | */ 95 | public static final int DEFAULT_HTTP_CONNECT_TIMEOUT = 2000; 96 | 97 | /** 98 | * The default HTTP read timeout in milliseconds. Set to 2000 milliseconds. 99 | */ 100 | public static final int DEFAULT_HTTP_READ_TIMEOUT = 2000; 101 | 102 | /** 103 | * The default HTTP entity size limit in bytes. Set to 50 KBytes. 104 | */ 105 | public static final int DEFAULT_HTTP_SIZE_LIMIT = 50 * 1024; 106 | 107 | public static final Set OIDC_METADATA_CLAIMS = new HashSet<>( 108 | Arrays.asList("at_hash", "sub", "iss", "aud", "nbf", "c_hash", "azp", "amr", "sid", "exp", "iat")); 109 | 110 | public enum ErrorMessages { 111 | 112 | AUTHENTICATION_FAILED("18001", "Authentication Failed."), 113 | ID_TOKEN_NULL("18002", "Null ID token."), 114 | ID_TOKEN_PARSE("18003", "Error found with parsing the ID token."), 115 | JWT_PARSE("18004", "Error found with parsing JWT."), 116 | AGENT_CONFIG_SCOPE("18005", 117 | "Scope parameter defined incorrectly. Scope parameter must contain the value 'openid'"), 118 | AGENT_CONFIG_CLIENT_ID("18006", 119 | "Consumer Key/Client ID must not be null. This refers to the client identifier assigned to the " + 120 | "Relying Party during its registration with the OpenID Provider."), 121 | AGENT_CONFIG_CLIENT_SECRET("18007", "Consumer secret/Client secret must not be null."), 122 | AGENT_CONFIG_CALLBACK_URL("18008", 123 | "Callback URL/Redirection URL must not be null. This refers to the Relying Party's redirection URIs " + 124 | "registered with the OpenID Provider."), 125 | SERVLET_CONNECTION("18009", "Error found with connection."); 126 | 127 | private final String code; 128 | private final String message; 129 | 130 | ErrorMessages(String code, String message) { 131 | 132 | this.code = code; 133 | this.message = message; 134 | } 135 | 136 | public String getCode() { 137 | 138 | return code; 139 | } 140 | 141 | public String getMessage() { 142 | 143 | return message; 144 | } 145 | 146 | @Override 147 | public String toString() { 148 | 149 | return code + " - " + message; 150 | } 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/validators/IDTokenValidator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.validators; 20 | 21 | import com.nimbusds.jose.JOSEException; 22 | import com.nimbusds.jose.JWSAlgorithm; 23 | import com.nimbusds.jose.proc.BadJOSEException; 24 | import com.nimbusds.jose.util.DefaultResourceRetriever; 25 | import com.nimbusds.jose.util.ResourceRetriever; 26 | import com.nimbusds.jwt.JWT; 27 | import com.nimbusds.oauth2.sdk.auth.Secret; 28 | import com.nimbusds.oauth2.sdk.id.Audience; 29 | import com.nimbusds.oauth2.sdk.id.ClientID; 30 | import com.nimbusds.oauth2.sdk.id.Issuer; 31 | import com.nimbusds.openid.connect.sdk.Nonce; 32 | import com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet; 33 | import io.asgardeo.java.oidc.sdk.SSOAgentConstants; 34 | import io.asgardeo.java.oidc.sdk.config.model.OIDCAgentConfig; 35 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentServerException; 36 | import org.apache.logging.log4j.LogManager; 37 | import org.apache.logging.log4j.Logger; 38 | 39 | import java.net.URI; 40 | import java.util.List; 41 | import java.util.Set; 42 | 43 | /** 44 | * Validator of ID tokens issued by an OpenID Provider. 45 | * 46 | *

Supports processing of ID tokens with: 47 | * 48 | *

    49 | *
  • ID tokens signed (JWS) with the OP's RSA or EC key, require the 50 | * OP public JWK set (provided by value or URL) to verify them. 51 | *
  • ID tokens authenticated with a JWS HMAC, require the client's secret 52 | * to verify them. 53 | *
54 | */ 55 | public class IDTokenValidator { 56 | 57 | private static final Logger logger = LogManager.getLogger(IDTokenValidator.class); 58 | 59 | private OIDCAgentConfig oidcAgentConfig; 60 | private JWT idToken; 61 | 62 | public IDTokenValidator(OIDCAgentConfig oidcAgentConfig, JWT idToken) { 63 | 64 | this.oidcAgentConfig = oidcAgentConfig; 65 | this.idToken = idToken; 66 | } 67 | 68 | public IDTokenClaimsSet validate(Nonce expectedNonce) throws SSOAgentServerException { 69 | 70 | JWSAlgorithm jwsAlgorithm = validateJWSAlgorithm(idToken); 71 | com.nimbusds.openid.connect.sdk.validators.IDTokenValidator validator = getIDTokenValidator(jwsAlgorithm); 72 | IDTokenClaimsSet claims; 73 | try { 74 | claims = validator.validate(idToken, expectedNonce); 75 | validateAudience(claims); 76 | } catch (JOSEException | BadJOSEException e) { 77 | throw new SSOAgentServerException(e.getMessage(), e.getCause()); 78 | } 79 | return claims; 80 | } 81 | 82 | private com.nimbusds.openid.connect.sdk.validators.IDTokenValidator getIDTokenValidator(JWSAlgorithm jwsAlgorithm) 83 | throws SSOAgentServerException { 84 | 85 | Issuer issuer = oidcAgentConfig.getIssuer(); 86 | URI jwkSetURI = oidcAgentConfig.getJwksEndpoint(); 87 | ClientID clientID = oidcAgentConfig.getConsumerKey(); 88 | Secret clientSecret = oidcAgentConfig.getConsumerSecret(); 89 | int httpConnectTimeout = oidcAgentConfig.getHttpConnectTimeout(); 90 | int httpReadTimeout = oidcAgentConfig.getHttpReadTimeout(); 91 | int httpSizeLimit = oidcAgentConfig.getHttpSizeLimit(); 92 | com.nimbusds.openid.connect.sdk.validators.IDTokenValidator validator; 93 | ResourceRetriever resourceRetriever = 94 | new DefaultResourceRetriever(httpConnectTimeout, httpReadTimeout, httpSizeLimit); 95 | 96 | // Creates a new validator for RSA, EC or ED protected ID tokens. 97 | if (JWSAlgorithm.Family.RSA.contains(jwsAlgorithm) || JWSAlgorithm.Family.EC.contains(jwsAlgorithm) || 98 | JWSAlgorithm.Family.ED.contains(jwsAlgorithm)) { 99 | try { 100 | validator = 101 | new com.nimbusds.openid.connect.sdk.validators.IDTokenValidator(issuer, clientID, jwsAlgorithm, 102 | jwkSetURI.toURL(), resourceRetriever); 103 | } catch (Exception e) { 104 | throw new SSOAgentServerException(e.getMessage(), e.getCause()); 105 | } 106 | // Creates a new validator for HMAC protected ID tokens. 107 | } else if (JWSAlgorithm.Family.HMAC_SHA.contains(jwsAlgorithm)) { 108 | validator = new com.nimbusds.openid.connect.sdk.validators.IDTokenValidator(issuer, clientID, jwsAlgorithm, 109 | clientSecret); 110 | } else { 111 | throw new SSOAgentServerException(String.format("Unsupported algorithm: %s.", jwsAlgorithm.getName())); 112 | } 113 | return validator; 114 | } 115 | 116 | private JWSAlgorithm validateJWSAlgorithm(JWT idToken) throws SSOAgentServerException { 117 | 118 | JWSAlgorithm jwsAlgorithm = (JWSAlgorithm) idToken.getHeader().getAlgorithm(); 119 | JWSAlgorithm expectedJWSAlgorithm = oidcAgentConfig.getSignatureAlgorithm(); 120 | 121 | if (expectedJWSAlgorithm == null) { 122 | if (JWSAlgorithm.RS256.equals(jwsAlgorithm)) { 123 | return jwsAlgorithm; 124 | } else { 125 | throw new SSOAgentServerException(String.format("Signed JWT rejected. Provided signature algorithm: " + 126 | "%s is not the default of RS256.", jwsAlgorithm.getName())); 127 | } 128 | } else if (!expectedJWSAlgorithm.equals(jwsAlgorithm)) { 129 | throw new SSOAgentServerException(String.format("Signed JWT rejected: Another algorithm expected. " + 130 | "Provided signature algorithm: %s.", jwsAlgorithm.getName())); 131 | } 132 | return jwsAlgorithm; 133 | } 134 | 135 | private void validateAudience(IDTokenClaimsSet claimsSet) 136 | throws SSOAgentServerException { 137 | 138 | List audience = claimsSet.getAudience(); 139 | if (audience.size() > 1) { 140 | if (claimsSet.getClaim(SSOAgentConstants.AZP) == null) { 141 | throw new SSOAgentServerException("ID token validation failed. AZP claim cannot be null for multiple " + 142 | "audiences."); 143 | } 144 | Set trustedAudience = oidcAgentConfig.getTrustedAudience(); 145 | for (Audience aud : audience) { 146 | if (!trustedAudience.contains(aud.getValue())) { 147 | throw new SSOAgentServerException("ID token validation failed. Untrusted JWT audience."); 148 | } 149 | } 150 | } 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/HTTPSessionBasedOIDCProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk; 20 | 21 | import io.asgardeo.java.oidc.sdk.bean.RequestContext; 22 | import io.asgardeo.java.oidc.sdk.bean.SessionContext; 23 | import io.asgardeo.java.oidc.sdk.config.model.OIDCAgentConfig; 24 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentClientException; 25 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentException; 26 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentServerException; 27 | import org.apache.commons.lang.StringUtils; 28 | import org.apache.logging.log4j.LogManager; 29 | import org.apache.logging.log4j.Logger; 30 | 31 | import javax.servlet.http.HttpServletRequest; 32 | import javax.servlet.http.HttpServletResponse; 33 | import javax.servlet.http.HttpSession; 34 | 35 | /** 36 | * A wrapper class for the {@link DefaultOIDCManager} that provides 37 | * the functionality defined by the {@link OIDCManager} with using 38 | * HTTP sessions as the storage entity for the {@link RequestContext} 39 | * and {@link SessionContext} information. 40 | */ 41 | public class HTTPSessionBasedOIDCProcessor { 42 | 43 | private static final Logger logger = LogManager.getLogger(HTTPSessionBasedOIDCProcessor.class); 44 | 45 | private final OIDCManager defaultOIDCManager; 46 | 47 | public HTTPSessionBasedOIDCProcessor(OIDCAgentConfig oidcAgentConfig) throws SSOAgentClientException { 48 | 49 | defaultOIDCManager = DefaultOIDCManagerFactory.createOIDCManager(oidcAgentConfig); 50 | } 51 | 52 | /** 53 | * Builds an authentication request and redirects. Information 54 | * regarding the authentication session would be retrieved via 55 | * {@link RequestContext} object and then, would be written to 56 | * the http session. 57 | * 58 | * @param request Incoming {@link HttpServletRequest}. 59 | * @param response Outgoing {@link HttpServletResponse}. 60 | * @throws SSOAgentException 61 | */ 62 | public void sendForLogin(HttpServletRequest request, HttpServletResponse response) 63 | throws SSOAgentException { 64 | 65 | HttpSession session = request.getSession(); 66 | RequestContext requestContext = defaultOIDCManager.sendForLogin(request, response); 67 | if (request.getRequestURI() != null) { 68 | StringBuilder redirectPageURI = new StringBuilder(); 69 | redirectPageURI.append(request.getRequestURI().substring(request.getContextPath().length() + 1)); 70 | if (StringUtils.isNotBlank(request.getQueryString())) { 71 | redirectPageURI.append("?").append(request.getQueryString()); 72 | } 73 | requestContext.setParameter(SSOAgentConstants.REDIRECT_URI_KEY, redirectPageURI.toString()); 74 | } 75 | session.setAttribute(SSOAgentConstants.REQUEST_CONTEXT, requestContext); 76 | } 77 | 78 | /** 79 | * Processes the OIDC callback response and extract the authorization 80 | * code, builds a token request, sends the token request and parse 81 | * the token response where the authenticated user info and tokens 82 | * would be added to the {@link SessionContext} object and written 83 | * into the available http session. 84 | * 85 | * @param request Incoming {@link HttpServletRequest}. 86 | * @param response Outgoing {@link HttpServletResponse}. 87 | * @throws SSOAgentException Upon failed authentication. 88 | */ 89 | public void handleOIDCCallback(HttpServletRequest request, HttpServletResponse response) throws SSOAgentException { 90 | 91 | RequestContext requestContext = getRequestContext(request); 92 | clearSession(request); 93 | SessionContext sessionContext = defaultOIDCManager.handleOIDCCallback(request, response, requestContext); 94 | 95 | if (sessionContext != null) { 96 | if (sessionContext.getAdditionalParams().containsKey(SSOAgentConstants.IS_LOGOUT) && 97 | ((boolean)sessionContext.getAdditionalParams().get(SSOAgentConstants.IS_LOGOUT))) { 98 | request.setAttribute(SSOAgentConstants.IS_LOGOUT, true); 99 | clearSession(request); 100 | } else { 101 | clearSession(request); 102 | HttpSession session = request.getSession(); 103 | session.setAttribute(SSOAgentConstants.SESSION_CONTEXT, sessionContext); 104 | } 105 | } else { 106 | throw new SSOAgentServerException("Null session context."); 107 | } 108 | } 109 | 110 | /** 111 | * Builds a logout request and redirects. 112 | * 113 | * @param request Incoming {@link HttpServletRequest}. 114 | * @param response Outgoing {@link HttpServletResponse} 115 | * @throws SSOAgentException 116 | */ 117 | public void logout(HttpServletRequest request, HttpServletResponse response) throws SSOAgentException { 118 | 119 | SessionContext sessionContext = getSessionContext(request); 120 | clearSession(request); 121 | HttpSession session = request.getSession(); 122 | RequestContext requestContext = defaultOIDCManager.logout(sessionContext, response); 123 | session.setAttribute(SSOAgentConstants.REQUEST_CONTEXT, requestContext); 124 | } 125 | 126 | private void clearSession(HttpServletRequest request) { 127 | 128 | HttpSession session = request.getSession(false); 129 | 130 | if (session != null) { 131 | session.invalidate(); 132 | } 133 | } 134 | 135 | private RequestContext getRequestContext(HttpServletRequest request) throws SSOAgentServerException { 136 | 137 | HttpSession session = request.getSession(false); 138 | 139 | if (session != null && session.getAttribute(SSOAgentConstants.REQUEST_CONTEXT) != null) { 140 | return (RequestContext) request.getSession(false) 141 | .getAttribute(SSOAgentConstants.REQUEST_CONTEXT); 142 | } 143 | throw new SSOAgentServerException("Request context null."); 144 | } 145 | 146 | private SessionContext getSessionContext(HttpServletRequest request) throws SSOAgentServerException { 147 | 148 | HttpSession session = request.getSession(false); 149 | 150 | if (session != null && session.getAttribute(SSOAgentConstants.SESSION_CONTEXT) != null) { 151 | return (SessionContext) request.getSession(false) 152 | .getAttribute(SSOAgentConstants.SESSION_CONTEXT); 153 | } 154 | throw new SSOAgentServerException("Session context null."); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/config/FileBasedOIDCConfigProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.config; 20 | 21 | import com.nimbusds.jose.JWSAlgorithm; 22 | import com.nimbusds.oauth2.sdk.Scope; 23 | import com.nimbusds.oauth2.sdk.auth.Secret; 24 | import com.nimbusds.oauth2.sdk.id.ClientID; 25 | import com.nimbusds.oauth2.sdk.id.Issuer; 26 | import io.asgardeo.java.oidc.sdk.SSOAgentConstants; 27 | import io.asgardeo.java.oidc.sdk.config.model.OIDCAgentConfig; 28 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentClientException; 29 | import org.apache.commons.lang.StringUtils; 30 | import org.apache.logging.log4j.Level; 31 | import org.apache.logging.log4j.LogManager; 32 | import org.apache.logging.log4j.Logger; 33 | 34 | import java.io.IOException; 35 | import java.io.InputStream; 36 | import java.net.URI; 37 | import java.net.URISyntaxException; 38 | import java.util.Collections; 39 | import java.util.HashSet; 40 | import java.util.Properties; 41 | import java.util.Set; 42 | 43 | /** 44 | * A file-based provider implementation for the {@link OIDCAgentConfig} model. 45 | * It is an implementation of the base class, {@link OIDCConfigProvider}. 46 | */ 47 | public class FileBasedOIDCConfigProvider implements OIDCConfigProvider { 48 | 49 | private static final Logger logger = LogManager.getLogger(FileBasedOIDCConfigProvider.class); 50 | 51 | private final OIDCAgentConfig oidcAgentConfig = new OIDCAgentConfig(); 52 | 53 | public FileBasedOIDCConfigProvider(InputStream fileInputStream) throws SSOAgentClientException { 54 | 55 | Properties properties = new Properties(); 56 | try { 57 | properties.load(fileInputStream); 58 | } catch (IOException e) { 59 | logger.log(Level.FATAL, "Error while loading properties.", e); 60 | } 61 | initConfig(properties); 62 | } 63 | 64 | private void initConfig(Properties properties) throws SSOAgentClientException { 65 | 66 | ClientID consumerKey = StringUtils.isNotBlank(properties.getProperty(SSOAgentConstants.CONSUMER_KEY)) ? 67 | new ClientID(properties.getProperty(SSOAgentConstants.CONSUMER_KEY)) : null; 68 | Secret consumerSecret = StringUtils.isNotBlank(properties.getProperty(SSOAgentConstants.CONSUMER_SECRET)) ? 69 | new Secret(properties.getProperty(SSOAgentConstants.CONSUMER_SECRET)) : null; 70 | String indexPage = properties.getProperty(SSOAgentConstants.INDEX_PAGE); 71 | String errorPage = properties.getProperty(SSOAgentConstants.ERROR_PAGE); 72 | String homePage = properties.getProperty(SSOAgentConstants.HOME_PAGE); 73 | String logoutURL = properties.getProperty(SSOAgentConstants.LOGOUT_URL); 74 | JWSAlgorithm jwsAlgorithm = 75 | StringUtils.isNotBlank(properties.getProperty(SSOAgentConstants.ID_TOKEN_SIGN_ALG)) ? 76 | new JWSAlgorithm(properties.getProperty(SSOAgentConstants.ID_TOKEN_SIGN_ALG)) : null; 77 | try { 78 | int httpConnectTimeout = resolveConnectionConfig(properties, SSOAgentConstants.HTTP_CONNECT_TIMEOUT, 79 | SSOAgentConstants.DEFAULT_HTTP_CONNECT_TIMEOUT); 80 | int httpReadTimeout = resolveConnectionConfig(properties, SSOAgentConstants.HTTP_READ_TIMEOUT, 81 | SSOAgentConstants.DEFAULT_HTTP_READ_TIMEOUT); 82 | int httpSizeLimit = resolveConnectionConfig(properties, SSOAgentConstants.HTTP_SIZE_LIMIT, 83 | SSOAgentConstants.DEFAULT_HTTP_SIZE_LIMIT); 84 | 85 | oidcAgentConfig.setHttpConnectTimeout(httpConnectTimeout); 86 | oidcAgentConfig.setHttpReadTimeout(httpReadTimeout); 87 | oidcAgentConfig.setHttpSizeLimit(httpSizeLimit); 88 | } catch (NumberFormatException e) { 89 | throw new SSOAgentClientException("Not a number.", e); 90 | } 91 | 92 | try { 93 | URI callbackUrl = StringUtils.isNotBlank(properties.getProperty(SSOAgentConstants.CALL_BACK_URL)) ? 94 | new URI(properties.getProperty(SSOAgentConstants.CALL_BACK_URL)) : null; 95 | URI authorizeEndpoint = 96 | StringUtils.isNotBlank(properties.getProperty(SSOAgentConstants.OAUTH2_AUTHZ_ENDPOINT)) ? 97 | new URI(properties.getProperty(SSOAgentConstants.OAUTH2_AUTHZ_ENDPOINT)) : null; 98 | URI logoutEndpoint = 99 | StringUtils.isNotBlank(properties.getProperty(SSOAgentConstants.OIDC_LOGOUT_ENDPOINT)) ? 100 | new URI(properties.getProperty(SSOAgentConstants.OIDC_LOGOUT_ENDPOINT)) : null; 101 | URI tokenEndpoint = StringUtils.isNotBlank(properties.getProperty(SSOAgentConstants.OIDC_TOKEN_ENDPOINT)) ? 102 | new URI(properties.getProperty(SSOAgentConstants.OIDC_TOKEN_ENDPOINT)) : null; 103 | URI jwksEndpoint = StringUtils.isNotBlank(properties.getProperty(SSOAgentConstants.OIDC_JWKS_ENDPOINT)) ? 104 | new URI(properties.getProperty(SSOAgentConstants.OIDC_JWKS_ENDPOINT)) : null; 105 | URI postLogoutRedirectURI = 106 | StringUtils.isNotBlank(properties.getProperty(SSOAgentConstants.POST_LOGOUT_REDIRECTION_URI)) ? 107 | new URI(properties.getProperty(SSOAgentConstants.POST_LOGOUT_REDIRECTION_URI)) : 108 | callbackUrl; 109 | 110 | oidcAgentConfig.setCallbackUrl(callbackUrl); 111 | oidcAgentConfig.setAuthorizeEndpoint(authorizeEndpoint); 112 | oidcAgentConfig.setLogoutEndpoint(logoutEndpoint); 113 | oidcAgentConfig.setTokenEndpoint(tokenEndpoint); 114 | oidcAgentConfig.setJwksEndpoint(jwksEndpoint); 115 | oidcAgentConfig.setPostLogoutRedirectURI(postLogoutRedirectURI); 116 | } catch (URISyntaxException e) { 117 | throw new SSOAgentClientException("URL not formatted properly.", e); 118 | } 119 | 120 | Issuer issuer = StringUtils.isNotBlank(properties.getProperty(SSOAgentConstants.OIDC_ISSUER)) ? 121 | new Issuer(properties.getProperty(SSOAgentConstants.OIDC_ISSUER)) : null; 122 | String scopeString = properties.getProperty(SSOAgentConstants.SCOPE); 123 | if (StringUtils.isNotBlank(scopeString)) { 124 | String[] scopeArray = scopeString.split(","); 125 | Scope scope = new Scope(scopeArray); 126 | oidcAgentConfig.setScope(scope); 127 | } 128 | 129 | Set skipURIs = new HashSet(); 130 | String skipURIsString = properties.getProperty(SSOAgentConstants.SKIP_URIS); 131 | if (StringUtils.isNotBlank(skipURIsString)) { 132 | String[] skipURIArray = skipURIsString.split(","); 133 | Collections.addAll(skipURIs, skipURIArray); 134 | } 135 | if (StringUtils.isNotBlank(indexPage)) { 136 | skipURIs.add(indexPage); 137 | } 138 | if (StringUtils.isNotBlank(errorPage)) { 139 | skipURIs.add(errorPage); 140 | } 141 | Set trustedAudience = new HashSet(); 142 | trustedAudience.add(consumerKey.getValue()); 143 | String trustedAudienceString = properties.getProperty(SSOAgentConstants.TRUSTED_AUDIENCE); 144 | if (StringUtils.isNotBlank(trustedAudienceString)) { 145 | String[] trustedAudienceArray = trustedAudienceString.split(","); 146 | Collections.addAll(trustedAudience, trustedAudienceArray); 147 | } 148 | 149 | oidcAgentConfig.setConsumerKey(consumerKey); 150 | oidcAgentConfig.setConsumerSecret(consumerSecret); 151 | oidcAgentConfig.setIndexPage(indexPage); 152 | oidcAgentConfig.setErrorPage(errorPage); 153 | oidcAgentConfig.setHomePage(homePage); 154 | oidcAgentConfig.setLogoutURL(logoutURL); 155 | oidcAgentConfig.setIssuer(issuer); 156 | oidcAgentConfig.setSkipURIs(skipURIs); 157 | oidcAgentConfig.setTrustedAudience(trustedAudience); 158 | oidcAgentConfig.setSignatureAlgorithm(jwsAlgorithm); 159 | } 160 | 161 | private int resolveConnectionConfig(Properties properties, String fileConfig, int defaultConfig) 162 | throws NumberFormatException { 163 | 164 | return StringUtils.isNotBlank(properties.getProperty(fileConfig)) ? 165 | Integer.parseInt(properties.getProperty(fileConfig)) : defaultConfig; 166 | } 167 | 168 | /** 169 | * {@inheritDoc} 170 | */ 171 | public OIDCAgentConfig getOidcAgentConfig() { 172 | 173 | return oidcAgentConfig; 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 21 | org.wso2 22 | wso2 23 | 1.4 24 | 25 | 26 | io.asgardeo.java.oidc.sdk 27 | 4.0.0 28 | java-oidc-sdk 29 | 0.1.31-SNAPSHOT 30 | pom 31 | Asgardeo - Java OIDC SDK Parent Module 32 | 33 | Asgardeo JAVA SDK for OIDC 34 | 35 | http://asgardeo.io 36 | 37 | 38 | https://github.com/asgardeo/asgardeo-java-oidc-sdk.git 39 | scm:git:https://github.com/asgardeo/asgardeo-java-oidc-sdk.git 40 | scm:git:https://github.com/asgardeo/asgardeo-java-oidc-sdk.git 41 | HEAD 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | commons-lang.wso2 50 | commons-lang 51 | ${commons-lang.wso2.version} 52 | 53 | 54 | javax.servlet 55 | javax.servlet-api 56 | ${javax.servlet-api.version} 57 | 58 | 59 | com.nimbusds 60 | nimbus-jose-jwt 61 | ${nimbus-jose-jwt.version} 62 | 63 | 64 | com.nimbusds 65 | oauth2-oidc-sdk 66 | ${nimbusds-oauth2-oidc-sdk.version} 67 | 68 | 69 | 70 | org.apache.logging.log4j 71 | log4j-api 72 | ${log4j.version} 73 | 74 | 75 | org.apache.logging.log4j 76 | log4j-core 77 | ${log4j.version} 78 | 79 | 80 | org.wso2.apache.httpcomponents 81 | httpclient 82 | ${httpcomponents-apache.wso2.version} 83 | 84 | 85 | 86 | org.testng 87 | testng 88 | ${testng.version} 89 | test 90 | 91 | 92 | org.powermock 93 | powermock-module-testng 94 | ${org.powermock.version} 95 | test 96 | 97 | 98 | org.mockito 99 | mockito-core 100 | ${mockito.version} 101 | test 102 | 103 | 104 | org.mockito 105 | mockito-inline 106 | ${mockito.version} 107 | test 108 | 109 | 110 | org.powermock 111 | powermock-api-mockito2 112 | ${mockito.api.version} 113 | test 114 | 115 | 116 | org.wiremock 117 | wiremock 118 | ${wiremock.version} 119 | test 120 | 121 | 122 | org.eclipse.jetty 123 | jetty-server 124 | ${eclipse.jetty.version} 125 | test 126 | 127 | 128 | org.eclipse.jetty 129 | jetty-servlet 130 | ${eclipse.jetty.version} 131 | test 132 | 133 | 134 | org.eclipse.jetty 135 | jetty-util 136 | ${eclipse.jetty.version} 137 | test 138 | 139 | 140 | org.jacoco 141 | jacoco-maven-plugin 142 | ${jacoco.version} 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | org.codehaus.mojo 152 | buildnumber-maven-plugin 153 | ${maven.buildnumber.plugin.version} 154 | 155 | 156 | validate 157 | 158 | create 159 | 160 | 161 | 162 | 163 | false 164 | false 165 | 166 | 167 | 168 | org.jacoco 169 | jacoco-maven-plugin 170 | ${jacoco.version} 171 | 172 | 173 | 174 | prepare-agent 175 | 176 | 177 | 178 | report 179 | test 180 | 181 | report 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | org.apache.maven.plugins 191 | maven-release-plugin 192 | 193 | clean install 194 | true 195 | 196 | 197 | 198 | org.apache.maven.plugins 199 | maven-deploy-plugin 200 | 201 | 202 | maven-compiler-plugin 203 | 2.3.1 204 | true 205 | 206 | UTF-8 207 | 1.8 208 | 1.8 209 | 210 | 211 | 212 | org.codehaus.mojo 213 | buildnumber-maven-plugin 214 | 215 | 216 | org.apache.maven.plugins 217 | maven-javadoc-plugin 218 | 219 | 1.8 220 | 221 | 222 | 223 | attach-javadocs 224 | 225 | jar 226 | 227 | 228 | 229 | none 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 2.6.0.wso2v1 239 | 3.0.1 240 | 9.37.2 241 | 9.43.3 242 | 4.3.1.wso2v1 243 | 1.4 244 | 2.17.1 245 | 7.10.2 246 | 2.0.7 247 | 3.5.13 248 | 2.0.7 249 | 3.8.0 250 | 11.0.22 251 | 252 | 0.8.12 253 | 254 | 255 | 256 | io.asgardeo.java.oidc.sdk 257 | 258 | 259 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Asgardeo OIDC 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-oidc-sdk%2F&style=flat)](https://wso2.org/jenkins/job/asgardeo/job/asgardeo-java-oidc-sdk/) 4 | [![FOSSA Status](https://app.fossa.com/api/projects/custom%2B28356%2Fgithub.com%2Fasgardeo%2Fasgardeo-java-oidc-sdk.svg?type=shield&issueType=license)](https://app.fossa.com/projects/custom%2B28356%2Fgithub.com%2Fasgardeo%2Fasgardeo-java-oidc-sdk?ref=badge_shield) 5 | [![FOSSA Status](https://app.fossa.com/api/projects/custom%2B28356%2Fgithub.com%2Fasgardeo%2Fasgardeo-java-oidc-sdk.svg?type=shield&issueType=security)](https://app.fossa.com/projects/custom%2B28356%2Fgithub.com%2Fasgardeo%2Fasgardeo-java-oidc-sdk?ref=badge_shield) 6 | [![Stackoverflow](https://img.shields.io/badge/Ask%20for%20help%20on-Stackoverflow-orange)](https://stackoverflow.com/questions/tagged/asgardeo) 7 | [![Join the chat at https://discord.gg/wso2](https://img.shields.io/badge/Join%20us%20on-Discord-%23e01563.svg)](https://discord.gg/wso2) 8 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/asgardeo/asgardeo-java-oidc-sdk/blob/master/LICENSE) 9 | [![Twitter](https://img.shields.io/twitter/follow/wso2.svg?style=social&label=Follow)](https://twitter.com/intent/follow?screen_name=asgardeo) 10 | --- 11 | 12 | The Asgardeo OIDC SDK for Java enables software developers to integrate OIDC based SSO authentication with Java Web 13 | applications. The SDK is built on top of the NimbusDS OAuth 2.0 SDK with OpenID Connection extensions library which 14 | allows Java developers to develop cross-domain single sign-on and federated access control solutions with minimum 15 | hassle. 16 | 17 | ## Getting Started 18 | 19 | You can experience the end-to-end capabilities of Asgardeo Java OIDC SDK by trying out the sample application 20 | featured in [Asgardeo OIDC tomcat agent getting started guide](https://github.com/asgardeo/asgardeo-tomcat-oidc-agent#getting-started). 21 | 22 | In this section, we would be looking at how you can embed the Asgardeo Java OIDC SDK to your existing Java web app. 23 | 24 | ### Table of Contents 25 | - [Initializing the SDK](#initializing-the-sdk) 26 | * [Maven dependency](#maven-dependency) 27 | * [Configuration file](#adding-the-configuration-properties) 28 | * [OIDC Manager](#oidc-manager) 29 | - [Login](#login) 30 | - [Handle Callback response](#handle-callback-response) 31 | - [Logout](#logout) 32 | - [Request Resolving](#request-resolving) 33 | 34 | ### Initializing the SDK 35 | This section covers the preliminary steps needed for getting the SDK ready to be used in your java webapp. 36 | 37 | #### Maven dependency 38 | You can add the Asgardeo Java OIDC SDK to your java project by installing it as a maven dependency: 39 | 40 | ```xml 41 | 42 | io.asgardeo.java.oidc.sdk 43 | io.asgardeo.java.oidc.sdk 44 | 0.1.30 45 | 46 | ``` 47 | #### Adding the configuration properties 48 | You need to add the configuration properties which provide the set of required parameters specific to the OIDC flows as 49 | described by the [OIDC Agent configuration catalog](https://github.com/asgardeo/asgardeo-tomcat-oidc-agent/blob/master/io.asgardeo.tomcat.oidc.sample/src/main/resources/configuration-catalog.md). For a sample configuration 50 | properties file, please refer to the one provided with the sample application in Asgardeo OIDC Tomcat Agent [here](https://github.com/asgardeo/asgardeo-tomcat-oidc-agent/blob/master/io.asgardeo.tomcat.oidc.sample/src/main/resources/oidc-sample-app.properties). 51 | 52 | You can use the default `FileBasedOIDCConfigProvider` for using file-based configurations. Or else, you have the 53 | freedom to implement your own custom configuration provider by implementing the interface, `OIDCConfigProvider`. 54 | 55 | For using the default `FileBasedOIDCConfigProvider`, you can use the following snippet. 56 | 57 | // public FileBasedOIDCConfigProvider(InputStream fileInputStream) 58 | 59 | ```java 60 | File configFile = new File("path/to/config/file"); 61 | InputStream configStream = new FileInputStream(configFile); 62 | OIDCConfigProvider configProvider = new FileBasedOIDCConfigProvider(configStream); 63 | ``` 64 | Now, the next step would be to create an `OIDCManager` instance which would provide you with the basic actions you 65 | want to perform in securing your Java webapp with OpenID Connect. 66 | 67 | #### OIDC Manager 68 | 69 | The OIDCManager interface provides a set of APIs which you can use to initiate a login flow, initiate a logout flow 70 | , and handle the callback responses from the OpenID Provider. For using these APIs, you only would need a single 71 | instance of a `OIDCManager` implementation. By default, Asgardeo Java OIDC SDK provides the `DefaultOIDCManger 72 | ` which is an implementation of the OIDCManager interface. 73 | 74 | For users who opt to use HTTP-session-based storage, the SDK provides an HTTP-session-based wrapper out of the box 75 | which adds HTTP session specific storing mechanisms on top of the `DefaultOIDCManager`. 76 | 77 | If you opt to use a different session storing system, you have the flexibility to write your own implementation of 78 | the `OIDCManager` interface and integrate it with your webapp. 79 | For this tutorial, we will be using the `HTTPSessionBasedOIDCProcessor` which is provided out of the box. 80 | The constructor for the `HTTPSessionBasedOIDCProcessor` takes in `OIDCAgentConfig` type object. 81 | 82 | public HTTPSessionBasedOIDCProcessor(OIDCAgentConfig oidcAgentConfig); 83 | 84 | This can be obtained by the OIDCConfigProvider instance we created earlier. Add the following code snippet to 85 | create the `HTTPSessionBasedOIDCProcessor` instance. 86 | 87 | OIDCAgentConfig config = configProvider.getOidcAgentConfig(); 88 | HTTPSessionBasedOIDCProcessor oidcManager = new HTTPSessionBasedOIDCProcessor(config); 89 | 90 | After creating one instance at the start, you can re-use the instance for sending every request and handling the 91 | responses. 92 | The `HTTPSessionBasedOIDCProcessor` provides you with the following APIs which can be used to initiate requests 93 | and handle responses. 94 | 95 | 1. `sendForLogin(HttpServletRequest request, HttpServletResponse response)` 96 | 97 | 2. `handleOIDCCallback(HttpServletRequest request, HttpServletResponse response, RequestContext requestContext)` 98 | 99 | 3. `logout(HttpServletRequest request, HttpServletResponse response)` 100 | 101 | In the following sections, we would look into these APIs in detail with the possible scenarios in which these can be 102 | used. 103 | 104 | ### Login 105 | ```java 106 | oidcmanager.sendForLogin(request, response); 107 | ``` 108 | 109 | The following are the parameters to the API. 110 | 111 | _request_ : Incoming `HttpServletRequest`. 112 | 113 | _response_ : Outgoing `HttpServletResponse`. 114 | 115 | This method can be used to send the user for authentication. The API would build an authentication request and 116 | redirect the user for authentication. Relevant information regarding the authentication session would be written to 117 | the http session. 118 | 119 | 120 | ### Handle Callback Response 121 | 122 | ```java 123 | oidcManager.handleOIDCCallback(request, response, requestContext); 124 | ``` 125 | 126 | The following are the parameters to the API. 127 | 128 | _request_ : Incoming `HttpServletRequest`. 129 | 130 | _response_ : Outgoing `HttpServletResponse`. 131 | 132 | _requestContext_ : `RequestContext` object containing the authentication request related information. 133 | 134 | This method should be used to process the OIDC callback response. It would obtain access tokens and refresh 135 | tokens, validate the ID token issued by the OpenID Provider, and redirect the user to secured pages. 136 | 137 | ### Logout 138 | 139 | ```java 140 | oidcManager.logout(request, response); 141 | ``` 142 | 143 | The following are the parameters to the API. 144 | 145 | _request_ : Incoming `HttpServletRequest`. 146 | 147 | _response_ : Outgoing `HttpServletResponse`. 148 | 149 | This method can be used to logout the user from the session. The API would build a logout request and 150 | log out the user from the authenticated session at the OpenID Provider. 151 | 152 | ### Request Resolving 153 | 154 | Asgardeo Java OIDC SDK provides utils to process the incoming HTTP requests and resolve them to be certain types 155 | . You can determine whether a request is a callback response, a logout request, an error request, etc. by using the 156 | provided `OIDCRequestResover` in places where the webapp is intercepting HTTP requests. 157 | 158 | You can create a `OIDCRequestResolver` instance with the following snippet. 159 | 160 | ```java 161 | OIDCRequestResolver requestResolver = new OIDCRequestResolver(request, oidcAgentConfig); 162 | ``` 163 | The following are the parameters. 164 | 165 | _oidcAgentConfig_ : `OIDCAgentConfig` object which can be obtained through the `OIDCConfigProvider` implementation as 166 | previously shown. 167 | 168 | _response_ : Outgoing `HttpServletResponse`. 169 | 170 | The provided util methods are as follows: 171 | 172 | | Method | Description | Returns | 173 | | ------------- |------------- | ------------ | 174 | |isCallbackResponse()|Checks if the request is a callback response. | boolean | 175 | |isLogoutURL()|Checks if the request is a logout request. | boolean | 176 | |isSkipURI()|Checks if the request is a URI to skip. | boolean | 177 | |isAuthorizationCodeResponse()|Checks if the request is an Authorization Code response. | boolean | 178 | |isError()|Checks if the request contains a parameter, "error". | boolean | 179 | 180 | 181 | ### Github 182 | The SDK is hosted on github. You can download it from: 183 | - Latest release: https://github.com/asgardeo/asgardeo-java-oidc-sdk/releases/latest 184 | - Master repo: https://github.com/asgardeo/asgardeo-java-oidc-sdk/tree/master/ 185 | 186 | ### Building from the source 187 | 188 | If you want to build **asgardeo-java-oidc-sdk** from the source code: 189 | 190 | 1. Install Java 8 191 | 2. Install Apache Maven 3.x.x (https://maven.apache.org/download.cgi#) 192 | 3. Get a clone or download the source from this repository (https://github.com/asgardeo/asgardeo-java-oidc-sdk.git) 193 | 4. Run the Maven command ``mvn clean install`` from the ``asgardeo-java-oidc-sdk`` directory. 194 | 195 | ## Contributing 196 | 197 | Please read [Contributing to the Code Base](http://wso2.github.io/) for details on our code of conduct, and the 198 | process for submitting pull requests to us. 199 | 200 | ### Reporting Issues 201 | We encourage you to report issues, improvements, and feature requests creating [Git Issues](https://github.com/asgardeo/asgardeo-java-oidc-sdk/issues). 202 | 203 | Important: Please be advised that security issues must be reported to security@wso2.com, not as GitHub issues, 204 | in order to reach the proper audience. We strongly advise following the WSO2 Security Vulnerability Reporting Guidelines 205 | when reporting the security issues. 206 | 207 | ## Versioning 208 | 209 | For the versions available, see the [tags on this repository](https://github.com/asgardeo/asgardeo-java-oidc-sdk/tags). 210 | 211 | ## License 212 | 213 | This project is licensed under the Apache License 2.0 under which WSO2 Carbon is distributed. See the [LICENSE 214 | ](LICENSE) file for details. 215 | 216 | -------------------------------------------------------------------------------- /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.oidc.sdk/src/test/java/io/asgardeo/java/oidc/sdk/DefaultOIDCManagerTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2020-2024, WSO2 LLC. (https://www.wso2.com). 3 | * 4 | * WSO2 LLC. 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.oidc.sdk; 20 | 21 | import com.github.tomakehurst.wiremock.WireMockServer; 22 | import com.github.tomakehurst.wiremock.core.WireMockConfiguration; 23 | import com.nimbusds.jwt.JWT; 24 | import com.nimbusds.jwt.JWTParser; 25 | import com.nimbusds.oauth2.sdk.AccessTokenResponse; 26 | import com.nimbusds.oauth2.sdk.AuthorizationCode; 27 | import com.nimbusds.oauth2.sdk.AuthorizationResponse; 28 | import com.nimbusds.oauth2.sdk.AuthorizationSuccessResponse; 29 | import com.nimbusds.oauth2.sdk.Scope; 30 | import com.nimbusds.oauth2.sdk.TokenResponse; 31 | import com.nimbusds.oauth2.sdk.auth.Secret; 32 | import com.nimbusds.oauth2.sdk.http.HTTPRequest; 33 | import com.nimbusds.oauth2.sdk.http.HTTPResponse; 34 | import com.nimbusds.oauth2.sdk.http.ServletUtils; 35 | import com.nimbusds.oauth2.sdk.id.ClientID; 36 | import com.nimbusds.oauth2.sdk.id.Issuer; 37 | import com.nimbusds.oauth2.sdk.id.State; 38 | import com.nimbusds.oauth2.sdk.id.Subject; 39 | import com.nimbusds.oauth2.sdk.token.AccessToken; 40 | import com.nimbusds.oauth2.sdk.token.AccessTokenType; 41 | import com.nimbusds.oauth2.sdk.token.RefreshToken; 42 | import com.nimbusds.oauth2.sdk.token.Tokens; 43 | import com.nimbusds.openid.connect.sdk.Nonce; 44 | import com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet; 45 | import io.asgardeo.java.oidc.sdk.bean.RequestContext; 46 | import io.asgardeo.java.oidc.sdk.bean.SessionContext; 47 | import io.asgardeo.java.oidc.sdk.config.model.OIDCAgentConfig; 48 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentException; 49 | import io.asgardeo.java.oidc.sdk.request.OIDCRequestResolver; 50 | import io.asgardeo.java.oidc.sdk.validators.IDTokenValidator; 51 | import org.mockito.Mock; 52 | import org.mockito.MockedStatic; 53 | import org.mockito.Mockito; 54 | import org.powermock.api.mockito.PowerMockito; 55 | import org.powermock.core.classloader.annotations.PrepareForTest; 56 | import org.powermock.modules.testng.PowerMockTestCase; 57 | import org.testng.annotations.AfterMethod; 58 | import org.testng.annotations.BeforeMethod; 59 | import org.testng.annotations.Test; 60 | 61 | import java.net.URI; 62 | import java.net.URISyntaxException; 63 | import java.util.HashMap; 64 | import java.util.Map; 65 | 66 | import javax.servlet.http.HttpServletRequest; 67 | import javax.servlet.http.HttpServletResponse; 68 | import javax.servlet.http.HttpSession; 69 | 70 | import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; 71 | import static org.mockito.ArgumentMatchers.any; 72 | import static org.mockito.Mockito.mock; 73 | import static org.mockito.Mockito.mockStatic; 74 | import static org.mockito.Mockito.when; 75 | import static org.testng.Assert.assertEquals; 76 | 77 | @PrepareForTest({IDTokenValidator.class, IDTokenClaimsSet.class, 78 | com.nimbusds.openid.connect.sdk.validators.IDTokenValidator.class}) 79 | public class DefaultOIDCManagerTest extends PowerMockTestCase { 80 | 81 | @Mock 82 | HttpServletRequest request; 83 | 84 | @Mock 85 | HttpServletResponse response; 86 | 87 | @Mock 88 | OIDCRequestResolver requestResolver; 89 | 90 | @Mock 91 | SessionContext sessionContext; 92 | 93 | OIDCAgentConfig oidcAgentConfig = new OIDCAgentConfig(); 94 | private WireMockServer wireMockServer; 95 | private static int SERVER_PORT = 9441; 96 | 97 | @BeforeMethod 98 | public void setUp() throws Exception { 99 | 100 | wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().port(SERVER_PORT)); 101 | wireMockServer.start(); 102 | configureFor("localhost", SERVER_PORT); 103 | 104 | Issuer issuer = new Issuer("issuer"); 105 | ClientID clientID = new ClientID("sampleClientId"); 106 | Secret clientSecret = new Secret("sampleClientSecret"); 107 | URI callbackURI = new URI("http://localhost:9441/sampleCallbackURL"); 108 | URI tokenEPURI = new URI("http://localhost:9441/sampleTokenEP"); 109 | URI jwksURI = new URI("http://localhost:9441/jwksEP"); 110 | URI logoutEP = new URI("http://test/sampleLogoutEP"); 111 | Scope scope = new Scope("sampleScope1", "openid"); 112 | JWT idToken = JWTParser 113 | .parse("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwia" + 114 | "WF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"); 115 | 116 | request = mock(HttpServletRequest.class); 117 | response = mock(HttpServletResponse.class); 118 | requestResolver = mock(OIDCRequestResolver.class); 119 | sessionContext = mock(SessionContext.class); 120 | 121 | oidcAgentConfig.setConsumerKey(clientID); 122 | oidcAgentConfig.setConsumerSecret(clientSecret); 123 | oidcAgentConfig.setCallbackUrl(callbackURI); 124 | oidcAgentConfig.setTokenEndpoint(tokenEPURI); 125 | oidcAgentConfig.setLogoutEndpoint(logoutEP); 126 | oidcAgentConfig.setScope(scope); 127 | oidcAgentConfig.setIssuer(issuer); 128 | oidcAgentConfig.setJwksEndpoint(jwksURI); 129 | when(sessionContext.getIdToken()).thenReturn(idToken.getParsedString()); 130 | IDTokenClaimsSet claimsSet = mock(IDTokenClaimsSet.class); 131 | IDTokenValidator idTokenValidator = mock(IDTokenValidator.class); 132 | com.nimbusds.openid.connect.sdk.validators.IDTokenValidator validator = mock( 133 | com.nimbusds.openid.connect.sdk.validators.IDTokenValidator.class); 134 | PowerMockito.whenNew(IDTokenValidator.class).withAnyArguments().thenReturn(idTokenValidator); 135 | PowerMockito.whenNew(com.nimbusds.openid.connect.sdk.validators.IDTokenValidator.class).withAnyArguments() 136 | .thenReturn(validator); 137 | when(validator.validate(any(JWT.class), any(Nonce.class))).thenReturn(claimsSet); 138 | Mockito.when(idTokenValidator.validate(any(Nonce.class))).thenReturn(claimsSet); 139 | Mockito.when(claimsSet.getSubject()).thenReturn(new Subject("alex@carbon.super")); 140 | } 141 | 142 | @Test 143 | public void testHandleOIDCCallback() throws Exception { 144 | 145 | AccessToken accessToken = new AccessToken(AccessTokenType.BEARER, "sampleAccessToken") { 146 | @Override 147 | public String toAuthorizationHeader() { 148 | 149 | return null; 150 | } 151 | }; 152 | RefreshToken refreshToken = new RefreshToken("sampleRefreshToken"); 153 | Tokens tokens = new Tokens(accessToken, refreshToken); 154 | Map customParameters = new HashMap<>(); 155 | String parsedIdToken = "eyJ4NXQiOiJNell4TW1Ga09HWXdNV0kwWldObU5EY3hOR1l3WW1NNFpUQTNNV0kyTkRBelpHUXpOR00wWkdS" + 156 | "bE5qSmtPREZrWkRSaU9URmtNV0ZoTXpVMlpHVmxOZyIsImtpZCI6Ik16WXhNbUZrT0dZd01XSTBaV05tTkRjeE5HWXdZbU00WlR" + 157 | "BM01XSTJOREF6WkdRek5HTTBaR1JsTmpKa09ERmtaRFJpT1RGa01XRmhNelUyWkdWbE5nX1JTMjU2IiwiYWxnIjoiUlMyNTYifQ" + 158 | ".eyJhdF9oYXNoIjoiSEJOUlJOeTlaVy1CMXF3dFdLRkJEZyIsInN1YiI6ImFsZXhAY2FyYm9uLnN1cGVyIiwiY291bnRyeSI6Ik" + 159 | "xLIiwiYW1yIjpbIkJhc2ljQXV0aGVudGljYXRvciJdLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0NDNcL29hdXRoMlwvd" + 160 | "G9rZW4iLCJzaWQiOiJkYmJhNGNkMC0wNWRjLTQxN2QtYTcwYy1lOGNmYmNiNDlhMDMiLCJhdWQiOiJLRTRPWWVZX2dmWXd6UWJK" + 161 | "YTl0R2hqMWhaSk1hIiwiY19oYXNoIjoiWXhUQ25rZ2UtOG9PSWZ3RUpmS2tfdyIsIm5iZiI6MTYwMjIyNjA5MSwiYXpwIjoiS0U" + 162 | "0T1llWV9nZll3elFiSmE5dEdoajFoWkpNYSIsImV4cCI6MTYwMjIyOTY5MSwiaWF0IjoxNjAyMjI2MDkxLCJlbWFpbCI6ImFsZX" + 163 | "hAd3NvMi5jb20ifQ.pHwsQqn64tif2J6iYcRShK_85WO3aBuL7Pz8urcHErXjyh6zvroOqSWD9KbSxJPocyoIshdqWdAEhdURKL" + 164 | "tXiw-l73HlvnX4qJKYT71VKXMTC26Z8dlk4TgytXiskmj8OpAcem3czuEWTrTLVbYzIw71p9kx-5Xxb9WNvzBg1YpwGC8MK3dkW" + 165 | "TfmUsu6oncIvHyv-gbX3kJebgMserp"; 166 | JWT idToken = JWTParser.parse(parsedIdToken); 167 | customParameters.put(SSOAgentConstants.ID_TOKEN, parsedIdToken); 168 | 169 | when(requestResolver.isError()).thenReturn(false); 170 | when(requestResolver.isAuthorizationCodeResponse()).thenReturn(true); 171 | 172 | MockedStatic mockedAuthorizationResponse = mockStatic(AuthorizationResponse.class); 173 | MockedStatic mockedServletUtils = mockStatic(ServletUtils.class); 174 | MockedStatic mockedTokenResponse = mockStatic(TokenResponse.class); 175 | HTTPRequest httpRequest = mock(HTTPRequest.class); 176 | AuthorizationResponse authorizationResponse = mock(AuthorizationResponse.class); 177 | AuthorizationSuccessResponse successResponse = mock(AuthorizationSuccessResponse.class); 178 | AuthorizationCode authorizationCode = mock(AuthorizationCode.class); 179 | TokenResponse tokenResponse = mock(TokenResponse.class); 180 | AccessTokenResponse accessTokenResponse = mock(AccessTokenResponse.class); 181 | when(ServletUtils.createHTTPRequest(request)).thenReturn(httpRequest); 182 | when(AuthorizationResponse.parse(httpRequest)).thenReturn(authorizationResponse); 183 | when(authorizationResponse.indicatesSuccess()).thenReturn(true); 184 | when(authorizationResponse.toSuccessResponse()).thenReturn(successResponse); 185 | when(successResponse.getAuthorizationCode()).thenReturn(authorizationCode); 186 | when(TokenResponse.parse((HTTPResponse) any())).thenReturn(tokenResponse); 187 | when(tokenResponse.indicatesSuccess()).thenReturn(true); 188 | when(tokenResponse.toSuccessResponse()).thenReturn(accessTokenResponse); 189 | when(accessTokenResponse.getTokens()).thenReturn(tokens); 190 | when(accessTokenResponse.getCustomParameters()).thenReturn(customParameters); 191 | HttpSession session = mock(HttpSession.class); 192 | when(request.getSession(false)).thenReturn(session); 193 | when(session.getAttribute(SSOAgentConstants.NONCE)).thenReturn(new Nonce()); 194 | RequestContext requestContext = new RequestContext(new State("state"), new Nonce()); 195 | 196 | OIDCManager oidcManager = new DefaultOIDCManager(oidcAgentConfig); 197 | SessionContext sessionContext = oidcManager.handleOIDCCallback(request, response, requestContext); 198 | 199 | assertEquals(sessionContext.getAccessToken(), accessToken.toJSONString()); 200 | assertEquals(sessionContext.getRefreshToken(), refreshToken.getValue()); 201 | assertEquals(sessionContext.getIdToken(), parsedIdToken); 202 | assertEquals(sessionContext.getUser().getSubject(), "alex@carbon.super"); 203 | mockedAuthorizationResponse.close(); 204 | mockedServletUtils.close(); 205 | mockedTokenResponse.close(); 206 | } 207 | 208 | @Test 209 | public void testLogoutCallbackURI() throws SSOAgentException { 210 | 211 | oidcAgentConfig.setPostLogoutRedirectURI(null); 212 | OIDCManager oidcManager = new DefaultOIDCManager(oidcAgentConfig); 213 | oidcManager.logout(sessionContext, response); 214 | } 215 | 216 | @Test 217 | public void testLogoutRedirectURI() throws URISyntaxException, SSOAgentException { 218 | 219 | URI redirectionURI = new URI("http://test/sampleRedirectionURL"); 220 | oidcAgentConfig.setPostLogoutRedirectURI(redirectionURI); 221 | OIDCManager oidcManager = new DefaultOIDCManager(oidcAgentConfig); 222 | oidcManager.logout(sessionContext, response); 223 | } 224 | 225 | @AfterMethod 226 | public void tearDown() { 227 | 228 | wireMockServer.stop(); 229 | } 230 | } 231 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/test/java/io/asgardeo/java/oidc/sdk/validators/IDTokenValidatorTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2020-2024, WSO2 LLC. (https://www.wso2.com). 3 | * 4 | * WSO2 LLC. 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.oidc.sdk.validators; 20 | 21 | import com.github.tomakehurst.wiremock.WireMockServer; 22 | import com.github.tomakehurst.wiremock.core.WireMockConfiguration; 23 | import com.nimbusds.jose.JOSEException; 24 | import com.nimbusds.jose.JWSAlgorithm; 25 | import com.nimbusds.jose.JWSHeader; 26 | import com.nimbusds.jose.JWSSigner; 27 | import com.nimbusds.jose.crypto.ECDSASigner; 28 | import com.nimbusds.jose.crypto.RSASSASigner; 29 | import com.nimbusds.jose.jwk.Curve; 30 | import com.nimbusds.jose.jwk.ECKey; 31 | import com.nimbusds.jose.jwk.JWK; 32 | import com.nimbusds.jose.jwk.JWKSet; 33 | import com.nimbusds.jose.jwk.RSAKey; 34 | import com.nimbusds.jwt.JWTClaimsSet; 35 | import com.nimbusds.jwt.SignedJWT; 36 | import com.nimbusds.oauth2.sdk.auth.Secret; 37 | import com.nimbusds.oauth2.sdk.id.Audience; 38 | import com.nimbusds.oauth2.sdk.id.ClientID; 39 | import com.nimbusds.oauth2.sdk.id.Issuer; 40 | import com.nimbusds.openid.connect.sdk.Nonce; 41 | import com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet; 42 | import io.asgardeo.java.oidc.sdk.config.model.OIDCAgentConfig; 43 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentServerException; 44 | import org.testng.annotations.AfterMethod; 45 | import org.testng.annotations.BeforeMethod; 46 | import org.testng.annotations.DataProvider; 47 | import org.testng.annotations.Test; 48 | 49 | import java.net.URL; 50 | import java.security.KeyPair; 51 | import java.security.KeyPairGenerator; 52 | import java.security.NoSuchAlgorithmException; 53 | import java.security.interfaces.ECPrivateKey; 54 | import java.security.interfaces.ECPublicKey; 55 | import java.security.interfaces.RSAPrivateKey; 56 | import java.security.interfaces.RSAPublicKey; 57 | import java.security.spec.ECParameterSpec; 58 | import java.util.Arrays; 59 | import java.util.Collections; 60 | import java.util.Date; 61 | import java.util.HashSet; 62 | import java.util.List; 63 | import java.util.Set; 64 | 65 | import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; 66 | import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; 67 | import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; 68 | import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; 69 | import static com.github.tomakehurst.wiremock.client.WireMock.get; 70 | import static org.testng.Assert.assertEquals; 71 | import static org.testng.Assert.assertTrue; 72 | 73 | public class IDTokenValidatorTest { 74 | 75 | private static int SERVER_PORT = 8099; 76 | private OIDCAgentConfig config; 77 | private RSAKey key; 78 | private WireMockServer wireMockServer; 79 | private JWKSet jwkSet; 80 | 81 | @BeforeMethod 82 | public void setUp() throws Exception { 83 | 84 | config = new OIDCAgentConfig(); 85 | jwkSet = generateJWKS(); 86 | key = (RSAKey) jwkSet.getKeys().get(0); 87 | 88 | Issuer issuer = new Issuer("issuer"); 89 | ClientID clientID = new ClientID("sampleClientId"); 90 | Secret clientSecret = new Secret("sampleClientSecret"); 91 | URL jwkSetURL = new URL("http://localhost:" + SERVER_PORT + "/jwksEP"); 92 | 93 | config.setIssuer(issuer); 94 | config.setConsumerKey(clientID); 95 | config.setConsumerSecret(clientSecret); 96 | config.setJwksEndpoint(jwkSetURL.toURI()); 97 | 98 | initWireMockServer(); 99 | } 100 | 101 | private void initWireMockServer() { 102 | 103 | if (wireMockServer != null && wireMockServer.isRunning()) { 104 | wireMockServer.stop(); 105 | } 106 | wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().port(SERVER_PORT)); 107 | wireMockServer.start(); 108 | configureFor("localhost", SERVER_PORT); 109 | 110 | stubFor(get(urlMatching("/jwksEP")) 111 | .willReturn(aResponse() 112 | .withStatus(200) 113 | .withHeader("Content-Type", "application/json") 114 | .withBody(jwkSet.toString(true)))); 115 | } 116 | 117 | private JWKSet generateJWKS() throws NoSuchAlgorithmException { 118 | 119 | KeyPairGenerator pairGen = KeyPairGenerator.getInstance("RSA"); 120 | pairGen.initialize(2048); 121 | KeyPair keyPair = pairGen.generateKeyPair(); 122 | 123 | RSAKey rsaJWK1 = new RSAKey.Builder((RSAPublicKey) keyPair.getPublic()) 124 | .privateKey((RSAPrivateKey) keyPair.getPrivate()) 125 | .keyID("1") 126 | .build(); 127 | 128 | keyPair = pairGen.generateKeyPair(); 129 | 130 | RSAKey rsaJWK2 = new RSAKey.Builder((RSAPublicKey) keyPair.getPublic()) 131 | .privateKey((RSAPrivateKey) keyPair.getPrivate()) 132 | .keyID("2") 133 | .build(); 134 | 135 | JWKSet jwkSet = new JWKSet(Arrays.asList((JWK) rsaJWK1, (JWK) rsaJWK2)); 136 | return jwkSet; 137 | } 138 | 139 | private com.nimbusds.jose.jwk.ECKey generateECJWK(final Curve curve) throws Exception { 140 | 141 | ECParameterSpec ecParameterSpec = curve.toECParameterSpec(); 142 | 143 | KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); 144 | generator.initialize(ecParameterSpec); 145 | KeyPair keyPair = generator.generateKeyPair(); 146 | 147 | return new com.nimbusds.jose.jwk.ECKey.Builder(curve, (ECPublicKey) keyPair.getPublic()). 148 | privateKey((ECPrivateKey) keyPair.getPrivate()). 149 | build(); 150 | } 151 | 152 | @DataProvider(name = "IssuerData") 153 | public Object[][] issuerData() { 154 | 155 | Issuer issuer1 = new Issuer("issuer1"); 156 | Issuer issuer2 = new Issuer("issuer2"); 157 | 158 | return new Object[][]{ 159 | // issuer 160 | // expected 161 | {issuer1, "issuer1"}, 162 | {issuer2, "issuer2"} 163 | }; 164 | } 165 | 166 | @Test(dataProvider = "IssuerData") 167 | public void testIssuer(Issuer issuer, String expectedIssuer) throws SSOAgentServerException, JOSEException { 168 | 169 | config.setIssuer(issuer); 170 | Nonce nonce = new Nonce(); 171 | JWTClaimsSet claims = new JWTClaimsSet.Builder() 172 | .issuer(issuer.getValue()) 173 | .subject("alice") 174 | .audience(config.getConsumerKey().getValue()) 175 | .expirationTime(new Date()) 176 | .issueTime(new Date()) 177 | .claim("nonce", nonce.getValue()) 178 | .build(); 179 | 180 | SignedJWT idToken = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claims); 181 | JWSSigner signer = new RSASSASigner(key); 182 | idToken.sign(signer); 183 | 184 | IDTokenValidator validator = new IDTokenValidator(config, idToken); 185 | IDTokenClaimsSet claimsSet = validator.validate(nonce); 186 | assertEquals(claimsSet.getIssuer().getValue(), expectedIssuer); 187 | } 188 | 189 | @DataProvider(name = "AudienceData") 190 | public Object[][] audienceData() { 191 | 192 | String clientID1 = "clientID1"; 193 | List tokenAudience1 = Arrays.asList(clientID1); 194 | Set trustedAudience1 = new HashSet<>(tokenAudience1); 195 | trustedAudience1.add(clientID1); 196 | String azp1 = null; 197 | 198 | String clientID2 = "clientID2"; 199 | List tokenAudience2 = Arrays.asList("aud1", "aud2", "aud3", clientID2); 200 | Set trustedAudience2 = new HashSet<>(tokenAudience2); 201 | String azp2 = clientID2; 202 | 203 | return new Object[][]{ 204 | // token audience 205 | // trusted audience 206 | // client ID 207 | // AZP value 208 | {tokenAudience1, trustedAudience1, clientID1, azp1}, 209 | {tokenAudience2, trustedAudience2, clientID2, azp2} 210 | }; 211 | } 212 | 213 | @Test(dataProvider = "AudienceData") 214 | public void testAudience(List audience, Set trustedAudience, String clientID, String azpValue) 215 | throws SSOAgentServerException, JOSEException { 216 | 217 | Nonce nonce = new Nonce(); 218 | config.setTrustedAudience(trustedAudience); 219 | config.setConsumerKey(new ClientID(clientID)); 220 | JWTClaimsSet claims = new JWTClaimsSet.Builder() 221 | .issuer(config.getIssuer().getValue()) 222 | .subject("alice") 223 | .audience(audience) 224 | .expirationTime(new Date()) 225 | .issueTime(new Date()) 226 | .claim("nonce", nonce.getValue()) 227 | .claim("azp", azpValue) 228 | .build(); 229 | 230 | SignedJWT idToken = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claims); 231 | JWSSigner signer = new RSASSASigner(key); 232 | idToken.sign(signer); 233 | 234 | IDTokenValidator validator = new IDTokenValidator(config, idToken); 235 | IDTokenClaimsSet claimsSet = validator.validate(nonce); 236 | List audiences = claimsSet.getAudience(); 237 | audiences.forEach(aud -> assertTrue(trustedAudience.contains(aud.getValue()))); 238 | } 239 | 240 | @DataProvider(name = "AlgorithmData") 241 | public Object[][] algorithmData() throws Exception { 242 | 243 | KeyPairGenerator pairGenRSA = KeyPairGenerator.getInstance("RSA"); 244 | pairGenRSA.initialize(2048); 245 | KeyPair keyPairRSA = pairGenRSA.generateKeyPair(); 246 | 247 | RSAKey rsaJWK = new RSAKey.Builder((RSAPublicKey) keyPairRSA.getPublic()) 248 | .privateKey((RSAPrivateKey) keyPairRSA.getPrivate()) 249 | .keyID("1") 250 | .build(); 251 | 252 | ECKey ecJWK = generateECJWK(Curve.P_256); 253 | 254 | return new Object[][]{ 255 | // algorithm 256 | // key 257 | {"RS256", (JWK) rsaJWK}, 258 | {"ES256", (JWK) ecJWK} 259 | }; 260 | } 261 | 262 | @Test(dataProvider = "AlgorithmData") 263 | public void testJWSAlgorithm(String signatureAlgorithm, JWK key) throws JOSEException, SSOAgentServerException { 264 | 265 | jwkSet = new JWKSet(Collections.singletonList(key)); 266 | // Reinitialize the mock server to add jwkSet. 267 | initWireMockServer(); 268 | 269 | Nonce nonce = new Nonce(); 270 | JWSAlgorithm jwsAlgorithm = new JWSAlgorithm(signatureAlgorithm); 271 | config.setSignatureAlgorithm(jwsAlgorithm); 272 | JWTClaimsSet claims = new JWTClaimsSet.Builder() 273 | .issuer(config.getIssuer().getValue()) 274 | .subject("alice") 275 | .audience(config.getConsumerKey().getValue()) 276 | .expirationTime(new Date()) 277 | .issueTime(new Date()) 278 | .claim("nonce", nonce.getValue()) 279 | .build(); 280 | 281 | SignedJWT idToken = new SignedJWT(new JWSHeader(jwsAlgorithm), claims); 282 | JWSSigner signer; 283 | if (key instanceof RSAKey) { 284 | signer = new RSASSASigner((RSAKey) key); 285 | } else { 286 | signer = new ECDSASigner((ECKey) key); 287 | } 288 | idToken.sign(signer); 289 | 290 | IDTokenValidator validator = new IDTokenValidator(config, idToken); 291 | IDTokenClaimsSet claimsSet = validator.validate(nonce); 292 | assertEquals(claimsSet.getNonce(), nonce); 293 | } 294 | 295 | @AfterMethod 296 | public void tearDown() { 297 | 298 | wireMockServer.stop(); 299 | } 300 | } 301 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/config/model/OIDCAgentConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk.config.model; 20 | 21 | import com.nimbusds.jose.JWSAlgorithm; 22 | import com.nimbusds.oauth2.sdk.Scope; 23 | import com.nimbusds.oauth2.sdk.auth.Secret; 24 | import com.nimbusds.oauth2.sdk.id.ClientID; 25 | import com.nimbusds.oauth2.sdk.id.Issuer; 26 | 27 | import java.net.URI; 28 | import java.util.HashSet; 29 | import java.util.Map; 30 | import java.util.Set; 31 | 32 | /** 33 | * A data model class to define the OIDC Agent Config element. 34 | */ 35 | public class OIDCAgentConfig { 36 | 37 | private ClientID consumerKey; 38 | private Secret consumerSecret; 39 | private String indexPage; 40 | private String errorPage; 41 | private String homePage; 42 | private String logoutURL; 43 | private URI callbackUrl; 44 | private Scope scope; 45 | private URI authorizeEndpoint; 46 | private URI logoutEndpoint; 47 | private URI tokenEndpoint; 48 | private Issuer issuer; 49 | private Set trustedAudience; 50 | private URI jwksEndpoint; 51 | private URI postLogoutRedirectURI; 52 | private JWSAlgorithm signatureAlgorithm; 53 | private Set skipURIs = new HashSet(); 54 | private int httpConnectTimeout; 55 | private int httpReadTimeout; 56 | private int httpSizeLimit; 57 | private String state; 58 | private Map additionalParamsForAuthorizeEndpoint; 59 | 60 | /** 61 | * Returns the consumer key (Client ID) of the OIDC agent. 62 | * 63 | * @return {@link ClientID} of the OIDC agent. 64 | */ 65 | public ClientID getConsumerKey() { 66 | 67 | return consumerKey; 68 | } 69 | 70 | /** 71 | * Sets the consumer key (Client ID) for the OIDC agent. 72 | * 73 | * @param consumerKey The consumer key of the OIDC agent. 74 | */ 75 | public void setConsumerKey(ClientID consumerKey) { 76 | 77 | this.consumerKey = consumerKey; 78 | } 79 | 80 | /** 81 | * Returns the consumer secret (Client secret) of the OIDC agent. 82 | * 83 | * @return {@link Secret} of the OIDC agent. 84 | */ 85 | public Secret getConsumerSecret() { 86 | 87 | return consumerSecret; 88 | } 89 | 90 | /** 91 | * Sets the consumer secret (Client secret) for the OIDC agent. 92 | * 93 | * @param consumerSecret The consumer secret of the OIDC agent. 94 | */ 95 | public void setConsumerSecret(Secret consumerSecret) { 96 | 97 | this.consumerSecret = consumerSecret; 98 | } 99 | 100 | /** 101 | * Returns the index page of the OIDC agent. 102 | * 103 | * @return Index page of the OIDC agent. 104 | */ 105 | public String getIndexPage() { 106 | 107 | return indexPage; 108 | } 109 | 110 | /** 111 | * Sets the index page for the OIDC agent. 112 | * 113 | * @param indexPage The index page of the OIDC agent. 114 | */ 115 | public void setIndexPage(String indexPage) { 116 | 117 | this.indexPage = indexPage; 118 | } 119 | 120 | /** 121 | * Returns the error page of the OIDC agent. 122 | * 123 | * @return Error page of the OIDC agent. 124 | */ 125 | public String getErrorPage() { 126 | 127 | return errorPage; 128 | } 129 | 130 | /** 131 | * Sets the error page for the OIDC agent. 132 | * 133 | * @param errorPage The error page of the OIDC agent. 134 | */ 135 | public void setErrorPage(String errorPage) { 136 | 137 | this.errorPage = errorPage; 138 | } 139 | 140 | /** 141 | * Returns the home page of the OIDC agent. 142 | * 143 | * @return Home page of the OIDC agent. 144 | */ 145 | public String getHomePage() { 146 | 147 | return homePage; 148 | } 149 | 150 | /** 151 | * Sets the home page for the OIDC agent. 152 | * 153 | * @param homePage The home page of the OIDC agent. 154 | */ 155 | public void setHomePage(String homePage) { 156 | 157 | this.homePage = homePage; 158 | } 159 | 160 | /** 161 | * Returns the logout URL of the OIDC agent. 162 | * 163 | * @return Logout URL of the OIDC agent. 164 | */ 165 | public String getLogoutURL() { 166 | 167 | return logoutURL; 168 | } 169 | 170 | /** 171 | * Sets the logout URL for the OIDC agent. 172 | * 173 | * @param logoutURL The logout URL of the OIDC agent. 174 | */ 175 | public void setLogoutURL(String logoutURL) { 176 | 177 | this.logoutURL = logoutURL; 178 | } 179 | 180 | /** 181 | * Returns the callback URI of the OIDC agent. 182 | * 183 | * @return Callback URI of the OIDC agent. 184 | */ 185 | public URI getCallbackUrl() { 186 | 187 | return callbackUrl; 188 | } 189 | 190 | /** 191 | * Sets the callback URL for the OIDC agent. 192 | * 193 | * @param callbackUrl The callback URL of the OIDC agent. 194 | */ 195 | public void setCallbackUrl(URI callbackUrl) { 196 | 197 | this.callbackUrl = callbackUrl; 198 | } 199 | 200 | /** 201 | * Returns the cscope of the OIDC agent. 202 | * 203 | * @return {@link Scope} of the OIDC agent. 204 | */ 205 | public Scope getScope() { 206 | 207 | return scope; 208 | } 209 | 210 | /** 211 | * Sets the scope for the OIDC agent. 212 | * 213 | * @param scope The scope of the OIDC agent. 214 | */ 215 | public void setScope(Scope scope) { 216 | 217 | this.scope = scope; 218 | } 219 | 220 | /** 221 | * Returns the authorize endpoint URI of the OIDC agent. 222 | * 223 | * @return The authorize endpoint URI of the OIDC agent. 224 | */ 225 | public URI getAuthorizeEndpoint() { 226 | 227 | return authorizeEndpoint; 228 | } 229 | 230 | /** 231 | * Sets the authorize endpoint URL for the OIDC agent. 232 | * 233 | * @param authorizeEndpoint The authorize endpoint URL of the OIDC agent. 234 | */ 235 | public void setAuthorizeEndpoint(URI authorizeEndpoint) { 236 | 237 | this.authorizeEndpoint = authorizeEndpoint; 238 | } 239 | 240 | /** 241 | * Returns the logout endpoint URI of the OIDC agent. 242 | * 243 | * @return The logout endpoint URI of the OIDC agent. 244 | */ 245 | public URI getLogoutEndpoint() { 246 | 247 | return logoutEndpoint; 248 | } 249 | 250 | /** 251 | * Sets the logout endpoint URL for the OIDC agent. 252 | * 253 | * @param logoutEndpoint The logout endpoint URL of the OIDC agent. 254 | */ 255 | public void setLogoutEndpoint(URI logoutEndpoint) { 256 | 257 | this.logoutEndpoint = logoutEndpoint; 258 | } 259 | 260 | /** 261 | * Returns the the token endpoint URI of the OIDC agent. 262 | * 263 | * @return The token endpoint URI of the OIDC agent. 264 | */ 265 | public URI getTokenEndpoint() { 266 | 267 | return tokenEndpoint; 268 | } 269 | 270 | /** 271 | * Sets the token endpoint URL for the OIDC agent. 272 | * 273 | * @param tokenEndpoint The token endpoint URL of the OIDC agent. 274 | */ 275 | public void setTokenEndpoint(URI tokenEndpoint) { 276 | 277 | this.tokenEndpoint = tokenEndpoint; 278 | } 279 | 280 | /** 281 | * Returns the issuer of the OIDC agent. 282 | * 283 | * @return {@link Issuer} of the OIDC agent. 284 | */ 285 | public Issuer getIssuer() { 286 | 287 | return issuer; 288 | } 289 | 290 | /** 291 | * Sets the issuer for the OIDC agent. 292 | * 293 | * @param issuer The issuer of the OIDC agent. 294 | */ 295 | public void setIssuer(Issuer issuer) { 296 | 297 | this.issuer = issuer; 298 | } 299 | 300 | public Set getTrustedAudience() { 301 | 302 | return trustedAudience; 303 | } 304 | 305 | public void setTrustedAudience(Set trustedAudience) { 306 | 307 | this.trustedAudience = trustedAudience; 308 | } 309 | 310 | /** 311 | * Returns the JWKS endpoint URI of the OIDC agent. 312 | * 313 | * @return The JWKS endpoint URI of the OIDC agent. 314 | */ 315 | public URI getJwksEndpoint() { 316 | 317 | return jwksEndpoint; 318 | } 319 | 320 | /** 321 | * Sets the JWKS endpoint URL for the OIDC agent. 322 | * 323 | * @param jwksEndpoint The JWKS endpoint URL of the OIDC agent. 324 | */ 325 | public void setJwksEndpoint(URI jwksEndpoint) { 326 | 327 | this.jwksEndpoint = jwksEndpoint; 328 | } 329 | 330 | /** 331 | * Returns the post-logout redirect URI of the OIDC agent. 332 | * 333 | * @return The post-logout redirect URI of the OIDC agent. 334 | */ 335 | public URI getPostLogoutRedirectURI() { 336 | 337 | return postLogoutRedirectURI; 338 | } 339 | 340 | /** 341 | * Sets the post-logout redirect URL for the OIDC agent. 342 | * 343 | * @param postLogoutRedirectURI The post-logout redirect URL of the OIDC agent. 344 | */ 345 | public void setPostLogoutRedirectURI(URI postLogoutRedirectURI) { 346 | 347 | this.postLogoutRedirectURI = postLogoutRedirectURI; 348 | } 349 | 350 | public JWSAlgorithm getSignatureAlgorithm() { 351 | 352 | return signatureAlgorithm; 353 | } 354 | 355 | public void setSignatureAlgorithm(JWSAlgorithm signatureAlgorithm) { 356 | 357 | this.signatureAlgorithm = signatureAlgorithm; 358 | } 359 | 360 | /** 361 | * Returns the skip URIs of the OIDC agent. 362 | * 363 | * @return The skip URIs of the OIDC agent. 364 | */ 365 | public Set getSkipURIs() { 366 | 367 | return skipURIs; 368 | } 369 | 370 | /** 371 | * Sets the skip URIs for the OIDC agent. 372 | * 373 | * @param skipURIs The skip URIs of the OIDC agent. 374 | */ 375 | public void setSkipURIs(Set skipURIs) { 376 | 377 | this.skipURIs = skipURIs; 378 | } 379 | 380 | /** 381 | * Returns the HTTP connect timeout in milliseconds. 382 | * 383 | * @return HTTP connect timeout in milliseconds. 384 | */ 385 | public int getHttpConnectTimeout() { 386 | 387 | return httpConnectTimeout; 388 | } 389 | 390 | /** 391 | * Sets the HTTP connect timeout in milliseconds. 392 | * 393 | * @param httpConnectTimeout HTTP connect timeout in milliseconds. 394 | */ 395 | public void setHttpConnectTimeout(int httpConnectTimeout) { 396 | 397 | this.httpConnectTimeout = httpConnectTimeout; 398 | } 399 | 400 | /** 401 | * Returns the HTTP read timeout in milliseconds. 402 | * 403 | * @return HTTP read timeout in milliseconds. 404 | */ 405 | public int getHttpReadTimeout() { 406 | 407 | return httpReadTimeout; 408 | } 409 | 410 | /** 411 | * Sets the HTTP read timeout in milliseconds. 412 | * 413 | * @param httpReadTimeout HTTP read timeout in milliseconds. 414 | */ 415 | public void setHttpReadTimeout(int httpReadTimeout) { 416 | 417 | this.httpReadTimeout = httpReadTimeout; 418 | } 419 | 420 | /** 421 | * Returns the HTTP entity size limit in bytes. 422 | * 423 | * @return HTTP entity size limit in bytes. 424 | */ 425 | public int getHttpSizeLimit() { 426 | 427 | return httpSizeLimit; 428 | } 429 | 430 | /** 431 | * Sets the HTTP entity size limit in bytes. 432 | * 433 | * @param httpSizeLimit HTTP entity size limit in bytes. 434 | */ 435 | public void setHttpSizeLimit(int httpSizeLimit) { 436 | 437 | this.httpSizeLimit = httpSizeLimit; 438 | } 439 | 440 | /** 441 | * Returns the state parameter of the OIDC agent. 442 | * 443 | * @return The state parameter of the OIDC agent. 444 | */ 445 | public String getState() { 446 | 447 | return state; 448 | } 449 | 450 | /** 451 | * Sets the state parameter for the OIDC agent. 452 | * 453 | * @param state The state parameter for the OIDC agent. 454 | */ 455 | public void setState(String state) { 456 | 457 | this.state = state; 458 | } 459 | 460 | /** 461 | * Returns the additional query parameters of the OIDC agent. 462 | * 463 | * @return The additional query params of the OIDC agent. 464 | */ 465 | public Map getAdditionalParamsForAuthorizeEndpoint() { 466 | 467 | return additionalParamsForAuthorizeEndpoint; 468 | } 469 | 470 | /** 471 | * Sets the additional query params for the OIDC agent. 472 | * 473 | * @param additionalParamsForAuthorizeEndpoint The additional query params of the OIDC agent. 474 | */ 475 | public void setAdditionalParamsForAuthorizeEndpoint(Map additionalParamsForAuthorizeEndpoint) { 476 | 477 | this.additionalParamsForAuthorizeEndpoint = additionalParamsForAuthorizeEndpoint; 478 | } 479 | } 480 | -------------------------------------------------------------------------------- /io.asgardeo.java.oidc.sdk/src/main/java/io/asgardeo/java/oidc/sdk/DefaultOIDCManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020, 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.oidc.sdk; 20 | 21 | import com.nimbusds.jwt.JWT; 22 | import com.nimbusds.jwt.JWTClaimsSet; 23 | import com.nimbusds.jwt.JWTParser; 24 | import com.nimbusds.jwt.SignedJWT; 25 | import com.nimbusds.oauth2.sdk.AbstractRequest; 26 | import com.nimbusds.oauth2.sdk.AccessTokenResponse; 27 | import com.nimbusds.oauth2.sdk.AuthorizationCode; 28 | import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; 29 | import com.nimbusds.oauth2.sdk.AuthorizationErrorResponse; 30 | import com.nimbusds.oauth2.sdk.AuthorizationGrant; 31 | import com.nimbusds.oauth2.sdk.AuthorizationResponse; 32 | import com.nimbusds.oauth2.sdk.AuthorizationSuccessResponse; 33 | import com.nimbusds.oauth2.sdk.Scope; 34 | import com.nimbusds.oauth2.sdk.TokenErrorResponse; 35 | import com.nimbusds.oauth2.sdk.TokenRequest; 36 | import com.nimbusds.oauth2.sdk.TokenResponse; 37 | import com.nimbusds.oauth2.sdk.auth.ClientAuthentication; 38 | import com.nimbusds.oauth2.sdk.auth.ClientSecretBasic; 39 | import com.nimbusds.oauth2.sdk.auth.Secret; 40 | import com.nimbusds.oauth2.sdk.http.HTTPRequest; 41 | import com.nimbusds.oauth2.sdk.http.ServletUtils; 42 | import com.nimbusds.oauth2.sdk.id.ClientID; 43 | import com.nimbusds.oauth2.sdk.token.AccessToken; 44 | import com.nimbusds.oauth2.sdk.token.RefreshToken; 45 | import com.nimbusds.openid.connect.sdk.Nonce; 46 | import com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet; 47 | import io.asgardeo.java.oidc.sdk.bean.RequestContext; 48 | import io.asgardeo.java.oidc.sdk.bean.SessionContext; 49 | import io.asgardeo.java.oidc.sdk.bean.User; 50 | import io.asgardeo.java.oidc.sdk.config.model.OIDCAgentConfig; 51 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentClientException; 52 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentException; 53 | import io.asgardeo.java.oidc.sdk.exception.SSOAgentServerException; 54 | import io.asgardeo.java.oidc.sdk.request.OIDCRequestBuilder; 55 | import io.asgardeo.java.oidc.sdk.request.OIDCRequestResolver; 56 | import io.asgardeo.java.oidc.sdk.request.model.AuthenticationRequest; 57 | import io.asgardeo.java.oidc.sdk.request.model.LogoutRequest; 58 | import io.asgardeo.java.oidc.sdk.validators.IDTokenValidator; 59 | import net.minidev.json.JSONObject; 60 | import org.apache.commons.lang.StringUtils; 61 | import org.apache.logging.log4j.Level; 62 | import org.apache.logging.log4j.LogManager; 63 | import org.apache.logging.log4j.Logger; 64 | 65 | import java.io.IOException; 66 | import java.net.URI; 67 | import java.text.ParseException; 68 | import java.util.HashMap; 69 | import java.util.Map; 70 | 71 | import javax.servlet.http.HttpServletRequest; 72 | import javax.servlet.http.HttpServletResponse; 73 | 74 | /** 75 | * OIDC manager implementation. 76 | */ 77 | public class DefaultOIDCManager implements OIDCManager { 78 | 79 | private static final Logger logger = LogManager.getLogger(DefaultOIDCManager.class); 80 | 81 | private OIDCAgentConfig oidcAgentConfig; 82 | 83 | public DefaultOIDCManager(OIDCAgentConfig oidcAgentConfig) throws SSOAgentClientException { 84 | 85 | validateConfig(oidcAgentConfig); 86 | this.oidcAgentConfig = oidcAgentConfig; 87 | } 88 | 89 | /** 90 | * {@inheritDoc} 91 | */ 92 | @Override 93 | public RequestContext sendForLogin(HttpServletRequest request, HttpServletResponse response) 94 | throws SSOAgentException { 95 | 96 | OIDCRequestBuilder requestBuilder = new OIDCRequestBuilder(oidcAgentConfig); 97 | AuthenticationRequest authenticationRequest = requestBuilder.buildAuthenticationRequest(); 98 | 99 | try { 100 | response.sendRedirect(authenticationRequest.getAuthenticationRequestURI().toString()); 101 | } catch (IOException e) { 102 | throw new SSOAgentException(e.getMessage(), e); 103 | } 104 | return authenticationRequest.getRequestContext(); 105 | } 106 | 107 | /** 108 | * {@inheritDoc} 109 | */ 110 | @Override 111 | public SessionContext handleOIDCCallback(HttpServletRequest request, HttpServletResponse response, 112 | RequestContext requestContext) throws SSOAgentException { 113 | 114 | OIDCRequestResolver requestResolver = new OIDCRequestResolver(request, oidcAgentConfig); 115 | SessionContext sessionContext = new SessionContext(); 116 | Nonce nonce = requestContext.getNonce(); 117 | 118 | try { 119 | if (requestResolver.isAuthorizationCodeResponse()) { 120 | // Auth code is received. 121 | logger.log(Level.TRACE, "Handling the OIDC Authorization response."); 122 | boolean isAuthenticated = handleAuthentication(request, sessionContext, nonce); 123 | if (isAuthenticated) { 124 | logger.log(Level.TRACE, "Authentication successful. Redirecting to the target page."); 125 | return sessionContext; 126 | } 127 | } else if (requestResolver.isError()) { 128 | // Error occurred. 129 | if (StringUtils.isNotEmpty(request.getParameter(SSOAgentConstants.ERROR_DESCRIPTION))) { 130 | logger.log(Level.ERROR, "Authentication unsuccessful. Error description: " + 131 | request.getParameter(SSOAgentConstants.ERROR_DESCRIPTION)); 132 | throw new SSOAgentServerException(request.getParameter(SSOAgentConstants.ERROR_DESCRIPTION), 133 | SSOAgentConstants.ErrorMessages.AUTHENTICATION_FAILED.getCode()); 134 | } 135 | } else { 136 | // Successful logout. 137 | sessionContext.getAdditionalParams().put(SSOAgentConstants.IS_LOGOUT, true); 138 | return sessionContext; 139 | } 140 | logger.log(Level.ERROR, "Authentication unsuccessful. Clearing the active session and redirecting."); 141 | throw new SSOAgentServerException(SSOAgentConstants.ErrorMessages.AUTHENTICATION_FAILED.getMessage(), 142 | SSOAgentConstants.ErrorMessages.AUTHENTICATION_FAILED.getCode()); 143 | } catch (SSOAgentServerException e) { 144 | throw new SSOAgentException(e.getMessage(), e.getErrorCode()); 145 | } 146 | } 147 | 148 | /** 149 | * {@inheritDoc} 150 | */ 151 | @Override 152 | public RequestContext logout(SessionContext sessionContext, HttpServletResponse response) throws SSOAgentException { 153 | 154 | if (oidcAgentConfig.getPostLogoutRedirectURI() == null) { 155 | logger.info("postLogoutRedirectURI is not configured. Using the callbackURL instead."); 156 | URI callbackURI = oidcAgentConfig.getCallbackUrl(); 157 | oidcAgentConfig.setPostLogoutRedirectURI(callbackURI); 158 | } 159 | 160 | OIDCRequestBuilder requestBuilder = new OIDCRequestBuilder(oidcAgentConfig); 161 | LogoutRequest logoutRequest = requestBuilder.buildLogoutRequest(sessionContext); 162 | 163 | try { 164 | response.sendRedirect(logoutRequest.getLogoutRequestURI().toString()); 165 | } catch (IOException e) { 166 | throw new SSOAgentException(SSOAgentConstants.ErrorMessages.SERVLET_CONNECTION.getMessage(), 167 | SSOAgentConstants.ErrorMessages.SERVLET_CONNECTION.getCode(), e); 168 | } 169 | return logoutRequest.getRequestContext(); 170 | } 171 | 172 | private boolean handleAuthentication(final HttpServletRequest request, SessionContext authenticationInfo, 173 | Nonce nonce) throws SSOAgentServerException { 174 | 175 | AuthorizationResponse authorizationResponse; 176 | AuthorizationCode authorizationCode; 177 | AuthorizationSuccessResponse successResponse; 178 | TokenRequest tokenRequest; 179 | TokenResponse tokenResponse; 180 | 181 | try { 182 | authorizationResponse = AuthorizationResponse.parse(ServletUtils.createHTTPRequest(request)); 183 | 184 | if (!authorizationResponse.indicatesSuccess()) { 185 | handleErrorAuthorizationResponse(authorizationResponse); 186 | return false; 187 | } 188 | 189 | successResponse = authorizationResponse.toSuccessResponse(); 190 | authorizationCode = successResponse.getAuthorizationCode(); 191 | tokenRequest = getTokenRequest(authorizationCode); 192 | tokenResponse = getTokenResponse(tokenRequest); 193 | 194 | if (!tokenResponse.indicatesSuccess()) { 195 | handleErrorTokenResponse(tokenRequest, tokenResponse); 196 | return false; 197 | } 198 | 199 | handleSuccessTokenResponse(tokenResponse, authenticationInfo, nonce); 200 | return true; 201 | } catch (com.nimbusds.oauth2.sdk.ParseException | SSOAgentServerException | IOException e) { 202 | throw new SSOAgentServerException(e.getMessage(), e); 203 | } 204 | } 205 | 206 | private void handleSuccessTokenResponse(TokenResponse tokenResponse, SessionContext sessionContext, Nonce nonce) 207 | throws SSOAgentServerException { 208 | 209 | AccessTokenResponse successResponse = tokenResponse.toSuccessResponse(); 210 | AccessToken accessToken = successResponse.getTokens().getAccessToken(); 211 | RefreshToken refreshToken = successResponse.getTokens().getRefreshToken(); 212 | String idToken; 213 | 214 | try { 215 | idToken = successResponse.getCustomParameters().get(SSOAgentConstants.ID_TOKEN).toString(); 216 | } catch (NullPointerException e) { 217 | logger.log(Level.ERROR, "id_token is null."); 218 | throw new SSOAgentServerException(SSOAgentConstants.ErrorMessages.ID_TOKEN_NULL.getMessage(), 219 | SSOAgentConstants.ErrorMessages.ID_TOKEN_NULL.getCode(), e); 220 | } 221 | 222 | try { 223 | JWT idTokenJWT = JWTParser.parse(idToken); 224 | IDTokenValidator idTokenValidator = new IDTokenValidator(oidcAgentConfig, idTokenJWT); 225 | IDTokenClaimsSet claimsSet = idTokenValidator.validate(nonce); 226 | User user = new User(claimsSet.getSubject().getValue(), getUserAttributes(idToken)); 227 | sessionContext.setIdToken(idTokenJWT.getParsedString()); 228 | sessionContext.setUser(user); 229 | sessionContext.setAccessToken(accessToken.toJSONString()); 230 | if (refreshToken != null) { 231 | sessionContext.setRefreshToken(refreshToken.getValue()); 232 | } 233 | 234 | } catch (ParseException e) { 235 | throw new SSOAgentServerException(SSOAgentConstants.ErrorMessages.ID_TOKEN_PARSE.getMessage(), 236 | SSOAgentConstants.ErrorMessages.ID_TOKEN_PARSE.getCode(), e); 237 | } 238 | } 239 | 240 | private void handleErrorTokenResponse(TokenRequest tokenRequest, TokenResponse tokenResponse) 241 | throws SSOAgentServerException { 242 | 243 | TokenErrorResponse errorResponse = tokenResponse.toErrorResponse(); 244 | JSONObject requestObject = requestToJson(tokenRequest); 245 | JSONObject responseObject = errorResponse.toJSONObject(); 246 | 247 | logger.log(Level.INFO, "Request object for the error response: " + requestObject); 248 | logger.log(Level.INFO, "Error response object: " + responseObject); 249 | 250 | if (((TokenErrorResponse) tokenResponse).getErrorObject().getCode() != null && 251 | ((TokenErrorResponse) tokenResponse).getErrorObject().getDescription() != null) { 252 | throw new SSOAgentServerException(((TokenErrorResponse) tokenResponse).getErrorObject().getDescription(), 253 | ((TokenErrorResponse) tokenResponse).getErrorObject().getCode()); 254 | } 255 | } 256 | 257 | private void handleErrorAuthorizationResponse(AuthorizationResponse authorizationResponse) { 258 | 259 | AuthorizationErrorResponse errorResponse = authorizationResponse.toErrorResponse(); 260 | JSONObject responseObject = errorResponse.getErrorObject().toJSONObject(); 261 | 262 | logger.log(Level.INFO, "Error response object: " + responseObject); 263 | } 264 | 265 | private TokenResponse getTokenResponse(TokenRequest tokenRequest) throws SSOAgentServerException { 266 | 267 | TokenResponse tokenResponse; 268 | 269 | try { 270 | HTTPRequest tokenHTTPRequest = tokenRequest.toHTTPRequest(); 271 | tokenHTTPRequest.setConnectTimeout(oidcAgentConfig.getHttpConnectTimeout()); 272 | tokenHTTPRequest.setReadTimeout(oidcAgentConfig.getHttpReadTimeout()); 273 | 274 | tokenResponse = TokenResponse.parse(tokenHTTPRequest.send()); 275 | } catch (com.nimbusds.oauth2.sdk.ParseException | IOException e) { 276 | throw new SSOAgentServerException(e.getMessage(), e); 277 | } 278 | return tokenResponse; 279 | } 280 | 281 | private TokenRequest getTokenRequest(AuthorizationCode authorizationCode) { 282 | 283 | URI callbackURI = oidcAgentConfig.getCallbackUrl(); 284 | AuthorizationGrant authorizationGrant = new AuthorizationCodeGrant(authorizationCode, callbackURI); 285 | ClientID clientID = oidcAgentConfig.getConsumerKey(); 286 | Secret clientSecret = oidcAgentConfig.getConsumerSecret(); 287 | ClientAuthentication clientAuthentication = new ClientSecretBasic(clientID, clientSecret); 288 | URI tokenEndpoint = oidcAgentConfig.getTokenEndpoint(); 289 | 290 | return new TokenRequest(tokenEndpoint, clientAuthentication, authorizationGrant); 291 | } 292 | 293 | private JSONObject requestToJson(AbstractRequest request) { 294 | 295 | JSONObject obj = new JSONObject(); 296 | 297 | obj.appendField("tokenEndpoint", request.toHTTPRequest().getURI().toString()); 298 | obj.appendField("request body", request.toHTTPRequest().getQueryParameters()); 299 | return obj; 300 | } 301 | 302 | private Map getUserAttributes(String idToken) throws SSOAgentServerException { 303 | 304 | Map userClaimValueMap = new HashMap<>(); 305 | 306 | try { 307 | JWTClaimsSet claimsSet = SignedJWT.parse(idToken).getJWTClaimsSet(); 308 | Map customClaimValueMap = claimsSet.getClaims(); 309 | 310 | for (String claim : customClaimValueMap.keySet()) { 311 | if (!SSOAgentConstants.OIDC_METADATA_CLAIMS.contains(claim)) { 312 | userClaimValueMap.put(claim, customClaimValueMap.get(claim)); 313 | } 314 | } 315 | } catch (ParseException e) { 316 | throw new SSOAgentServerException(SSOAgentConstants.ErrorMessages.JWT_PARSE.getMessage(), 317 | SSOAgentConstants.ErrorMessages.JWT_PARSE.getCode(), e); 318 | } 319 | return userClaimValueMap; 320 | } 321 | 322 | private void validateConfig(OIDCAgentConfig oidcAgentConfig) throws SSOAgentClientException { 323 | 324 | validateForCode(oidcAgentConfig); 325 | } 326 | 327 | private void validateForCode(OIDCAgentConfig oidcAgentConfig) throws SSOAgentClientException { 328 | 329 | Scope scope = oidcAgentConfig.getScope(); 330 | 331 | if (scope.isEmpty() || !scope.contains(SSOAgentConstants.OIDC_OPENID)) { 332 | throw new SSOAgentClientException(SSOAgentConstants.ErrorMessages.AGENT_CONFIG_SCOPE.getMessage(), 333 | SSOAgentConstants.ErrorMessages.AGENT_CONFIG_SCOPE.getCode()); 334 | } 335 | 336 | if (oidcAgentConfig.getConsumerKey() == null) { 337 | throw new SSOAgentClientException(SSOAgentConstants.ErrorMessages.AGENT_CONFIG_CLIENT_ID.getMessage(), 338 | SSOAgentConstants.ErrorMessages.AGENT_CONFIG_CLIENT_ID.getCode()); 339 | } 340 | 341 | if (oidcAgentConfig.getConsumerSecret() == null) { 342 | throw new SSOAgentClientException(SSOAgentConstants.ErrorMessages.AGENT_CONFIG_CLIENT_SECRET.getMessage(), 343 | SSOAgentConstants.ErrorMessages.AGENT_CONFIG_CLIENT_SECRET.getCode()); 344 | } 345 | 346 | if (StringUtils.isEmpty(oidcAgentConfig.getCallbackUrl().toString())) { 347 | throw new SSOAgentClientException(SSOAgentConstants.ErrorMessages.AGENT_CONFIG_CALLBACK_URL.getMessage(), 348 | SSOAgentConstants.ErrorMessages.AGENT_CONFIG_CALLBACK_URL.getCode()); 349 | } 350 | } 351 | } 352 | --------------------------------------------------------------------------------