From f228b17858a8f67ef630227604c2d948eb0bc315 Mon Sep 17 00:00:00 2001 From: Petr Dvorak Date: Fri, 12 Feb 2021 16:49:14 +0100 Subject: [PATCH 1/8] Fix #271: Assure customAttibutes map is not null when calling activation provider --- .../jaxrs/service/v3/ActivationService.java | 35 +++++++++++++----- .../spring/service/v3/ActivationService.java | 36 +++++++++++++------ 2 files changed, 53 insertions(+), 18 deletions(-) diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/ActivationService.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/ActivationService.java index 4940b099..7b026c56 100644 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/ActivationService.java +++ b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/ActivationService.java @@ -89,8 +89,8 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request final String encryptedData = activationData.getEncryptedData(); final String mac = activationData.getMac(); final String nonce = activationData.getNonce(); - final Map customAttributes = request.getCustomAttributes(); final Map identity = request.getIdentityAttributes(); + final Map customAttributes = (request.getCustomAttributes() != null) ? request.getCustomAttributes() : new HashMap<>(); // Validate inner encryption if (nonce == null && !"3.0".equals(eciesEncryption.getContext().getVersion())) { @@ -101,8 +101,20 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request switch (request.getType()) { // Regular activation which uses "code" identity attribute case CODE: { + + // Check if identity attributes are present + if (identity == null || identity.isEmpty()) { + logger.warn("Identity attributes are missing for code activation"); + throw new PowerAuthActivationException(); + } + // Extract data from request and encryption object - String activationCode = request.getIdentityAttributes().get("code"); + String activationCode = identity.get("code"); + + if (activationCode == null || activationCode.isEmpty()) { + logger.warn("Activation code is missing"); + throw new PowerAuthActivationException(); + } // Call PrepareActivation SOAP method on PA server PowerAuthPortV3ServiceStub.PrepareActivationResponse response = powerAuthClient.prepareActivation(activationCode, applicationKey, ephemeralPublicKey, encryptedData, mac, nonce); @@ -144,7 +156,13 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request case CUSTOM: { // Check if there is a custom activation provider available, return an error in case it is not available if (activationProvider == null) { - logger.warn("Activation provider is missing"); + logger.warn("Activation provider is not available"); + throw new PowerAuthActivationException(); + } + + // Check if identity attributes are present + if (identity == null || identity.isEmpty()) { + logger.warn("Identity attributes are missing for custom activation"); throw new PowerAuthActivationException(); } @@ -156,7 +174,7 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request // If no user was found or user ID is invalid, return an error if (userId == null || userId.equals("") || userId.length() > 255) { - logger.warn("User ID is invalid: {}", userId); + logger.warn("Invalid user ID: {}", userId); throw new PowerAuthActivationException(); } @@ -215,14 +233,15 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request // Activation using recovery code case RECOVERY: { - if (request.getIdentityAttributes() == null) { - logger.warn("Identity attributes are missing"); + // Check if identity attributes are present + if (identity == null || identity.isEmpty()) { + logger.warn("Identity attributes are missing for activation recovery"); throw new PowerAuthActivationException(); } // Extract data from request and encryption object - String recoveryCode = request.getIdentityAttributes().get("recoveryCode"); - String recoveryPuk = request.getIdentityAttributes().get("puk"); + String recoveryCode = identity.get("recoveryCode"); + String recoveryPuk = identity.get("puk"); if (recoveryCode == null || recoveryCode.isEmpty()) { logger.warn("Recovery code is missing"); diff --git a/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/ActivationService.java b/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/ActivationService.java index a5cbfb26..51310cf9 100644 --- a/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/ActivationService.java +++ b/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/ActivationService.java @@ -44,10 +44,7 @@ import org.springframework.stereotype.Service; import java.time.Instant; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.util.*; /** * Service implementing activation functionality. @@ -103,8 +100,8 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request final String encryptedData = activationData.getEncryptedData(); final String mac = activationData.getMac(); final String nonce = activationData.getNonce(); - final Map customAttributes = request.getCustomAttributes(); final Map identity = request.getIdentityAttributes(); + final Map customAttributes = (request.getCustomAttributes() != null) ? request.getCustomAttributes() : new HashMap<>(); // Validate inner encryption if (nonce == null && !"3.0".equals(eciesContext.getVersion())) { @@ -115,8 +112,20 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request switch (request.getType()) { // Regular activation which uses "code" identity attribute case CODE: { + + // Check if identity attributes are present + if (identity == null || identity.isEmpty()) { + logger.warn("Identity attributes are missing for code activation"); + throw new PowerAuthActivationException(); + } + // Extract data from request and encryption object - String activationCode = request.getIdentityAttributes().get("code"); + String activationCode = identity.get("code"); + + if (activationCode == null || activationCode.isEmpty()) { + logger.warn("Activation code is missing"); + throw new PowerAuthActivationException(); + } // Call PrepareActivation method on PA server PrepareActivationResponse response = powerAuthClient.prepareActivation(activationCode, applicationKey, ephemeralPublicKey, encryptedData, mac, nonce); @@ -162,6 +171,12 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request throw new PowerAuthActivationException(); } + // Check if identity attributes are present + if (identity == null || identity.isEmpty()) { + logger.warn("Identity attributes are missing for custom activation"); + throw new PowerAuthActivationException(); + } + // Create context for passing parameters between activation provider calls Map context = new LinkedHashMap<>(); @@ -229,14 +244,15 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request // Activation using recovery code case RECOVERY: { - if (request.getIdentityAttributes() == null) { - logger.warn("Identity attributes are missing"); + // Check if identity attributes are present + if (identity == null || identity.isEmpty()) { + logger.warn("Identity attributes are missing for activation recovery"); throw new PowerAuthActivationException(); } // Extract data from request and encryption object - String recoveryCode = request.getIdentityAttributes().get("recoveryCode"); - String recoveryPuk = request.getIdentityAttributes().get("puk"); + String recoveryCode = identity.get("recoveryCode"); + String recoveryPuk = identity.get("puk"); if (recoveryCode == null || recoveryCode.isEmpty()) { logger.warn("Recovery code is missing"); From 2d57ef657dcf4bbe8ecda74f0f603679a5abdbab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Dvo=C5=99=C3=A1k?= Date: Tue, 6 Apr 2021 13:18:08 +0200 Subject: [PATCH 2/8] Create codeql-analysis.yml --- .github/workflows/codeql-analysis.yml | 67 +++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 .github/workflows/codeql-analysis.yml diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 00000000..dee72c9e --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,67 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ develop, master ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ develop ] + schedule: + - cron: '27 4 * * 2' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + language: [ 'java' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] + # Learn more: + # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed + + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v1 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v1 + + # ℹī¸ Command-line programs to run using the OS shell. + # 📚 https://git.io/JvXDl + + # ✏ī¸ If the Autobuild fails above, remove it and uncomment the following three lines + # and modify them (or add more) to build your code if your project + # uses a compiled language + + #- run: | + # make bootstrap + # make release + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v1 From 11a55e33ef21653986941587b4f7d88246e03d34 Mon Sep 17 00:00:00 2001 From: Petr Dvorak Date: Wed, 5 May 2021 22:39:35 +0200 Subject: [PATCH 3/8] Prepare fixes for 1.1.0-SNAPSHOT Fix #275: Allow dynamic resource ID value in Spring annotation Fix #276: Deprecate Java EE support Update dependencies --- pom.xml | 14 +- powerauth-restful-model/pom.xml | 4 +- powerauth-restful-security-base/pom.xml | 15 +- powerauth-restful-security-javaee/pom.xml | 65 --- .../DefaultApplicationConfiguration.java | 40 -- .../PowerAuthApiAuthenticationImpl.java | 150 ------ .../PowerAuthSignatureAuthenticationImpl.java | 243 ---------- .../PowerAuthTokenAuthenticationImpl.java | 150 ------ .../controller/v2/ActivationController.java | 130 ------ .../controller/v2/SecureVaultController.java | 96 ---- .../controller/v2/SignatureController.java | 143 ------ .../jaxrs/controller/v2/TokenController.java | 137 ------ .../controller/v3/ActivationController.java | 139 ------ .../controller/v3/RecoveryController.java | 108 ----- .../controller/v3/SecureVaultController.java | 103 ----- .../controller/v3/SignatureController.java | 144 ------ .../jaxrs/controller/v3/TokenController.java | 137 ------ .../controller/v3/UpgradeController.java | 145 ------ .../converter/v2/SignatureTypeConverter.java | 89 ---- .../converter/v3/SignatureTypeConverter.java | 89 ---- .../jaxrs/encryption/EncryptorFactory.java | 81 ---- .../PowerAuthActivationExceptionResolver.java | 43 -- ...erAuthAuthenticationExceptionResolver.java | 46 -- .../PowerAuthEncryptionExceptionResolver.java | 43 -- .../PowerAuthRecoveryExceptionResolver.java | 43 -- ...PowerAuthSecureVaultExceptionResolver.java | 44 -- .../PowerAuthUpgradeExceptionResolver.java | 24 - .../jaxrs/filter/PowerAuthRequestFilter.java | 57 --- .../PowerAuthAuthenticationProvider.java | 329 ------------- .../provider/PowerAuthEncryptionProvider.java | 64 --- .../jaxrs/service/v2/ActivationService.java | 96 ---- .../jaxrs/service/v2/SecureVaultService.java | 150 ------ .../api/jaxrs/service/v2/TokenService.java | 99 ---- .../jaxrs/service/v3/ActivationService.java | 434 ------------------ .../api/jaxrs/service/v3/RecoveryService.java | 86 ---- .../jaxrs/service/v3/SecureVaultService.java | 119 ----- .../api/jaxrs/service/v3/TokenService.java | 140 ------ .../api/jaxrs/service/v3/UpgradeService.java | 156 ------- .../pom.xml | 10 +- .../PowerAuthAnnotationInterceptor.java | 90 +++- powerauth-restful-security-spring/pom.xml | 8 +- .../META-INF/application.xml | 27 -- powerauth-restful-server-javaee/pom.xml | 72 --- .../rest/api/javaee/JavaEEApplication.java | 85 ---- .../DefaultJacksonJsonProvider.java | 51 -- .../configuration/PowerAuthBeanFactory.java | 58 --- .../controller/AuthenticationController.java | 78 ---- .../javaee/controller/TokenController.java | 57 --- .../v2/CustomActivationController.java | 152 ------ .../v2/EncryptedDataExchangeController.java | 126 ----- .../v3/EncryptedDataExchangeController.java | 248 ---------- .../model/request/DataExchangeRequest.java | 41 -- .../model/response/DataExchangeResponse.java | 41 -- .../DefaultCustomActivationProvider.java | 69 --- .../src/main/webapp/WEB-INF/beans.xml | 27 -- powerauth-restful-server-spring/pom.xml | 6 +- .../controller/AuthenticationController.java | 36 +- 57 files changed, 135 insertions(+), 5342 deletions(-) delete mode 100644 powerauth-restful-security-javaee/pom.xml delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/application/DefaultApplicationConfiguration.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/authentication/PowerAuthApiAuthenticationImpl.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/authentication/PowerAuthSignatureAuthenticationImpl.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/authentication/PowerAuthTokenAuthenticationImpl.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/ActivationController.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/SecureVaultController.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/SignatureController.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/TokenController.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/ActivationController.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/RecoveryController.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/SecureVaultController.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/SignatureController.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/TokenController.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/UpgradeController.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/converter/v2/SignatureTypeConverter.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/converter/v3/SignatureTypeConverter.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/encryption/EncryptorFactory.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthActivationExceptionResolver.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthAuthenticationExceptionResolver.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthEncryptionExceptionResolver.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthRecoveryExceptionResolver.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthSecureVaultExceptionResolver.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthUpgradeExceptionResolver.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/filter/PowerAuthRequestFilter.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/provider/PowerAuthAuthenticationProvider.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/provider/PowerAuthEncryptionProvider.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v2/ActivationService.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v2/SecureVaultService.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v2/TokenService.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/ActivationService.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/RecoveryService.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/SecureVaultService.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/TokenService.java delete mode 100644 powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/UpgradeService.java delete mode 100644 powerauth-restful-server-javaee/META-INF/application.xml delete mode 100644 powerauth-restful-server-javaee/pom.xml delete mode 100644 powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/JavaEEApplication.java delete mode 100644 powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/configuration/DefaultJacksonJsonProvider.java delete mode 100644 powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/configuration/PowerAuthBeanFactory.java delete mode 100644 powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/AuthenticationController.java delete mode 100644 powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/TokenController.java delete mode 100644 powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/v2/CustomActivationController.java delete mode 100644 powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/v2/EncryptedDataExchangeController.java delete mode 100644 powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/v3/EncryptedDataExchangeController.java delete mode 100644 powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/model/request/DataExchangeRequest.java delete mode 100644 powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/model/response/DataExchangeResponse.java delete mode 100644 powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/provider/DefaultCustomActivationProvider.java delete mode 100644 powerauth-restful-server-javaee/src/main/webapp/WEB-INF/beans.xml diff --git a/pom.xml b/pom.xml index ad1effa1..d97182b8 100644 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,7 @@ io.getlime.security powerauth-restful-integration-parent - 1.0.0 + 1.1.0-SNAPSHOT pom 2017 @@ -70,10 +70,8 @@ powerauth-restful-model powerauth-restful-security-base - powerauth-restful-security-javaee powerauth-restful-security-spring powerauth-restful-security-spring-annotation - powerauth-restful-server-javaee powerauth-restful-server-spring @@ -86,13 +84,11 @@ 3.2.0 3.2.1 3.3.1 - 7.0 3.1.0 - 2.3.7.RELEASE - 30.0-jre - 1.7.30 - 2.11.3 - 1.67 + 2.4.5 + 1.9 + 2.12.3 + 1.68 1.2.0 diff --git a/powerauth-restful-model/pom.xml b/powerauth-restful-model/pom.xml index cac290f6..22affa7c 100644 --- a/powerauth-restful-model/pom.xml +++ b/powerauth-restful-model/pom.xml @@ -24,14 +24,14 @@ 4.0.0 powerauth-restful-model - 1.0.0 + 1.1.0-SNAPSHOT powerauth-restful-model Model classes PowerAuth Standard RESTful API io.getlime.security powerauth-restful-integration-parent - 1.0.0 + 1.1.0-SNAPSHOT ../pom.xml diff --git a/powerauth-restful-security-base/pom.xml b/powerauth-restful-security-base/pom.xml index 65873da7..4bd59fec 100644 --- a/powerauth-restful-security-base/pom.xml +++ b/powerauth-restful-security-base/pom.xml @@ -25,12 +25,12 @@ 4.0.0 powerauth-restful-security-base - 1.0.0 + 1.1.0-SNAPSHOT powerauth-restful-integration-parent io.getlime.security - 1.0.0 + 1.1.0-SNAPSHOT ../pom.xml @@ -40,17 +40,17 @@ io.getlime.security powerauth-java-crypto - 1.0.0 + 1.1.0-SNAPSHOT io.getlime.security powerauth-java-http - 1.0.0 + 1.1.0-SNAPSHOT io.getlime.security powerauth-restful-model - 1.0.0 + 1.1.0-SNAPSHOT @@ -64,6 +64,11 @@ jackson-databind ${jackson-databind.version} + + org.apache.commons + commons-text + ${commons-text.version} + diff --git a/powerauth-restful-security-javaee/pom.xml b/powerauth-restful-security-javaee/pom.xml deleted file mode 100644 index 3e703bc5..00000000 --- a/powerauth-restful-security-javaee/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - 4.0.0 - - powerauth-restful-security-javaee - 1.0.0 - powerauth-restful-security-javaee - PowerAuth RESTful API Security Additions for EJB - - - powerauth-restful-integration-parent - io.getlime.security - 1.0.0 - ../pom.xml - - - - - - javax - javaee-api - ${javaee-api.version} - provided - - - - io.getlime.security - powerauth-restful-security-base - 1.0.0 - - - io.getlime.security - powerauth-java-client-axis - 1.0.0 - - - org.slf4j - slf4j-api - ${slf4j-api.version} - - - - - diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/application/DefaultApplicationConfiguration.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/application/DefaultApplicationConfiguration.java deleted file mode 100644 index 5c8e3448..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/application/DefaultApplicationConfiguration.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.application; - -import io.getlime.security.powerauth.rest.api.base.application.PowerAuthApplicationConfiguration; - -import java.util.Map; - -/** - * Default (empty) implementation of application configuration. - * - * @author Petr Dvorak, petr@wultra.com - */ -public class DefaultApplicationConfiguration implements PowerAuthApplicationConfiguration { - - public DefaultApplicationConfiguration() { - } - - @Override - public Map statusServiceCustomObject() { - return null; - } -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/authentication/PowerAuthApiAuthenticationImpl.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/authentication/PowerAuthApiAuthenticationImpl.java deleted file mode 100644 index 41fc612e..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/authentication/PowerAuthApiAuthenticationImpl.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.authentication; - -import io.getlime.security.powerauth.crypto.lib.enums.PowerAuthSignatureTypes; -import io.getlime.security.powerauth.http.PowerAuthHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; - -import java.io.Serializable; -import java.util.List; - -/** - * PowerAuth API authentication object used between intermediate server application (such as mobile - * banking API) and core systems (such as banking core). - * - * @author Petr Dvorak - * - */ -public class PowerAuthApiAuthenticationImpl implements PowerAuthApiAuthentication, Serializable { - - private static final long serialVersionUID = -1270504081898389806L; - - private String activationId; - private String userId; - private Long applicationId; - private List applicationRoles; - private List activationFlags; - private PowerAuthSignatureTypes factors; - private String version; - private PowerAuthHttpHeader httpHeader; - - /** - * Default constructor. - */ - public PowerAuthApiAuthenticationImpl() { - } - - /** - * Constructor for a new PowerAuthApiAuthenticationImpl. - * @param activationId Activation ID. - * @param userId User ID. - * @param applicationId Application ID. - * @param applicationRoles Application roles. - * @param factors Authentication factors. - */ - public PowerAuthApiAuthenticationImpl(String activationId, String userId, Long applicationId, List applicationRoles, PowerAuthSignatureTypes factors) { - this.activationId = activationId; - this.userId = userId; - this.applicationId = applicationId; - this.applicationRoles = applicationRoles; - this.factors = factors; - } - - @Override - public String getUserId() { - return userId; - } - - @Override - public void setUserId(String userId) { - this.userId = userId; - } - - @Override - public String getActivationId() { - return activationId; - } - - @Override - public void setActivationId(String activationId) { - this.activationId = activationId; - } - - @Override - public Long getApplicationId() { - return applicationId; - } - - @Override - public void setApplicationId(Long id) { - this.applicationId = id; - } - - @Override - public List getApplicationRoles() { - return applicationRoles; - } - - @Override - public void setApplicationRoles(List applicationRoles) { - this.applicationRoles = applicationRoles; - } - - @Override - public List getActivationFlags() { - return activationFlags; - } - - @Override - public void setActivationFlags(List activationFlags) { - this.activationFlags = activationFlags; - } - - @Override - public PowerAuthSignatureTypes getSignatureFactors() { - return factors; - } - - @Override - public void setSignatureFactors(PowerAuthSignatureTypes factors) { - this.factors = factors; - } - - @Override - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - @Override - public PowerAuthHttpHeader getHttpHeader() { - return httpHeader; - } - - @Override - public void setHttpHeader(PowerAuthHttpHeader httpHeader) { - this.httpHeader = httpHeader; - } -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/authentication/PowerAuthSignatureAuthenticationImpl.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/authentication/PowerAuthSignatureAuthenticationImpl.java deleted file mode 100644 index 5dffb4ff..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/authentication/PowerAuthSignatureAuthenticationImpl.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.authentication; - -import io.getlime.security.powerauth.http.PowerAuthHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthSignatureAuthentication; - -/** - * PowerAuth authentication object used between PowerAuth Client and intermediate server - * application (such as mobile banking API). - * - * @author Petr Dvorak - * - */ -public class PowerAuthSignatureAuthenticationImpl implements PowerAuthSignatureAuthentication { - - private String activationId; - private String applicationKey; - private String signature; - private String signatureType; - private String requestUri; - private String httpMethod; - private byte[] nonce; - private byte[] data; - private String version; - private PowerAuthHttpHeader httpHeader; - private Integer forcedSignatureVersion; - - /** - * Get activation ID. - * @return Activation ID. - */ - @Override - public String getActivationId() { - return activationId; - } - - /** - * Set activation ID. - * @param activationId Activation ID. - */ - @Override - public void setActivationId(String activationId) { - this.activationId = activationId; - } - - /** - * Get application key. - * @return Application key. - */ - @Override - public String getApplicationKey() { - return applicationKey; - } - - /** - * Set application key. - * @param applicationKey Application key. - */ - @Override - public void setApplicationKey(String applicationKey) { - this.applicationKey = applicationKey; - } - - /** - * Get signature. - * @return Signature. - */ - @Override - public String getSignature() { - return signature; - } - - /** - * Set signature. - * @param signature Signature. - */ - @Override - public void setSignature(String signature) { - this.signature = signature; - } - - /** - * Get signature type. - * @return Signature type. - */ - @Override - public String getSignatureType() { - return signatureType; - } - - /** - * Set signature type. - * @param signatureType Signature type. - */ - @Override - public void setSignatureType(String signatureType) { - this.signatureType = signatureType; - } - - /** - * Get request URI identifier. - * @return Request URI identifier. - */ - @Override - public String getRequestUri() { - return requestUri; - } - - /** - * Set request URI identifier. - * @param requestUri Request URI identifier. - */ - @Override - public void setRequestUri(String requestUri) { - this.requestUri = requestUri; - } - - /** - * Get HTTP method. - * @return HTTP method. - */ - @Override - public String getHttpMethod() { - return httpMethod; - } - - /** - * Set HTTP method. - * @param httpMethod HTTP method. - */ - @Override - public void setHttpMethod(String httpMethod) { - this.httpMethod = httpMethod; - } - - /** - * Get nonce. - * @return Nonce. - */ - @Override - public byte[] getNonce() { - return nonce; - } - - /** - * Set nonce. - * @param nonce Nonce. - */ - @Override - public void setNonce(byte[] nonce) { - this.nonce = nonce; - } - - /** - * Get request data. - * @return Request data. - */ - @Override - public byte[] getData() { - return data; - } - - /** - * Set request data. - * @param data Request data. - */ - @Override - public void setData(byte[] data) { - this.data = data; - } - - /** - * Get PowerAuth protocol version. - * @return PowerAuth protocol version. - */ - @Override - public String getVersion() { - return version; - } - - /** - * Set PowerAuth protocol version. - * @param version PowerAuth protocol version. - */ - @Override - public void setVersion(String version) { - this.version = version; - } - - /** - * Get parsed PowerAuth HTTP header. - * @return PowerAuth HTTP header. - */ - @Override - public PowerAuthHttpHeader getHttpHeader() { - return httpHeader; - } - - /** - * Set parsed PowerAuth HTTP header. - * @param httpHeader PowerAuth HTTP header. - */ - @Override - public void setHttpHeader(PowerAuthHttpHeader httpHeader) { - this.httpHeader = httpHeader; - } - - /** - * Get forced signature version which is used during upgrade. - * @return Forced signature version. - */ - @Override - public Integer getForcedSignatureVersion() { - return forcedSignatureVersion; - } - - /** - * Set forced signature version which is used during upgrade. - * @param forcedSignatureVersion Forced signature version. - */ - @Override - public void setForcedSignatureVersion(Integer forcedSignatureVersion) { - this.forcedSignatureVersion = forcedSignatureVersion; - } -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/authentication/PowerAuthTokenAuthenticationImpl.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/authentication/PowerAuthTokenAuthenticationImpl.java deleted file mode 100644 index e47fac44..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/authentication/PowerAuthTokenAuthenticationImpl.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.authentication; - -import io.getlime.security.powerauth.http.PowerAuthHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthTokenAuthentication; - -/** - * Implementation of the {@link PowerAuthTokenAuthentication} interface, with Spring Security objects. - * - * @author Petr Dvorak, petr@wultra.com - */ -public class PowerAuthTokenAuthenticationImpl implements PowerAuthTokenAuthentication { - - private String tokenId; - private String tokenDigest; - private String nonce; - private String timestamp; - private String version; - private PowerAuthHttpHeader httpHeader; - - /** - * Default constructor - */ - public PowerAuthTokenAuthenticationImpl() { - } - - // Getters and setters for fields - - /** - * Get token ID. - * @return Token ID. - */ - @Override - public String getTokenId() { - return tokenId; - } - - /** - * Set token ID. - * @param tokenId Token ID. - */ - public void setTokenId(String tokenId) { - this.tokenId = tokenId; - } - - /** - * Get token digest. - * @return Token digest. - */ - @Override - public String getTokenDigest() { - return tokenDigest; - } - - /** - * Set token digest. - * @param tokenDigest Token digest. - */ - public void setTokenDigest(String tokenDigest) { - this.tokenDigest = tokenDigest; - } - - /** - * Get token related nonce. - * @return Nonce. - */ - @Override - public String getNonce() { - return nonce; - } - - /** - * Set token related nonce. - * @param nonce Nonce. - */ - public void setNonce(String nonce) { - this.nonce = nonce; - } - - /** - * Get token creation timestamp. - * @return Token timestamp. - */ - @Override - public String getTimestamp() { - return timestamp; - } - - /** - * Set token creation timestamp. - * @param timestamp Token timestamp. - */ - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } - - /** - * Get PowerAuth protocol version. - * @return PowerAuth protocol version. - */ - @Override - public String getVersion() { - return version; - } - - /** - * Set PowerAuth protocol version. - * @param version PowerAuth protocol version. - */ - @Override - public void setVersion(String version) { - this.version = version; - } - - /** - * Get parsed PowerAuth HTTP header. - * @return PowerAuth HTTP header. - */ - @Override - public PowerAuthHttpHeader getHttpHeader() { - return httpHeader; - } - - /** - * Set parsed PowerAuth HTTP header. - * @param httpHeader PowerAuth HTTP header. - */ - @Override - public void setHttpHeader(PowerAuthHttpHeader httpHeader) { - this.httpHeader = httpHeader; - } -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/ActivationController.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/ActivationController.java deleted file mode 100644 index 405e5b8b..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/ActivationController.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.controller.v2; - -import io.getlime.core.rest.model.base.request.ObjectRequest; -import io.getlime.core.rest.model.base.response.ObjectResponse; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthActivationException; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthInvalidRequestException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureInvalidException; -import io.getlime.security.powerauth.rest.api.jaxrs.provider.PowerAuthAuthenticationProvider; -import io.getlime.security.powerauth.rest.api.model.request.v2.ActivationCreateRequest; -import io.getlime.security.powerauth.rest.api.model.request.v3.ActivationStatusRequest; -import io.getlime.security.powerauth.rest.api.model.response.v2.ActivationCreateResponse; -import io.getlime.security.powerauth.rest.api.model.response.v3.ActivationRemoveResponse; -import io.getlime.security.powerauth.rest.api.model.response.v3.ActivationStatusResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; - -/** - * Controller implementing activation related end-points from the PowerAuth - * Standard API. - * - * @author Petr Dvorak, petr@wultra.com - * - */ -@Path("pa/activation") -@Produces(MediaType.APPLICATION_JSON) -public class ActivationController { - - private static final Logger logger = LoggerFactory.getLogger(ActivationController.class); - - @Inject - private io.getlime.security.powerauth.rest.api.jaxrs.service.v2.ActivationService activationServiceV2; - - @Inject - private io.getlime.security.powerauth.rest.api.jaxrs.service.v3.ActivationService activationServiceV3; - - @Inject - private PowerAuthAuthenticationProvider authenticationProvider; - - /** - * Create a new activation. - * @param request PowerAuth RESTful request with {@link ActivationCreateRequest} payload. - * @return PowerAuth RESTful response with {@link ActivationCreateResponse} payload. - * @throws PowerAuthActivationException In case creating activation fails. - */ - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @Path("create") - public ObjectResponse createActivation(ObjectRequest request) throws PowerAuthActivationException { - if (request.getRequestObject() == null || request.getRequestObject().getActivationIdShort() == null) { - logger.warn("Invalid request object in activation create"); - throw new PowerAuthActivationException(); - } - ActivationCreateResponse response = activationServiceV2.createActivation(request.getRequestObject()); - return new ObjectResponse<>(response); - } - - /** - * Get activation status. - * @param request PowerAuth RESTful request with {@link ActivationStatusRequest} payload. - * @return PowerAuth RESTful response with {@link ActivationStatusResponse} payload. - * @throws PowerAuthActivationException In case request fails. - */ - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @Path("status") - public ObjectResponse getActivationStatus(ObjectRequest request) throws PowerAuthActivationException { - if (request.getRequestObject() == null || request.getRequestObject().getActivationId() == null) { - logger.warn("Invalid request object in activation status"); - throw new PowerAuthActivationException(); - } - ActivationStatusResponse response = activationServiceV3.getActivationStatus(request.getRequestObject()); - return new ObjectResponse<>(response); - } - - /** - * Remove activation. - * @param signatureHeader PowerAuth signature HTTP header. - * @return PowerAuth RESTful response with {@link ActivationRemoveResponse} payload. - * @throws PowerAuthAuthenticationException In case the signature validation fails. - * @throws PowerAuthActivationException In case remove request fails. - */ - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @Path("remove") - public ObjectResponse removeActivation(@HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String signatureHeader) throws PowerAuthAuthenticationException, PowerAuthActivationException { - // Request body needs to be set to null because the SDK uses null for the signature, although {} is sent as request body - PowerAuthApiAuthentication apiAuthentication = authenticationProvider.validateRequestSignature("POST", null, "/pa/activation/remove", signatureHeader); - if (apiAuthentication == null || apiAuthentication.getActivationId() == null) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - if (!"2.0".equals(apiAuthentication.getVersion()) && !"2.1".equals(apiAuthentication.getVersion())) { - logger.warn("Endpoint does not support PowerAuth protocol version {}", apiAuthentication.getVersion()); - throw new PowerAuthInvalidRequestException(); - } - ActivationRemoveResponse response = activationServiceV3.removeActivation(apiAuthentication); - return new ObjectResponse<>(response); - } - - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/SecureVaultController.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/SecureVaultController.java deleted file mode 100644 index 4c825cec..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/SecureVaultController.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.controller.v2; - -import io.getlime.core.rest.model.base.request.ObjectRequest; -import io.getlime.core.rest.model.base.response.ObjectResponse; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.http.validator.InvalidPowerAuthHttpHeaderException; -import io.getlime.security.powerauth.http.validator.PowerAuthSignatureHttpHeaderValidator; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthSecureVaultException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthInvalidRequestException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureInvalidException; -import io.getlime.security.powerauth.rest.api.jaxrs.service.v2.SecureVaultService; -import io.getlime.security.powerauth.rest.api.model.request.v2.VaultUnlockRequest; -import io.getlime.security.powerauth.rest.api.model.response.v2.VaultUnlockResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; - -/** - * Controller implementing secure vault related end-points from the - * PowerAuth Standard API. - * - * @author Petr Dvorak, petr@wultra.com - */ -@Path("pa/vault") -@Produces(MediaType.APPLICATION_JSON) -public class SecureVaultController { - - private static final Logger logger = LoggerFactory.getLogger(SecureVaultController.class); - - @Inject - private SecureVaultService secureVaultServiceV2; - - @Inject - private HttpServletRequest httpServletRequest; - - /** - * Request the vault unlock key. - * @param signatureHeader PowerAuth signature HTTP header. - * @param request Vault unlock request data. - * @return PowerAuth RESTful response with {@link VaultUnlockResponse} payload. - * @throws PowerAuthAuthenticationException In case authentication fails. - * @throws PowerAuthSecureVaultException In case unlocking the vault fails. - */ - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @Path("unlock") - public ObjectResponse unlockVault(@HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String signatureHeader, - ObjectRequest request) throws PowerAuthAuthenticationException, PowerAuthSecureVaultException { - // Request object is not validated - it is optional for version 2 - - // Parse the header - PowerAuthSignatureHttpHeader header = new PowerAuthSignatureHttpHeader().fromValue(signatureHeader); - - // Validate the header - try { - PowerAuthSignatureHttpHeaderValidator.validate(header); - } catch (InvalidPowerAuthHttpHeaderException ex) { - logger.warn("Signature HTTP header validation failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthSignatureInvalidException(); - } - - if (!"2.0".equals(header.getVersion()) && !"2.1".equals(header.getVersion())) { - logger.warn("Endpoint does not support PowerAuth protocol version {}", header.getVersion()); - throw new PowerAuthInvalidRequestException(); - } - VaultUnlockResponse response = secureVaultServiceV2.vaultUnlock(signatureHeader, request.getRequestObject(), httpServletRequest); - return new ObjectResponse<>(response); - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/SignatureController.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/SignatureController.java deleted file mode 100644 index a1c304c3..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/SignatureController.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.controller.v2; - -import io.getlime.core.rest.model.base.response.Response; -import io.getlime.security.powerauth.crypto.lib.enums.PowerAuthSignatureTypes; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthInvalidRequestException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureErrorException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureInvalidException; -import io.getlime.security.powerauth.rest.api.jaxrs.provider.PowerAuthAuthenticationProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import java.util.Arrays; - -/** - * End-point for validating signatures. - * - * @author Roman Strobl, roman.strobl@wultra.com - * - */ -@Path("pa/signature") -@Consumes(MediaType.APPLICATION_JSON) -@Produces(MediaType.APPLICATION_JSON) -public class SignatureController { - - private static final Logger logger = LoggerFactory.getLogger(SignatureController.class); - - @Context - private HttpServletRequest httpServletRequest; - - @Inject - private PowerAuthAuthenticationProvider authenticationProvider; - - /** - * Validate signature by validating any data sent in GET request to this end-point. - * @param authHeader PowerAuth authentication HTTP header. - * @return API response with success. - * @throws PowerAuthAuthenticationException In case any error occurs, including signature validation errors. - */ - @GET - @Path("validate") - public Response validateSignatureGet(@HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthAuthenticationException { - return validateSignature(authHeader); - } - - /** - * Validate signature by validating any data sent in POST request to this end-point. - * @param authHeader PowerAuth authentication HTTP header. - * @return API response with success. - * @throws PowerAuthAuthenticationException In case any error occurs, including signature validation errors. - */ - @POST - @Path("validate") - public Response validateSignaturePost(@HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthAuthenticationException { - return validateSignature(authHeader); - } - - /** - * Validate signature by validating any data sent in PUT request to this end-point. - * @param authHeader PowerAuth authentication HTTP header. - * @return API response with success. - * @throws PowerAuthAuthenticationException In case any error occurs, including signature validation errors. - */ - @PUT - @Path("validate") - public Response validateSignaturePut(@HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthAuthenticationException { - return validateSignature(authHeader); - } - - /** - * Validate signature by validating any data sent in DELETE request to this end-point. - * @param authHeader PowerAuth authentication HTTP header. - * @return API response with success. - * @throws PowerAuthAuthenticationException In case any error occurs, including signature validation errors. - */ - @DELETE - @Path("validate") - public Response validateSignatureDelete(@HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthAuthenticationException { - return validateSignature(authHeader); - } - - /** - * Signature validation logic. - * @param authHeader PowerAuth authentication header. - * @return Response with Status.OK when signature validation succeeds. - * @throws PowerAuthAuthenticationException Thrown when signature validation fails or any other error occurs. - */ - private Response validateSignature(String authHeader) throws PowerAuthAuthenticationException { - try { - PowerAuthApiAuthentication authentication = authenticationProvider.validateRequestSignature( - httpServletRequest, - "/pa/signature/validate", - authHeader, - Arrays.asList( - PowerAuthSignatureTypes.POSSESSION_KNOWLEDGE, - PowerAuthSignatureTypes.POSSESSION_BIOMETRY, - PowerAuthSignatureTypes.POSSESSION_KNOWLEDGE_BIOMETRY - ) - ); - if (authentication == null || authentication.getActivationId() == null) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - if (!"2.0".equals(authentication.getVersion()) && !"2.1".equals(authentication.getVersion())) { - logger.warn("Endpoint does not support PowerAuth protocol version {}", authentication.getVersion()); - throw new PowerAuthInvalidRequestException(); - } - return new Response(); - } catch (PowerAuthAuthenticationException ex) { - throw ex; - } catch (Exception ex) { - logger.warn("Signature validation failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthSignatureErrorException(); - } - } -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/TokenController.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/TokenController.java deleted file mode 100644 index 3d24240d..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v2/TokenController.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.controller.v2; - -import io.getlime.core.rest.model.base.request.ObjectRequest; -import io.getlime.core.rest.model.base.response.ObjectResponse; -import io.getlime.security.powerauth.crypto.lib.enums.PowerAuthSignatureTypes; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.http.PowerAuthTokenHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthInvalidRequestException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureInvalidException; -import io.getlime.security.powerauth.rest.api.jaxrs.provider.PowerAuthAuthenticationProvider; -import io.getlime.security.powerauth.rest.api.model.request.v2.TokenCreateRequest; -import io.getlime.security.powerauth.rest.api.model.request.v3.TokenRemoveRequest; -import io.getlime.security.powerauth.rest.api.model.response.v2.TokenCreateResponse; -import io.getlime.security.powerauth.rest.api.model.response.v3.TokenRemoveResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import java.util.Arrays; - -/** - * Controller responsible for publishing services related to simple token-based authentication. - * - * @author Petr Dvorak, petr@wultra.com - */ -@Path("pa/token") -@Produces(MediaType.APPLICATION_JSON) -public class TokenController { - - private static final Logger logger = LoggerFactory.getLogger(TokenController.class); - - @Context - private HttpServletRequest httpRequest; - - @Inject - private io.getlime.security.powerauth.rest.api.jaxrs.service.v2.TokenService tokenServiceV2; - - @Inject - private io.getlime.security.powerauth.rest.api.jaxrs.service.v3.TokenService tokenServiceV3; - - @Inject - private PowerAuthAuthenticationProvider authenticationProvider; - - @Context - private HttpServletRequest httpServletRequest; - - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @Path("create") - public ObjectResponse createToken(ObjectRequest request, - @HeaderParam(PowerAuthTokenHttpHeader.HEADER_NAME) String tokenHeader, - @HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthAuthenticationException { - - if (request.getRequestObject() == null) { - logger.warn("Invalid request object in create token"); - throw new PowerAuthInvalidRequestException(); - } - // Verify request signature before creating token - PowerAuthApiAuthentication authentication = authenticationProvider.validateRequestSignature( - httpRequest, "/pa/token/create", authHeader, - Arrays.asList( - PowerAuthSignatureTypes.POSSESSION, - PowerAuthSignatureTypes.POSSESSION_KNOWLEDGE, - PowerAuthSignatureTypes.POSSESSION_BIOMETRY, - PowerAuthSignatureTypes.POSSESSION_KNOWLEDGE_BIOMETRY - )); - if (authentication == null || authentication.getActivationId() == null) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - if (!"2.0".equals(authentication.getVersion()) && !"2.1".equals(authentication.getVersion())) { - logger.warn("Endpoint does not support PowerAuth protocol version {}", authentication.getVersion()); - throw new PowerAuthInvalidRequestException(); - } - TokenCreateResponse response = tokenServiceV2.createToken(request.getRequestObject(), authentication); - return new ObjectResponse<>(response); - } - - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @Path("remove") - public ObjectResponse removeToken(ObjectRequest request, - @HeaderParam(PowerAuthTokenHttpHeader.HEADER_NAME) String tokenHeader, - @HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthAuthenticationException { - if (request.getRequestObject() == null) { - logger.warn("Invalid request object in create token"); - throw new PowerAuthInvalidRequestException(); - } - // Verify request signature before removing token - PowerAuthApiAuthentication authentication = authenticationProvider.validateRequestSignature( - httpRequest, "/pa/token/remove", authHeader, - Arrays.asList( - PowerAuthSignatureTypes.POSSESSION, - PowerAuthSignatureTypes.POSSESSION_KNOWLEDGE, - PowerAuthSignatureTypes.POSSESSION_BIOMETRY, - PowerAuthSignatureTypes.POSSESSION_KNOWLEDGE_BIOMETRY - )); - if (authentication == null || authentication.getActivationId() == null) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - if (!"2.0".equals(authentication.getVersion()) && !"2.1".equals(authentication.getVersion())) { - logger.warn("Endpoint does not support PowerAuth protocol version {}", authentication.getVersion()); - throw new PowerAuthInvalidRequestException(); - } - TokenRemoveResponse response = tokenServiceV3.removeToken(request.getRequestObject(), authentication); - return new ObjectResponse<>(response); - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/ActivationController.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/ActivationController.java deleted file mode 100644 index 52b5a362..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/ActivationController.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.controller.v3; - -import io.getlime.core.rest.model.base.request.ObjectRequest; -import io.getlime.core.rest.model.base.response.ObjectResponse; -import io.getlime.security.powerauth.crypto.lib.encryptor.ecies.model.EciesScope; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.encryption.PowerAuthEciesEncryption; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthActivationException; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthEncryptionException; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthRecoveryException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthInvalidRequestException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureInvalidException; -import io.getlime.security.powerauth.rest.api.jaxrs.provider.PowerAuthAuthenticationProvider; -import io.getlime.security.powerauth.rest.api.jaxrs.provider.PowerAuthEncryptionProvider; -import io.getlime.security.powerauth.rest.api.model.request.v3.ActivationLayer1Request; -import io.getlime.security.powerauth.rest.api.model.request.v3.ActivationStatusRequest; -import io.getlime.security.powerauth.rest.api.model.response.v3.ActivationLayer1Response; -import io.getlime.security.powerauth.rest.api.model.response.v3.ActivationRemoveResponse; -import io.getlime.security.powerauth.rest.api.model.response.v3.ActivationStatusResponse; -import io.getlime.security.powerauth.rest.api.model.response.v3.EciesEncryptedResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - -/** - * Controller implementing activation related end-points from the PowerAuth - * Standard API. - * - * @author Petr Dvorak, petr@wultra.com - * - */ -@Path("pa/v3/activation") -@Produces(MediaType.APPLICATION_JSON) -public class ActivationController { - - private static final Logger logger = LoggerFactory.getLogger(ActivationController.class); - - @Inject - private io.getlime.security.powerauth.rest.api.jaxrs.service.v3.ActivationService activationServiceV3; - - @Inject - private PowerAuthAuthenticationProvider authenticationProvider; - - @Inject - private PowerAuthEncryptionProvider encryptionProvider; - - @Context - private HttpServletRequest httpServletRequest; - - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @Path("create") - public EciesEncryptedResponse createActivation() throws PowerAuthActivationException, PowerAuthRecoveryException { - try { - PowerAuthEciesEncryption eciesEncryption = encryptionProvider.decryptRequest(httpServletRequest, ActivationLayer1Request.class, EciesScope.APPLICATION_SCOPE); - ActivationLayer1Request layer1Request = eciesEncryption.getRequestObject(); - ActivationLayer1Response layer1Response = activationServiceV3.createActivation(layer1Request, eciesEncryption); - return encryptionProvider.encryptResponse(layer1Response, eciesEncryption); - } catch (PowerAuthEncryptionException ex) { - logger.warn("Encryption failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthActivationException(); - } - } - - /** - * Get activation status. - * @param request PowerAuth RESTful request with {@link ActivationStatusRequest} payload. - * @return PowerAuth RESTful response with {@link ActivationStatusResponse} payload. - * @throws PowerAuthActivationException In case request fails. - */ - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @Path("status") - public ObjectResponse getActivationStatus(ObjectRequest request) throws PowerAuthActivationException { - if (request.getRequestObject() == null || request.getRequestObject().getActivationId() == null) { - logger.warn("Invalid request object in activation status"); - throw new PowerAuthActivationException(); - } - ActivationStatusResponse response = activationServiceV3.getActivationStatus(request.getRequestObject()); - return new ObjectResponse<>(response); - } - - /** - * Remove activation. - * @param signatureHeader PowerAuth signature HTTP header. - * @return PowerAuth RESTful response with {@link ActivationRemoveResponse} payload. - * @throws PowerAuthAuthenticationException In case the signature validation fails. - * @throws PowerAuthActivationException In case remove request fails. - */ - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @Path("remove") - public ObjectResponse removeActivation(@HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String signatureHeader) throws PowerAuthAuthenticationException, PowerAuthActivationException { - byte[] requestBodyBytes = authenticationProvider.extractRequestBodyBytes(httpServletRequest); - PowerAuthApiAuthentication apiAuthentication = authenticationProvider.validateRequestSignature("POST", requestBodyBytes, "/pa/activation/remove", signatureHeader); - if (apiAuthentication == null || apiAuthentication.getActivationId() == null) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - if (!"3.0".equals(apiAuthentication.getVersion()) && !"3.1".equals(apiAuthentication.getVersion())) { - logger.warn("Endpoint does not support PowerAuth protocol version {}", apiAuthentication.getVersion()); - throw new PowerAuthInvalidRequestException(); - } - ActivationRemoveResponse response = activationServiceV3.removeActivation(apiAuthentication); - return new ObjectResponse<>(response); - } - - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/RecoveryController.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/RecoveryController.java deleted file mode 100644 index bc80d67f..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/RecoveryController.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.controller.v3; - -import io.getlime.security.powerauth.crypto.lib.enums.PowerAuthSignatureTypes; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthInvalidRequestException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureInvalidException; -import io.getlime.security.powerauth.rest.api.jaxrs.provider.PowerAuthAuthenticationProvider; -import io.getlime.security.powerauth.rest.api.jaxrs.service.v3.RecoveryService; -import io.getlime.security.powerauth.rest.api.model.request.v3.EciesEncryptedRequest; -import io.getlime.security.powerauth.rest.api.model.response.v3.EciesEncryptedResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import java.util.Collections; - -/** - * Controller implementing recovery related end-points from the PowerAuth - * Standard API. - * - *

PowerAuth protocol versions: - *

    - *
  • 3.0
  • - *
- * - * @author Roman Strobl, roman.strobl@wultra.com - * - */ -@Path("/pa/v3/recovery") -@Produces(MediaType.APPLICATION_JSON) -public class RecoveryController { - - private static final Logger logger = LoggerFactory.getLogger(RecoveryController.class); - - @Context - private HttpServletRequest httpServletRequest; - - @Inject - private PowerAuthAuthenticationProvider authenticationProvider; - - @Inject - private RecoveryService recoveryService; - - /** - * Confirm recovery code. - * @param request ECIES encrypted request. - * @param authHeader PowerAuth signature HTTP header. - * @return ECIES encrypted response. - * @throws PowerAuthAuthenticationException In case confirm recovery fails. - */ - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @Path("confirm") - public EciesEncryptedResponse confirmRecoveryCode(EciesEncryptedRequest request, - @HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthAuthenticationException { - - if (request == null) { - logger.warn("Invalid request object in confirm recovery"); - throw new PowerAuthInvalidRequestException(); - } - // Verify request signature before creating token - PowerAuthApiAuthentication authentication = authenticationProvider.validateRequestSignature( - httpServletRequest, "/pa/recovery/confirm", authHeader, - Collections.singletonList( - PowerAuthSignatureTypes.POSSESSION_KNOWLEDGE - )); - if (authentication == null || authentication.getActivationId() == null) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - if (!"3.0".equals(authentication.getVersion()) && !"3.1".equals(authentication.getVersion())) { - logger.warn("Endpoint does not support PowerAuth protocol version {}", authentication.getVersion()); - throw new PowerAuthInvalidRequestException(); - } - if (request.getNonce() == null && !"3.0".equals(authentication.getVersion())) { - logger.warn("Missing nonce in ECIES request data"); - throw new PowerAuthInvalidRequestException(); - } - return recoveryService.confirmRecoveryCode(request, authentication); - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/SecureVaultController.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/SecureVaultController.java deleted file mode 100644 index bd20ff55..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/SecureVaultController.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.controller.v3; - -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.http.validator.InvalidPowerAuthHttpHeaderException; -import io.getlime.security.powerauth.http.validator.PowerAuthSignatureHttpHeaderValidator; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthSecureVaultException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthInvalidRequestException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureInvalidException; -import io.getlime.security.powerauth.rest.api.jaxrs.service.v3.SecureVaultService; -import io.getlime.security.powerauth.rest.api.model.request.v3.EciesEncryptedRequest; -import io.getlime.security.powerauth.rest.api.model.response.v3.EciesEncryptedResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - -/** - * Controller implementing secure vault related end-points from the - * PowerAuth Standard API. - * - * @author Petr Dvorak, petr@wultra.com - */ -@Path("pa/v3/vault") -@Produces(MediaType.APPLICATION_JSON) -public class SecureVaultController { - - private static final Logger logger = LoggerFactory.getLogger(SecureVaultController.class); - - @Inject - private SecureVaultService secureVaultServiceV3; - - @Context - private HttpServletRequest httpServletRequest; - - /** - * Request the vault unlock key. - * @param signatureHeader PowerAuth signature HTTP header. - * @param request Vault unlock request data. - * @param httpServletRequest HTTP servlet request. - * @return Response object encrypted by ECIES. - * @throws PowerAuthAuthenticationException In case authentication fails. - * @throws PowerAuthSecureVaultException In case unlocking the vault fails. - */ - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @Path("unlock") - public EciesEncryptedResponse unlockVault(@HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String signatureHeader, - EciesEncryptedRequest request, - @Context HttpServletRequest httpServletRequest) throws PowerAuthAuthenticationException, PowerAuthSecureVaultException { - if (request == null) { - logger.warn("Invalid request object in vault unlock"); - throw new PowerAuthInvalidRequestException(); - } - - // Parse the header - PowerAuthSignatureHttpHeader header = new PowerAuthSignatureHttpHeader().fromValue(signatureHeader); - - // Validate the header - try { - PowerAuthSignatureHttpHeaderValidator.validate(header); - } catch (InvalidPowerAuthHttpHeaderException ex) { - logger.warn("Signature HTTP header validation failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthSignatureInvalidException(); - } - - if (!"3.0".equals(header.getVersion()) && !"3.1".equals(header.getVersion())) { - logger.warn("Endpoint does not support PowerAuth protocol version {}", header.getVersion()); - throw new PowerAuthInvalidRequestException(); - } - if (request.getNonce() == null && !"3.0".equals(header.getVersion())) { - logger.warn("Missing nonce in ECIES request data"); - throw new PowerAuthInvalidRequestException(); - } - return secureVaultServiceV3.vaultUnlock(header, request, httpServletRequest); - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/SignatureController.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/SignatureController.java deleted file mode 100644 index 1fe9739e..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/SignatureController.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.controller.v3; - -import io.getlime.core.rest.model.base.response.Response; -import io.getlime.security.powerauth.crypto.lib.enums.PowerAuthSignatureTypes; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthInvalidRequestException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureErrorException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureInvalidException; -import io.getlime.security.powerauth.rest.api.jaxrs.provider.PowerAuthAuthenticationProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import java.util.Arrays; - -/** - * End-point for validating signatures. - * - * @author Roman Strobl, roman.strobl@wultra.com - * - */ -@Path("pa/v3/signature") -@Consumes(MediaType.APPLICATION_JSON) -@Produces(MediaType.APPLICATION_JSON) -public class SignatureController { - - private static final Logger logger = LoggerFactory.getLogger(SignatureController.class); - - @Context - private HttpServletRequest httpServletRequest; - - @Inject - private PowerAuthAuthenticationProvider authenticationProvider; - - /** - * Validate signature by validating any data sent in GET request to this end-point. - * @param authHeader PowerAuth authentication HTTP header. - * @return API response with success. - * @throws PowerAuthAuthenticationException In case any error occurs, including signature validation errors. - */ - @GET - @Path("validate") - public Response validateSignatureGet(@HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthAuthenticationException { - return validateSignature(authHeader); - } - - /** - * Validate signature by validating any data sent in POST request to this end-point. - * @param authHeader PowerAuth authentication HTTP header. - * @return API response with success. - * @throws PowerAuthAuthenticationException In case any error occurs, including signature validation errors. - */ - @POST - @Path("validate") - public Response validateSignaturePost(@HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthAuthenticationException { - return validateSignature(authHeader); - } - - /** - * Validate signature by validating any data sent in PUT request to this end-point. - * @param authHeader PowerAuth authentication HTTP header. - * @return API response with success. - * @throws PowerAuthAuthenticationException In case any error occurs, including signature validation errors. - */ - @PUT - @Path("validate") - public Response validateSignaturePut(@HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthAuthenticationException { - return validateSignature(authHeader); - } - - /** - * Validate signature by validating any data sent in DELETE request to this end-point. - * @param authHeader PowerAuth authentication HTTP header. - * @return API response with success. - * @throws PowerAuthAuthenticationException In case any error occurs, including signature validation errors. - */ - @DELETE - @Path("validate") - public Response validateSignatureDelete(@HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthAuthenticationException { - return validateSignature(authHeader); - } - - /** - * Signature validation logic. - * @param authHeader PowerAuth authentication header. - * @return Response with Status.OK when signature validation succeeds. - * @throws PowerAuthAuthenticationException Thrown when signature validation fails or any other error occurs. - */ - private Response validateSignature(String authHeader) throws PowerAuthAuthenticationException { - try { - PowerAuthApiAuthentication authentication = authenticationProvider.validateRequestSignature( - httpServletRequest, - "/pa/signature/validate", - authHeader, - Arrays.asList( - PowerAuthSignatureTypes.POSSESSION, - PowerAuthSignatureTypes.POSSESSION_KNOWLEDGE, - PowerAuthSignatureTypes.POSSESSION_BIOMETRY, - PowerAuthSignatureTypes.POSSESSION_KNOWLEDGE_BIOMETRY - ) - ); - if (authentication == null || authentication.getActivationId() == null) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - if (!"3.0".equals(authentication.getVersion()) && !"3.1".equals(authentication.getVersion())) { - logger.warn("Endpoint does not support PowerAuth protocol version {}", authentication.getVersion()); - throw new PowerAuthInvalidRequestException(); - } - return new Response(); - } catch (PowerAuthAuthenticationException ex) { - throw ex; - } catch (Exception ex) { - logger.warn("Signature validation failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthSignatureErrorException(); - } - } -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/TokenController.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/TokenController.java deleted file mode 100644 index 5ea9d078..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/TokenController.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.controller.v3; - -import io.getlime.core.rest.model.base.request.ObjectRequest; -import io.getlime.core.rest.model.base.response.ObjectResponse; -import io.getlime.security.powerauth.crypto.lib.enums.PowerAuthSignatureTypes; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.http.PowerAuthTokenHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthInvalidRequestException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureInvalidException; -import io.getlime.security.powerauth.rest.api.jaxrs.provider.PowerAuthAuthenticationProvider; -import io.getlime.security.powerauth.rest.api.jaxrs.service.v3.TokenService; -import io.getlime.security.powerauth.rest.api.model.request.v3.EciesEncryptedRequest; -import io.getlime.security.powerauth.rest.api.model.request.v3.TokenRemoveRequest; -import io.getlime.security.powerauth.rest.api.model.response.v3.EciesEncryptedResponse; -import io.getlime.security.powerauth.rest.api.model.response.v3.TokenRemoveResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import java.util.Arrays; - -/** - * Controller responsible for publishing services related to simple token-based authentication. - * - * @author Roman Strobl, roman.strobl@wultra.com - */ -@Path("pa/v3/token") -@Produces(MediaType.APPLICATION_JSON) -public class TokenController { - - private static final Logger logger = LoggerFactory.getLogger(TokenController.class); - - @Context - private HttpServletRequest httpServletRequest; - - @Inject - private TokenService tokenServiceV3; - - @Inject - private PowerAuthAuthenticationProvider authenticationProvider; - - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @Path("create") - public EciesEncryptedResponse createToken(EciesEncryptedRequest request, - @HeaderParam(PowerAuthTokenHttpHeader.HEADER_NAME) String tokenHeader, - @HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthAuthenticationException { - - if (request == null) { - logger.warn("Invalid request object in create token"); - throw new PowerAuthInvalidRequestException(); - } - // Verify request signature before creating token - PowerAuthApiAuthentication authentication = authenticationProvider.validateRequestSignature( - httpServletRequest, "/pa/token/create", authHeader, - Arrays.asList( - PowerAuthSignatureTypes.POSSESSION, - PowerAuthSignatureTypes.POSSESSION_KNOWLEDGE, - PowerAuthSignatureTypes.POSSESSION_BIOMETRY, - PowerAuthSignatureTypes.POSSESSION_KNOWLEDGE_BIOMETRY - )); - if (authentication == null || authentication.getActivationId() == null) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - if (!"3.0".equals(authentication.getVersion()) && !"3.1".equals(authentication.getVersion())) { - logger.warn("Endpoint does not support PowerAuth protocol version {}", authentication.getVersion()); - throw new PowerAuthInvalidRequestException(); - } - if (request.getNonce() == null && !"3.0".equals(authentication.getVersion())) { - logger.warn("Missing nonce in ECIES request data"); - throw new PowerAuthInvalidRequestException(); - } - return tokenServiceV3.createToken(request, authentication); - } - - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @Path("remove") - public ObjectResponse removeToken(ObjectRequest request, - @HeaderParam(PowerAuthTokenHttpHeader.HEADER_NAME) String tokenHeader, - @HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthAuthenticationException { - if (request.getRequestObject() == null) { - logger.warn("Invalid request object in remove token"); - throw new PowerAuthInvalidRequestException(); - } - - // Verify request signature before removing token - PowerAuthApiAuthentication authentication = authenticationProvider.validateRequestSignature( - httpServletRequest, "/pa/token/remove", authHeader, - Arrays.asList( - PowerAuthSignatureTypes.POSSESSION, - PowerAuthSignatureTypes.POSSESSION_KNOWLEDGE, - PowerAuthSignatureTypes.POSSESSION_BIOMETRY, - PowerAuthSignatureTypes.POSSESSION_KNOWLEDGE_BIOMETRY - )); - - if (authentication == null || authentication.getActivationId() == null) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - if (!"3.0".equals(authentication.getVersion()) && !"3.1".equals(authentication.getVersion())) { - logger.warn("Endpoint does not support PowerAuth protocol version {}", authentication.getVersion()); - throw new PowerAuthInvalidRequestException(); - } - TokenRemoveResponse response = tokenServiceV3.removeToken(request.getRequestObject(), authentication); - return new ObjectResponse<>(response); - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/UpgradeController.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/UpgradeController.java deleted file mode 100644 index 75f8005e..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/controller/v3/UpgradeController.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.controller.v3; - -import io.getlime.core.rest.model.base.response.Response; -import io.getlime.security.powerauth.http.PowerAuthEncryptionHttpHeader; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.http.validator.InvalidPowerAuthHttpHeaderException; -import io.getlime.security.powerauth.http.validator.PowerAuthEncryptionHttpHeaderValidator; -import io.getlime.security.powerauth.http.validator.PowerAuthSignatureHttpHeaderValidator; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthUpgradeException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthInvalidRequestException; -import io.getlime.security.powerauth.rest.api.jaxrs.service.v3.UpgradeService; -import io.getlime.security.powerauth.rest.api.model.request.v3.EciesEncryptedRequest; -import io.getlime.security.powerauth.rest.api.model.response.v3.EciesEncryptedResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - -/** - * Controller responsible for upgrade. - * - *

PowerAuth protocol versions: - *

    - *
  • 3.0
  • - *
- * - * @author Roman Strobl, roman.strobl@wultra - */ -@Path("pa/v3/upgrade") -@Produces(MediaType.APPLICATION_JSON) -public class UpgradeController { - - private static final Logger logger = LoggerFactory.getLogger(UpgradeController.class); - - @Context - private HttpServletRequest httpServletRequest; - - @Inject - private UpgradeService upgradeService; - - /** - * Start upgrade of activation to version 3. - * - * @param request ECIES encrypted request. - * @param encryptionHeader Encryption HTTP header. - * @return ECIES encrypted response. - * @throws PowerAuthUpgradeException In case upgrade fails. - */ - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @Path("start") - public EciesEncryptedResponse upgradeStart(EciesEncryptedRequest request, - @HeaderParam(PowerAuthEncryptionHttpHeader.HEADER_NAME) String encryptionHeader) throws PowerAuthUpgradeException { - - - if (request == null) { - logger.warn("Invalid request object in upgrade start"); - throw new PowerAuthUpgradeException(); - } - - // Parse the encryption header - PowerAuthEncryptionHttpHeader header = new PowerAuthEncryptionHttpHeader().fromValue(encryptionHeader); - - // Validate the encryption header - try { - PowerAuthEncryptionHttpHeaderValidator.validate(header); - } catch (InvalidPowerAuthHttpHeaderException ex) { - logger.warn("Encryption HTTP header validation failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthUpgradeException(); - } - - if (!"3.0".equals(header.getVersion()) && !"3.1".equals(header.getVersion())) { - logger.warn("Endpoint does not support PowerAuth protocol version {}", header.getVersion()); - throw new PowerAuthUpgradeException(); - } - - if (request.getNonce() == null && !"3.0".equals(header.getVersion())) { - logger.warn("Missing nonce in ECIES request data"); - throw new PowerAuthUpgradeException(); - } - - return upgradeService.upgradeStart(request, header); - } - - /** - * Commit upgrade of activation to version 3. - * - * @param signatureHeader PowerAuth signature HTTP header. - * @return Response. - * @throws PowerAuthAuthenticationException In case request signature is invalid. - * @throws PowerAuthUpgradeException In case commit fails. - */ - @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - @Path("commit") - public Response upgradeCommit(@HeaderParam(PowerAuthSignatureHttpHeader.HEADER_NAME) String signatureHeader) throws PowerAuthAuthenticationException, PowerAuthUpgradeException { - - // Parse the signature header - PowerAuthSignatureHttpHeader header = new PowerAuthSignatureHttpHeader().fromValue(signatureHeader); - - // Validate the signature header - try { - PowerAuthSignatureHttpHeaderValidator.validate(header); - } catch (InvalidPowerAuthHttpHeaderException ex) { - logger.warn("Signature HTTP header validation failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthUpgradeException(); - } - - if (!"3.0".equals(header.getVersion()) && !"3.1".equals(header.getVersion())) { - logger.warn("Endpoint does not support PowerAuth protocol version {}", header.getVersion()); - throw new PowerAuthInvalidRequestException(); - } - - return upgradeService.upgradeCommit(signatureHeader, httpServletRequest); - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/converter/v2/SignatureTypeConverter.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/converter/v2/SignatureTypeConverter.java deleted file mode 100644 index 4a781994..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/converter/v2/SignatureTypeConverter.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.converter.v2; - -import com.wultra.security.powerauth.client.v2.PowerAuthPortV2ServiceStub; -import io.getlime.security.powerauth.crypto.lib.enums.PowerAuthSignatureTypes; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Helper class to convert from and to - * {@link com.wultra.security.powerauth.client.v2.PowerAuthPortV2ServiceStub.SignatureType} class. - * - * @author Petr Dvorak, petr@wultra.com - */ -public class SignatureTypeConverter { - - private static final Logger logger = LoggerFactory.getLogger(SignatureTypeConverter.class); - - /** - * Convert {@link com.wultra.security.powerauth.client.v2.PowerAuthPortV2ServiceStub.SignatureType} - * from a {@link String} value. - * @param signatureTypeString String value representing signature type. - * @return Signature type. - */ - public PowerAuthPortV2ServiceStub.SignatureType convertFrom(String signatureTypeString) { - - // Return null value which represents an unknown signature type - if (signatureTypeString == null) { - return null; - } - - // Try to convert signature type - try { - signatureTypeString = signatureTypeString.toUpperCase(); - return PowerAuthPortV2ServiceStub.SignatureType.Factory.fromValue(signatureTypeString); - } catch (IllegalArgumentException ex) { - logger.warn("Invalid signature type, error: {}", ex.getMessage()); - logger.debug("Error details", ex); - // Return null value which represents an unknown signature type - return null; - } - - } - - /** - * Convert {@link com.wultra.security.powerauth.client.v2.PowerAuthPortV2ServiceStub.SignatureType} from - * {@link PowerAuthSignatureTypes}. - * @param powerAuthSignatureTypes Signature type from crypto representation. - * @return Signature type. - */ - public PowerAuthPortV2ServiceStub.SignatureType convertFrom(PowerAuthSignatureTypes powerAuthSignatureTypes) { - if (powerAuthSignatureTypes == null) { - return null; - } - switch (powerAuthSignatureTypes) { - case POSSESSION: - return PowerAuthPortV2ServiceStub.SignatureType.POSSESSION; - case KNOWLEDGE: - return PowerAuthPortV2ServiceStub.SignatureType.KNOWLEDGE; - case BIOMETRY: - return PowerAuthPortV2ServiceStub.SignatureType.BIOMETRY; - case POSSESSION_KNOWLEDGE: - return PowerAuthPortV2ServiceStub.SignatureType.POSSESSION_KNOWLEDGE; - case POSSESSION_BIOMETRY: - return PowerAuthPortV2ServiceStub.SignatureType.POSSESSION_BIOMETRY; - default: - return null; - } - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/converter/v3/SignatureTypeConverter.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/converter/v3/SignatureTypeConverter.java deleted file mode 100644 index 1fbaf985..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/converter/v3/SignatureTypeConverter.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.converter.v3; - -import com.wultra.security.powerauth.client.v3.PowerAuthPortV3ServiceStub; -import io.getlime.security.powerauth.crypto.lib.enums.PowerAuthSignatureTypes; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Helper class to convert from and to - * {@link PowerAuthPortV3ServiceStub.SignatureType} class. - * - * @author Petr Dvorak, petr@wultra.com - */ -public class SignatureTypeConverter { - - private static final Logger logger = LoggerFactory.getLogger(SignatureTypeConverter.class); - - /** - * Convert {@link PowerAuthPortV3ServiceStub.SignatureType} - * from a {@link String} value. - * @param signatureTypeString String value representing signature type. - * @return Signature type. - */ - public PowerAuthPortV3ServiceStub.SignatureType convertFrom(String signatureTypeString) { - - // Return null value which represents an unknown signature type - if (signatureTypeString == null) { - return null; - } - - // Try to convert signature type - try { - signatureTypeString = signatureTypeString.toUpperCase(); - return PowerAuthPortV3ServiceStub.SignatureType.Factory.fromValue(signatureTypeString); - } catch (IllegalArgumentException ex) { - logger.warn("Invalid signature type, error: {}", ex.getMessage()); - logger.debug("Error details", ex); - // Return null value which represents an unknown signature type - return null; - } - - } - - /** - * Convert {@link PowerAuthPortV3ServiceStub.SignatureType} from - * {@link PowerAuthSignatureTypes}. - * @param powerAuthSignatureTypes Signature type from crypto representation. - * @return Signature type. - */ - public PowerAuthPortV3ServiceStub.SignatureType convertFrom(PowerAuthSignatureTypes powerAuthSignatureTypes) { - if (powerAuthSignatureTypes == null) { - return null; - } - switch (powerAuthSignatureTypes) { - case POSSESSION: - return PowerAuthPortV3ServiceStub.SignatureType.POSSESSION; - case KNOWLEDGE: - return PowerAuthPortV3ServiceStub.SignatureType.KNOWLEDGE; - case BIOMETRY: - return PowerAuthPortV3ServiceStub.SignatureType.BIOMETRY; - case POSSESSION_KNOWLEDGE: - return PowerAuthPortV3ServiceStub.SignatureType.POSSESSION_KNOWLEDGE; - case POSSESSION_BIOMETRY: - return PowerAuthPortV3ServiceStub.SignatureType.POSSESSION_BIOMETRY; - default: - return null; - } - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/encryption/EncryptorFactory.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/encryption/EncryptorFactory.java deleted file mode 100644 index d3c43f37..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/encryption/EncryptorFactory.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.encryption; - -import com.wultra.security.powerauth.client.v2.PowerAuthPortV2ServiceStub; -import io.getlime.core.rest.model.base.request.ObjectRequest; -import io.getlime.security.powerauth.rest.api.base.encryption.PowerAuthNonPersonalizedEncryptor; -import io.getlime.security.powerauth.rest.api.model.entity.NonPersonalizedEncryptedPayloadModel; -import io.getlime.security.powerauth.soap.axis.client.PowerAuthServiceClient; - -import javax.ejb.Stateless; -import javax.inject.Inject; -import java.rmi.RemoteException; - -/** - * Class responsible for building encryptors. - * - * @author Petr Dvorak, petr@wultra.com - */ -@Stateless -public class EncryptorFactory { - - @Inject - private PowerAuthServiceClient powerAuthClient; - - public EncryptorFactory() { - } - - /** - * Return a new instance of a non-personalized encryptor. - * @param object Request object to be used to initialize a new encryptor. - * @return New instance of a non-personalized encryptor. - * @throws RemoteException In case a SOAP exception occurs. - */ - public PowerAuthNonPersonalizedEncryptor buildNonPersonalizedEncryptor(ObjectRequest object) throws RemoteException { - return this.buildNonPersonalizedEncryptor( - object.getRequestObject().getApplicationKey(), - object.getRequestObject().getSessionIndex(), - object.getRequestObject().getEphemeralPublicKey() - ); - } - - /** - * Return a new instance of a non-personalized encryptor. - * @param applicationKeyBase64 Application key associated with an application master key used for encryption. - * @param sessionIndexBase64 Session index. - * @param ephemeralPublicKeyBase64 Ephemeral public key. - * @return New instance of a non-personalized encryptor. - * @throws RemoteException In case a SOAP exception occurs. - */ - public PowerAuthNonPersonalizedEncryptor buildNonPersonalizedEncryptor(String applicationKeyBase64, String sessionIndexBase64, String ephemeralPublicKeyBase64) throws RemoteException { - final PowerAuthPortV2ServiceStub.GetNonPersonalizedEncryptionKeyResponse encryptionKeyResponse = powerAuthClient.v2().generateNonPersonalizedE2EEncryptionKey( - applicationKeyBase64, - ephemeralPublicKeyBase64, - sessionIndexBase64 - ); - return new PowerAuthNonPersonalizedEncryptor( - encryptionKeyResponse.getApplicationKey(), - encryptionKeyResponse.getEncryptionKey(), encryptionKeyResponse.getEncryptionKeyIndex(), - encryptionKeyResponse.getEphemeralPublicKey() - ); - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthActivationExceptionResolver.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthActivationExceptionResolver.java deleted file mode 100644 index a583cf9d..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthActivationExceptionResolver.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.exception; - -import io.getlime.core.rest.model.base.response.ErrorResponse; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthActivationException; - -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; - -/** - * Class responsible for PowerAuth Standard RESTful API exception handling for - * exceptions that are raised during the activation phase. - * - * @author Petr Dvorak, petr@wultra.com - */ -public class PowerAuthActivationExceptionResolver implements ExceptionMapper { - - @Override - public Response toResponse(PowerAuthActivationException ex) { - return Response - .status(Response.Status.BAD_REQUEST) - .entity(new ErrorResponse(ex.getDefaultCode(), ex.getDefaultError())) - .build(); - } -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthAuthenticationExceptionResolver.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthAuthenticationExceptionResolver.java deleted file mode 100644 index 9d3d73a5..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthAuthenticationExceptionResolver.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.exception; - -import io.getlime.core.rest.model.base.response.ErrorResponse; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; - -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; -import javax.ws.rs.ext.Provider; - -/** - * Class responsible for PowerAuth Standard RESTful API exception handling for - * exceptions raised during the authentication phase. - * - * @author Petr Dvorak, petr@wultra.com - */ -@Provider -public class PowerAuthAuthenticationExceptionResolver implements ExceptionMapper { - - @Override - public Response toResponse(PowerAuthAuthenticationException ex) { - return Response - .status(Response.Status.UNAUTHORIZED) - .entity(new ErrorResponse(ex.getDefaultCode(), ex.getDefaultError())) - .build(); - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthEncryptionExceptionResolver.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthEncryptionExceptionResolver.java deleted file mode 100644 index d77bcfbf..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthEncryptionExceptionResolver.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.exception; - -import io.getlime.core.rest.model.base.response.ErrorResponse; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthEncryptionException; - -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; - -/** - * Class responsible for PowerAuth Standard RESTful API exception handling for - * exceptions that are raised during encryption or decryption. - * - * @author Roman Strobl, roman.strobl@wultra.com - */ -public class PowerAuthEncryptionExceptionResolver implements ExceptionMapper { - - @Override - public Response toResponse(PowerAuthEncryptionException ex) { - return Response - .status(Response.Status.BAD_REQUEST) - .entity(new ErrorResponse(ex.getDefaultCode(), ex.getDefaultError())) - .build(); - } -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthRecoveryExceptionResolver.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthRecoveryExceptionResolver.java deleted file mode 100644 index de2098aa..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthRecoveryExceptionResolver.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2019 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.exception; - -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthRecoveryException; -import io.getlime.security.powerauth.rest.api.model.exception.RecoveryErrorResponse; - -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; - -/** - * Class responsible for PowerAuth Standard RESTful API exception handling for - * exceptions that are raised during the recovery phase. - * - * @author Roman Strobl, roman.strobl@wultra.com - */ -public class PowerAuthRecoveryExceptionResolver implements ExceptionMapper { - - @Override - public Response toResponse(PowerAuthRecoveryException ex) { - return Response - .status(Response.Status.BAD_REQUEST) - .entity(new RecoveryErrorResponse(ex.getErrorCode(), ex.getDefaultError(), ex.getCurrentRecoveryPukIndex())) - .build(); - } -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthSecureVaultExceptionResolver.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthSecureVaultExceptionResolver.java deleted file mode 100644 index 52af952f..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthSecureVaultExceptionResolver.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.exception; - -import io.getlime.core.rest.model.base.response.ErrorResponse; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthSecureVaultException; - -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; - -/** - * Class responsible for PowerAuth Standard RESTful API exception handling for - * exceptions that are raised during the vault unlocking phase. - * - * @author Petr Dvorak, petr@wultra.com - */ -public class PowerAuthSecureVaultExceptionResolver implements ExceptionMapper { - - @Override - public Response toResponse(PowerAuthSecureVaultException ex) { - return Response - .status(Response.Status.BAD_REQUEST) - .entity(new ErrorResponse(ex.getDefaultCode(), ex.getDefaultError())) - .build(); - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthUpgradeExceptionResolver.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthUpgradeExceptionResolver.java deleted file mode 100644 index 4cdf0d90..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/exception/PowerAuthUpgradeExceptionResolver.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.getlime.security.powerauth.rest.api.jaxrs.exception; - -import io.getlime.core.rest.model.base.response.ErrorResponse; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthUpgradeException; - -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; - -/** - * Class responsible for PowerAuth Standard RESTful API exception handling for - * exceptions that are raised during the activation upgrade. - * - * @author Roman Strobl, roman.strobl@wultra.com - */ -public class PowerAuthUpgradeExceptionResolver implements ExceptionMapper { - - @Override - public Response toResponse(PowerAuthUpgradeException ex) { - return Response - .status(Response.Status.BAD_REQUEST) - .entity(new ErrorResponse(ex.getDefaultCode(), ex.getDefaultError())) - .build(); - } -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/filter/PowerAuthRequestFilter.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/filter/PowerAuthRequestFilter.java deleted file mode 100644 index 5085ac02..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/filter/PowerAuthRequestFilter.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.filter; - -import io.getlime.security.powerauth.rest.api.base.filter.PowerAuthRequestFilterBase; -import io.getlime.security.powerauth.rest.api.base.filter.ResettableStreamHttpServletRequest; - -import javax.annotation.Priority; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Priorities; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.core.Context; -import javax.ws.rs.ext.Provider; -import java.io.IOException; - -/** - * Request filter that intercepts the request body, forwards it to the controller - * as a request attribute named "X-PowerAuth-Request-Body" and resets the stream. - * - * @author Petr Dvorak, petr@wultra.com - * - */ -@Provider -@Priority(Priorities.AUTHENTICATION) -public class PowerAuthRequestFilter implements ContainerRequestFilter { - - @Context - private HttpServletRequest httpRequest; - - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - // WORKAROUND: fix issues with @FormParam annotations - httpRequest.getParameterMap(); - - final ResettableStreamHttpServletRequest httpServletRequest = PowerAuthRequestFilterBase.filterRequest(httpRequest); - requestContext.setEntityStream(httpServletRequest.getInputStream()); - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/provider/PowerAuthAuthenticationProvider.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/provider/PowerAuthAuthenticationProvider.java deleted file mode 100644 index d35674b9..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/provider/PowerAuthAuthenticationProvider.java +++ /dev/null @@ -1,329 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.provider; - -import com.google.common.io.BaseEncoding; -import com.wultra.security.powerauth.client.v3.PowerAuthPortV3ServiceStub; -import io.getlime.security.powerauth.crypto.lib.enums.PowerAuthSignatureTypes; -import io.getlime.security.powerauth.http.PowerAuthHttpBody; -import io.getlime.security.powerauth.http.PowerAuthHttpHeader; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.http.PowerAuthTokenHttpHeader; -import io.getlime.security.powerauth.http.validator.InvalidPowerAuthHttpHeaderException; -import io.getlime.security.powerauth.http.validator.PowerAuthSignatureHttpHeaderValidator; -import io.getlime.security.powerauth.http.validator.PowerAuthTokenHttpHeaderValidator; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthAuthentication; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthSignatureAuthentication; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthTokenAuthentication; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.*; -import io.getlime.security.powerauth.rest.api.base.provider.PowerAuthAuthenticationProviderBase; -import io.getlime.security.powerauth.rest.api.jaxrs.authentication.PowerAuthApiAuthenticationImpl; -import io.getlime.security.powerauth.rest.api.jaxrs.authentication.PowerAuthSignatureAuthenticationImpl; -import io.getlime.security.powerauth.rest.api.jaxrs.authentication.PowerAuthTokenAuthenticationImpl; -import io.getlime.security.powerauth.rest.api.jaxrs.converter.v3.SignatureTypeConverter; -import io.getlime.security.powerauth.soap.axis.client.PowerAuthServiceClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ejb.Stateless; -import javax.inject.Inject; -import java.rmi.RemoteException; -import java.util.Arrays; -import java.util.List; - -/** - * Implementation of PowerAuth authentication provider. - * - * @author Petr Dvorak - * - */ -@Stateless -public class PowerAuthAuthenticationProvider extends PowerAuthAuthenticationProviderBase { - - private static final Logger logger = LoggerFactory.getLogger(PowerAuthAuthenticationProvider.class); - - @Inject - private PowerAuthServiceClient powerAuthClient; - - public PowerAuthAuthenticationProvider() { - } - - public PowerAuthApiAuthentication authenticate(PowerAuthAuthentication authentication) throws PowerAuthAuthenticationException, RemoteException { - // Handle signature based authentications - if (authentication instanceof PowerAuthSignatureAuthentication) { - return validateSignatureAuthentication((PowerAuthSignatureAuthentication) authentication); - } - // Handle basic token-based authentications - else if (authentication instanceof PowerAuthTokenAuthentication) { - return validateTokenAuthentication((PowerAuthTokenAuthentication) authentication); - } - // Return null in case unknown authentication type is provided - return null; - } - - /** - * Validate signature based authentication. - * - * @param authentication Signature based authentication object. - * @return API authentication object in case of successful authentication, null otherwise. - * @throws PowerAuthAuthenticationException In case signature type is invalid. - * @throws RemoteException In case remote communication fails. - */ - private PowerAuthApiAuthentication validateSignatureAuthentication(PowerAuthSignatureAuthentication authentication) throws PowerAuthAuthenticationException, RemoteException { - if (authentication.getSignatureType() != null) { - - SignatureTypeConverter converter = new SignatureTypeConverter(); - final PowerAuthPortV3ServiceStub.SignatureType signatureType = converter.convertFrom(authentication.getSignatureType()); - if (signatureType == null) { - logger.warn("Invalid signature type: {}", authentication.getSignatureType()); - throw new PowerAuthSignatureTypeInvalidException(); - } - - PowerAuthPortV3ServiceStub.VerifySignatureRequest soapRequest = new PowerAuthPortV3ServiceStub.VerifySignatureRequest(); - soapRequest.setActivationId(authentication.getActivationId()); - soapRequest.setApplicationKey(authentication.getApplicationKey()); - soapRequest.setSignature(authentication.getSignature()); - soapRequest.setSignatureType(signatureType); - soapRequest.setSignatureVersion(authentication.getVersion()); - soapRequest.setData(PowerAuthHttpBody.getSignatureBaseString( - authentication.getHttpMethod(), - authentication.getRequestUri(), - authentication.getNonce(), - authentication.getData() - )); - - // In case forced signature version is specified, use it in the SOAP request - if (authentication.getForcedSignatureVersion() != null) { - soapRequest.setForcedSignatureVersion(authentication.getForcedSignatureVersion()); - } - - PowerAuthPortV3ServiceStub.VerifySignatureResponse soapResponse = powerAuthClient.verifySignature(soapRequest); - - if (soapResponse.getSignatureValid()) { - return copyAuthenticationAttributes(soapResponse.getActivationId(), soapResponse.getUserId(), - soapResponse.getApplicationId(), Arrays.asList(soapResponse.getApplicationRoles()), Arrays.asList(soapResponse.getActivationFlags()), - PowerAuthSignatureTypes.getEnumFromString(soapResponse.getSignatureType().getValue()), - authentication.getVersion(), authentication.getHttpHeader()); - } else { - return null; - } - - } else { - return null; - } - } - - /** - * Validate basic token-based authentication. - * - * @param authentication Token based authentication object. - * @return API authentication object in case of successful authentication, null otherwise. - */ - private PowerAuthApiAuthentication validateTokenAuthentication(PowerAuthTokenAuthentication authentication) throws RemoteException { - - PowerAuthPortV3ServiceStub.ValidateTokenRequest soapRequest = new PowerAuthPortV3ServiceStub.ValidateTokenRequest(); - soapRequest.setTokenId(authentication.getTokenId()); - soapRequest.setTokenDigest(authentication.getTokenDigest()); - soapRequest.setNonce(authentication.getNonce()); - soapRequest.setTimestamp(Long.valueOf(authentication.getTimestamp())); - - try { - final PowerAuthPortV3ServiceStub.ValidateTokenResponse soapResponse = powerAuthClient.validateToken(soapRequest); - if (soapResponse.getTokenValid()) { - return copyAuthenticationAttributes(soapResponse.getActivationId(), soapResponse.getUserId(), - soapResponse.getApplicationId(), Arrays.asList(soapResponse.getApplicationRoles()), Arrays.asList(soapResponse.getActivationFlags()), - PowerAuthSignatureTypes.getEnumFromString(soapResponse.getSignatureType().getValue()), - authentication.getVersion(), authentication.getHttpHeader()); - } else { - return null; - } - } catch (Exception ex) { - logger.warn("Token validation failed, error: {}", ex.getMessage()); - logger.debug("Error details", ex); - return null; - } - } - - /** - * Prepare API initialized authentication object with provided authentication attributes. - * - * @param activationId Activation ID. - * @param userId User ID. - * @param applicationId Application ID. - * @param applicationRoles Application roles. - * @param activationFlags Activation flags. - * @param signatureType Signature Type. - * @param version PowerAuth protocol version. - * @param httpHeader Raw PowerAuth HTTP header. - * @return Initialized instance of API authentication. - */ - private PowerAuthApiAuthentication copyAuthenticationAttributes(String activationId, String userId, Long applicationId, List applicationRoles, - List activationFlags, PowerAuthSignatureTypes signatureType, String version, - PowerAuthHttpHeader httpHeader) { - PowerAuthApiAuthentication apiAuthentication = new PowerAuthApiAuthenticationImpl(); - apiAuthentication.setActivationId(activationId); - apiAuthentication.setUserId(userId); - apiAuthentication.setApplicationId(applicationId); - apiAuthentication.setApplicationRoles(applicationRoles); - apiAuthentication.setActivationFlags(activationFlags); - apiAuthentication.setSignatureFactors(signatureType); - apiAuthentication.setVersion(version); - apiAuthentication.setHttpHeader(httpHeader); - return apiAuthentication; - } - - /** - * Validate the signature from the PowerAuth HTTP header against the provided HTTP method, request body and URI identifier. - * Make sure to accept only allowed signatures. - * @param httpMethod HTTP method (GET, POST, ...) - * @param httpBody Body of the HTTP request. - * @param requestUriIdentifier Request URI identifier. - * @param httpAuthorizationHeader PowerAuth HTTP authorization header. - * @param allowedSignatureTypes Allowed types of the signature. - * @param forcedSignatureVersion Forced signature version during upgrade. - * @return Instance of a PowerAuthApiAuthenticationImpl on successful authorization. - * @throws PowerAuthAuthenticationException In case authorization fails, exception is raised. - */ - public PowerAuthApiAuthentication validateRequestSignature( - String httpMethod, - byte[] httpBody, - String requestUriIdentifier, - String httpAuthorizationHeader, - List allowedSignatureTypes, - Integer forcedSignatureVersion - ) throws PowerAuthAuthenticationException { - - // Check for HTTP PowerAuth signature header - if (httpAuthorizationHeader == null || httpAuthorizationHeader.equals("undefined")) { - logger.warn("Signature HTTP header is missing"); - throw new PowerAuthHeaderMissingException(); - } - - // Parse HTTP header - PowerAuthSignatureHttpHeader header = new PowerAuthSignatureHttpHeader().fromValue(httpAuthorizationHeader); - - // Validate the header - try { - PowerAuthSignatureHttpHeaderValidator.validate(header); - } catch (InvalidPowerAuthHttpHeaderException ex) { - logger.warn("Signature HTTP header validation failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthSignatureInvalidException(); - } - - // Check if the signature type is allowed - PowerAuthSignatureTypes expectedSignatureType = PowerAuthSignatureTypes.getEnumFromString(header.getSignatureType()); - if (expectedSignatureType == null || !allowedSignatureTypes.contains(expectedSignatureType)) { - logger.warn("Invalid signature type: {}", expectedSignatureType); - throw new PowerAuthSignatureTypeInvalidException(); - } - - // Configure PowerAuth authentication object - PowerAuthSignatureAuthentication powerAuthAuthentication = new PowerAuthSignatureAuthenticationImpl(); - powerAuthAuthentication.setActivationId(header.getActivationId()); - powerAuthAuthentication.setApplicationKey(header.getApplicationKey()); - powerAuthAuthentication.setNonce(BaseEncoding.base64().decode(header.getNonce())); - powerAuthAuthentication.setSignatureType(header.getSignatureType()); - powerAuthAuthentication.setSignature(header.getSignature()); - powerAuthAuthentication.setHttpMethod(httpMethod); - powerAuthAuthentication.setRequestUri(requestUriIdentifier); - powerAuthAuthentication.setData(httpBody); - powerAuthAuthentication.setVersion(header.getVersion()); - powerAuthAuthentication.setHttpHeader(header); - powerAuthAuthentication.setForcedSignatureVersion(forcedSignatureVersion); - - // Call the authentication - PowerAuthApiAuthentication auth; - try { - auth = this.authenticate(powerAuthAuthentication); - } catch (RemoteException ex) { - logger.warn("Remote communication failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthSignatureErrorException(); - } - - // In case authentication is null, throw PowerAuth exception - if (auth == null) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - - return auth; - } - - @Override - public PowerAuthApiAuthentication validateToken(String tokenHeader, List allowedSignatureTypes) throws PowerAuthAuthenticationException { - - // Check for HTTP PowerAuth signature header - if (tokenHeader == null || tokenHeader.equals("undefined")) { - logger.warn("Token HTTP header is missing"); - throw new PowerAuthHeaderMissingException(); - } - - // Parse HTTP header - PowerAuthTokenHttpHeader header = new PowerAuthTokenHttpHeader().fromValue(tokenHeader); - - // Validate the header - try { - PowerAuthTokenHttpHeaderValidator.validate(header); - } catch (InvalidPowerAuthHttpHeaderException ex) { - logger.warn("Token validation failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthTokenInvalidException(); - } - - // Prepare authentication object - PowerAuthTokenAuthentication powerAuthTokenAuthentication = new PowerAuthTokenAuthenticationImpl(); - powerAuthTokenAuthentication.setTokenId(header.getTokenId()); - powerAuthTokenAuthentication.setTokenDigest(header.getTokenDigest()); - powerAuthTokenAuthentication.setNonce(header.getNonce()); - powerAuthTokenAuthentication.setTimestamp(header.getTimestamp()); - powerAuthTokenAuthentication.setVersion(header.getVersion()); - powerAuthTokenAuthentication.setHttpHeader(header); - - // Call the authentication based on token authentication object - final PowerAuthApiAuthentication auth; - try { - auth = this.authenticate(powerAuthTokenAuthentication); - } catch (RemoteException ex) { - logger.warn("Remote communication failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthTokenErrorException(); - } - - // In case authentication is null, throw PowerAuth exception - if (auth == null) { - logger.debug("Invalid token value"); - throw new PowerAuthTokenInvalidException(); - } - - // Check if the signature type is allowed - PowerAuthSignatureTypes expectedSignatureType = auth.getSignatureFactors(); - if (expectedSignatureType == null || !allowedSignatureTypes.contains(expectedSignatureType)) { - logger.warn("Invalid signature type in token validation: {}", expectedSignatureType); - throw new PowerAuthSignatureTypeInvalidException(); - } - - return auth; - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/provider/PowerAuthEncryptionProvider.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/provider/PowerAuthEncryptionProvider.java deleted file mode 100644 index d43f4bb9..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/provider/PowerAuthEncryptionProvider.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.provider; - -import com.wultra.security.powerauth.client.v3.PowerAuthPortV3ServiceStub; -import io.getlime.security.powerauth.rest.api.base.encryption.PowerAuthEciesDecryptorParameters; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthEncryptionException; -import io.getlime.security.powerauth.rest.api.base.provider.PowerAuthEncryptionProviderBase; -import io.getlime.security.powerauth.soap.axis.client.PowerAuthServiceClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ejb.Stateless; -import javax.inject.Inject; -import java.rmi.RemoteException; - -/** - * Implementation of PowerAuth encryption provider. - * - * @author Roman Strobl, roman.strobl@wultra.com - * - */ -@Stateless -public class PowerAuthEncryptionProvider extends PowerAuthEncryptionProviderBase { - - private static final Logger logger = LoggerFactory.getLogger(PowerAuthEncryptionProvider.class); - - @Inject - private PowerAuthServiceClient powerAuthClient; - - @Override - public PowerAuthEciesDecryptorParameters getEciesDecryptorParameters(String activationId, String applicationKey, String ephemeralPublicKey) throws PowerAuthEncryptionException { - try { - PowerAuthPortV3ServiceStub.GetEciesDecryptorRequest eciesDecryptorRequest = new PowerAuthPortV3ServiceStub.GetEciesDecryptorRequest(); - eciesDecryptorRequest.setActivationId(activationId); - eciesDecryptorRequest.setApplicationKey(applicationKey); - eciesDecryptorRequest.setEphemeralPublicKey(ephemeralPublicKey); - PowerAuthPortV3ServiceStub.GetEciesDecryptorResponse eciesDecryptorResponse = powerAuthClient.getEciesDecryptor(eciesDecryptorRequest); - return new PowerAuthEciesDecryptorParameters(eciesDecryptorResponse.getSecretKey(), eciesDecryptorResponse.getSharedInfo2()); - } catch (RemoteException ex) { - logger.warn("Get ECIES decryptor call failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthEncryptionException(); - } - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v2/ActivationService.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v2/ActivationService.java deleted file mode 100644 index bd89b832..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v2/ActivationService.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.service.v2; - -import com.wultra.security.powerauth.client.v2.PowerAuthPortV2ServiceStub; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthActivationException; -import io.getlime.security.powerauth.rest.api.model.request.v2.ActivationCreateRequest; -import io.getlime.security.powerauth.rest.api.model.response.v2.ActivationCreateResponse; -import io.getlime.security.powerauth.soap.axis.client.PowerAuthServiceClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ejb.Stateless; -import javax.inject.Inject; - -/** - * Service implementing activation functionality. - * - *

PowerAuth protocol versions: - *

    - *
  • 2.0
  • - *
  • 2.1
  • - *
- * - * @author Roman Strobl, roman.strobl@wultra.com - * - */ -@Stateless(name = "ActivationServiceV2") -public class ActivationService { - - @Inject - private PowerAuthServiceClient powerAuthClient; - - private static final Logger logger = LoggerFactory.getLogger(ActivationService.class); - - /** - * Create activation. - * @param request Create activation request. - * @return Create activation response. - * @throws PowerAuthActivationException In case create activation fails. - */ - public ActivationCreateResponse createActivation(ActivationCreateRequest request) throws PowerAuthActivationException { - try { - String activationIDShort = request.getActivationIdShort(); - String activationNonce = request.getActivationNonce(); - String cDevicePublicKey = request.getEncryptedDevicePublicKey(); - String activationName = request.getActivationName(); - String extras = request.getExtras(); - String applicationKey = request.getApplicationKey(); - String applicationSignature = request.getApplicationSignature(); - String clientEphemeralKey = request.getEphemeralPublicKey(); - - PowerAuthPortV2ServiceStub.PrepareActivationResponse soapResponse = powerAuthClient.v2().prepareActivation( - activationIDShort, - activationName, - activationNonce, - clientEphemeralKey, - cDevicePublicKey, - extras, - applicationKey, - applicationSignature - ); - - ActivationCreateResponse response = new ActivationCreateResponse(); - response.setActivationId(soapResponse.getActivationId()); - response.setActivationNonce(soapResponse.getActivationNonce()); - response.setEncryptedServerPublicKey(soapResponse.getEncryptedServerPublicKey()); - response.setEncryptedServerPublicKeySignature(soapResponse.getEncryptedServerPublicKeySignature()); - response.setEphemeralPublicKey(soapResponse.getEphemeralPublicKey()); - - return response; - } catch (Exception ex) { - logger.warn("Creating PowerAuth activation failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthActivationException(); - } - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v2/SecureVaultService.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v2/SecureVaultService.java deleted file mode 100644 index d1336bc4..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v2/SecureVaultService.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.service.v2; - -import com.google.common.io.BaseEncoding; -import com.wultra.security.powerauth.client.v2.PowerAuthPortV2ServiceStub; -import io.getlime.security.powerauth.http.PowerAuthHttpBody; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.http.validator.InvalidPowerAuthHttpHeaderException; -import io.getlime.security.powerauth.http.validator.PowerAuthSignatureHttpHeaderValidator; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthSecureVaultException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureInvalidException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureTypeInvalidException; -import io.getlime.security.powerauth.rest.api.jaxrs.converter.v2.SignatureTypeConverter; -import io.getlime.security.powerauth.rest.api.jaxrs.provider.PowerAuthAuthenticationProvider; -import io.getlime.security.powerauth.rest.api.model.request.v2.VaultUnlockRequest; -import io.getlime.security.powerauth.rest.api.model.response.v2.VaultUnlockResponse; -import io.getlime.security.powerauth.soap.axis.client.PowerAuthServiceClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ejb.Stateless; -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; - -/** - * Service implementing secure vault functionality. - * - *

PowerAuth protocol versions: - *

    - *
  • 2.0
  • - *
  • 2.1
  • - *
- * - * @author Roman Strobl, roman.strobl@wultra.com - * - */ -@Stateless(name = "SecureVaultServiceV2") -public class SecureVaultService { - - private static final Logger logger = LoggerFactory.getLogger(SecureVaultService.class); - - @Inject - private PowerAuthServiceClient powerAuthClient; - - @Inject - private PowerAuthAuthenticationProvider authenticationProvider; - - /** - * Unlock secure vault. - * @param signatureHeader PowerAuth signature HTTP header. - * @param request Vault unlock request. - * @param httpServletRequest HTTP servlet request. - * @return Vault unlock response. - * @throws PowerAuthSecureVaultException In case vault unlock fails. - * @throws PowerAuthAuthenticationException In case authentication fails. - */ - public VaultUnlockResponse vaultUnlock(String signatureHeader, - VaultUnlockRequest request, - HttpServletRequest httpServletRequest) throws PowerAuthSecureVaultException, PowerAuthAuthenticationException { - try { - // Parse the header - PowerAuthSignatureHttpHeader header = new PowerAuthSignatureHttpHeader().fromValue(signatureHeader); - - // Validate the header - try { - PowerAuthSignatureHttpHeaderValidator.validate(header); - } catch (InvalidPowerAuthHttpHeaderException ex) { - logger.warn("Signature HTTP header validation failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthSignatureInvalidException(); - } - - SignatureTypeConverter converter = new SignatureTypeConverter(); - - String activationId = header.getActivationId(); - String applicationId = header.getApplicationKey(); - String signature = header.getSignature(); - PowerAuthPortV2ServiceStub.SignatureType signatureType = converter.convertFrom(header.getSignatureType()); - if (signatureType == null) { - logger.warn("Invalid signature type: {}", header.getSignatureType()); - throw new PowerAuthSignatureTypeInvalidException(); - } - - String nonce = header.getNonce(); - - String reason = null; - byte[] requestBodyBytes; - - if ("2.0".equals(header.getVersion())) { - // Version 2.0 requires null data in signature for vault unlock. - requestBodyBytes = null; - } else if ("2.1".equals(header.getVersion())) { - // Version 2.1 or higher requires request data in signature (POST request body) for vault unlock. - if (request != null) { - // Send vault unlock reason, in case it is available. - if (request.getReason() != null) { - reason = request.getReason(); - } - } - - // Use POST request body as data for signature. - requestBodyBytes = authenticationProvider.extractRequestBodyBytes(httpServletRequest); - } else { - logger.warn("Invalid protocol version in secure vault: {}", header.getVersion()); - throw new PowerAuthSecureVaultException(); - } - - String data = PowerAuthHttpBody.getSignatureBaseString("POST", "/pa/vault/unlock", BaseEncoding.base64().decode(nonce), requestBodyBytes); - - PowerAuthPortV2ServiceStub.VaultUnlockResponse soapResponse = powerAuthClient.v2().unlockVault(activationId, applicationId, data, signature, signatureType, reason); - - if (!soapResponse.getSignatureValid()) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - - VaultUnlockResponse response = new VaultUnlockResponse(); - response.setActivationId(soapResponse.getActivationId()); - response.setEncryptedVaultEncryptionKey(soapResponse.getEncryptedVaultEncryptionKey()); - - return response; - } catch (PowerAuthAuthenticationException ex) { - throw ex; - } catch (Exception ex) { - logger.warn("PowerAuth vault unlock failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthSecureVaultException(); - } - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v2/TokenService.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v2/TokenService.java deleted file mode 100644 index 22d001b3..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v2/TokenService.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.service.v2; - -import com.wultra.security.powerauth.client.v2.PowerAuthPortV2ServiceStub; -import io.getlime.security.powerauth.crypto.lib.enums.PowerAuthSignatureTypes; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureTypeInvalidException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthTokenErrorException; -import io.getlime.security.powerauth.rest.api.jaxrs.converter.v2.SignatureTypeConverter; -import io.getlime.security.powerauth.rest.api.model.request.v2.TokenCreateRequest; -import io.getlime.security.powerauth.rest.api.model.response.v2.TokenCreateResponse; -import io.getlime.security.powerauth.soap.axis.client.PowerAuthServiceClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ejb.Stateless; -import javax.inject.Inject; - -/** - * Service implementing token functionality. - * - *

PowerAuth protocol versions: - *

    - *
  • 2.0
  • - *
  • 2.1
  • - *
- * - * @author Roman Strobl, roman.strobl@wultra.com - * - */ -@Stateless(name = "TokenServiceV2") -public class TokenService { - - private static final Logger logger = LoggerFactory.getLogger(TokenService.class); - - @Inject - private PowerAuthServiceClient powerAuthClient; - - /** - * Create token. - * @param request Create token request. - * @param authentication PowerAuth API authentication. - * @return Create token response. - * @throws PowerAuthAuthenticationException In case token could not be created. - */ - public TokenCreateResponse createToken(TokenCreateRequest request, PowerAuthApiAuthentication authentication) throws PowerAuthAuthenticationException { - try { - // Fetch activation ID and signature type - final String activationId = authentication.getActivationId(); - final PowerAuthSignatureTypes signatureFactors = authentication.getSignatureFactors(); - - // Fetch data from the request - final String ephemeralPublicKey = request.getEphemeralPublicKey(); - - // Prepare a signature type converter - SignatureTypeConverter converter = new SignatureTypeConverter(); - - // Convert signature type - PowerAuthPortV2ServiceStub.SignatureType signatureType = converter.convertFrom(signatureFactors); - if (signatureType == null) { - logger.warn("Invalid signature type: {}", signatureFactors); - throw new PowerAuthSignatureTypeInvalidException(); - } - - // Create a token - final PowerAuthPortV2ServiceStub.CreateTokenResponse token = powerAuthClient.v2().createToken(activationId, ephemeralPublicKey, signatureType); - - // Prepare a response - final TokenCreateResponse response = new TokenCreateResponse(); - response.setMac(token.getMac()); - response.setEncryptedData(token.getEncryptedData()); - return response; - } catch (Exception ex) { - logger.warn("Creating PowerAuth token failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthTokenErrorException(); - } - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/ActivationService.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/ActivationService.java deleted file mode 100644 index 7b026c56..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/ActivationService.java +++ /dev/null @@ -1,434 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.service.v3; - -import com.wultra.security.powerauth.client.v3.PowerAuthPortV3ServiceStub; -import io.getlime.security.powerauth.rest.api.base.application.PowerAuthApplicationConfiguration; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.encryption.PowerAuthEciesEncryption; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthActivationException; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthRecoveryException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthInvalidRequestException; -import io.getlime.security.powerauth.rest.api.base.provider.CustomActivationProvider; -import io.getlime.security.powerauth.rest.api.model.entity.ActivationType; -import io.getlime.security.powerauth.rest.api.model.request.v3.ActivationLayer1Request; -import io.getlime.security.powerauth.rest.api.model.request.v3.ActivationStatusRequest; -import io.getlime.security.powerauth.rest.api.model.request.v3.EciesEncryptedRequest; -import io.getlime.security.powerauth.rest.api.model.response.v3.ActivationLayer1Response; -import io.getlime.security.powerauth.rest.api.model.response.v3.ActivationRemoveResponse; -import io.getlime.security.powerauth.rest.api.model.response.v3.ActivationStatusResponse; -import io.getlime.security.powerauth.rest.api.model.response.v3.EciesEncryptedResponse; -import io.getlime.security.powerauth.soap.axis.client.PowerAuthServiceClient; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.soap.SOAPFaultDetail; -import org.apache.axis2.AxisFault; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ejb.Stateless; -import javax.inject.Inject; -import java.time.Instant; -import java.util.*; - -/** - * Service implementing activation functionality. - * - *

PowerAuth protocol versions: - *

    - *
  • 3.0
  • - *
- * - * @author Roman Strobl, roman.strobl@wultra.com - */ -@Stateless(name = "ActivationServiceV3") -public class ActivationService { - - @Inject - private PowerAuthServiceClient powerAuthClient; - - @Inject - private PowerAuthApplicationConfiguration applicationConfiguration; - - @Inject - private CustomActivationProvider activationProvider; - - private static final Logger logger = LoggerFactory.getLogger(ActivationService.class); - - /** - * Create activation. - * - * @param request Create activation layer 1 request. - * @param eciesEncryption PowerAuth ECIES encryption object. - * @return Create activation layer 1 response. - * @throws PowerAuthActivationException In case create activation fails. - * @throws PowerAuthRecoveryException In case activation recovery fails. - */ - public ActivationLayer1Response createActivation(ActivationLayer1Request request, PowerAuthEciesEncryption eciesEncryption) throws PowerAuthActivationException, PowerAuthRecoveryException { - try { - - final String applicationKey = eciesEncryption.getContext().getApplicationKey(); - final EciesEncryptedRequest activationData = request.getActivationData(); - final String ephemeralPublicKey = activationData.getEphemeralPublicKey(); - final String encryptedData = activationData.getEncryptedData(); - final String mac = activationData.getMac(); - final String nonce = activationData.getNonce(); - final Map identity = request.getIdentityAttributes(); - final Map customAttributes = (request.getCustomAttributes() != null) ? request.getCustomAttributes() : new HashMap<>(); - - // Validate inner encryption - if (nonce == null && !"3.0".equals(eciesEncryption.getContext().getVersion())) { - logger.warn("Missing nonce for protocol version: {}", eciesEncryption.getContext().getVersion()); - throw new PowerAuthActivationException(); - } - - switch (request.getType()) { - // Regular activation which uses "code" identity attribute - case CODE: { - - // Check if identity attributes are present - if (identity == null || identity.isEmpty()) { - logger.warn("Identity attributes are missing for code activation"); - throw new PowerAuthActivationException(); - } - - // Extract data from request and encryption object - String activationCode = identity.get("code"); - - if (activationCode == null || activationCode.isEmpty()) { - logger.warn("Activation code is missing"); - throw new PowerAuthActivationException(); - } - - // Call PrepareActivation SOAP method on PA server - PowerAuthPortV3ServiceStub.PrepareActivationResponse response = powerAuthClient.prepareActivation(activationCode, applicationKey, ephemeralPublicKey, encryptedData, mac, nonce); - - // Create context for passing parameters between activation provider calls - Map context = new LinkedHashMap<>(); - - Map processedCustomAttributes = customAttributes; - // In case a custom activation provider is enabled, process custom attributes and save any flags - if (activationProvider != null) { - processedCustomAttributes = activationProvider.processCustomActivationAttributes(customAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.CODE, context); - List activationFlags = activationProvider.getActivationFlags(identity, processedCustomAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.CODE, context); - if (activationFlags != null && !activationFlags.isEmpty()) { - powerAuthClient.addActivationFlags(response.getActivationId(), activationFlags); - } - } - - boolean notifyActivationCommit = false; - if (response.getActivationStatus() == PowerAuthPortV3ServiceStub.ActivationStatus.ACTIVE) { - // Activation was committed instantly due to presence of Activation OTP. - notifyActivationCommit = true; - } else { - // Otherwise check if activation should be committed instantly and if yes, perform commit. - if (activationProvider != null && activationProvider.shouldAutoCommitActivation(identity, customAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.CODE, context)) { - PowerAuthPortV3ServiceStub.CommitActivationResponse commitResponse = powerAuthClient.commitActivation(response.getActivationId(), null); - notifyActivationCommit = commitResponse.getActivated(); - } - } - // Notify activation provider about an activation commit. - if (activationProvider != null && notifyActivationCommit) { - activationProvider.activationWasCommitted(identity, customAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.CODE, context); - } - - // Prepare and return encrypted response - return prepareEncryptedResponse(response.getEncryptedData(), response.getMac(), processedCustomAttributes); - } - - // Custom activation - case CUSTOM: { - // Check if there is a custom activation provider available, return an error in case it is not available - if (activationProvider == null) { - logger.warn("Activation provider is not available"); - throw new PowerAuthActivationException(); - } - - // Check if identity attributes are present - if (identity == null || identity.isEmpty()) { - logger.warn("Identity attributes are missing for custom activation"); - throw new PowerAuthActivationException(); - } - - // Create context for passing parameters between activation provider calls - Map context = new LinkedHashMap<>(); - - // Lookup user ID using a provided identity attributes - String userId = activationProvider.lookupUserIdForAttributes(identity, context); - - // If no user was found or user ID is invalid, return an error - if (userId == null || userId.equals("") || userId.length() > 255) { - logger.warn("Invalid user ID: {}", userId); - throw new PowerAuthActivationException(); - } - - // Resolve maxFailedCount and activationExpireTimestamp parameters, null value means use value configured on PowerAuth server - final Integer maxFailed = activationProvider.getMaxFailedAttemptCount(identity, customAttributes, userId, ActivationType.CUSTOM, context); - final Long maxFailedCount = maxFailed == null ? null : maxFailed.longValue(); - final Long activationValidityPeriod = activationProvider.getValidityPeriodDuringActivation(identity, customAttributes, userId, ActivationType.CUSTOM, context); - Date activationExpireTimestamp = null; - if (activationValidityPeriod != null) { - Instant now = Instant.now(); - Instant expiration = now.plusMillis(activationValidityPeriod); - activationExpireTimestamp = Date.from(expiration); - } - - // Create activation for a looked up user and application related to the given application key - PowerAuthPortV3ServiceStub.CreateActivationResponse response = powerAuthClient.createActivation( - userId, - activationExpireTimestamp, - maxFailedCount, - applicationKey, - ephemeralPublicKey, - encryptedData, - mac, - nonce - ); - - // Process custom attributes using a custom logic - final Map processedCustomAttributes = activationProvider.processCustomActivationAttributes(customAttributes, response.getActivationId(), userId, response.getApplicationId(), ActivationType.CUSTOM, context); - - // Save activation flags in case the provider specified any flags - List activationFlags = activationProvider.getActivationFlags(identity, processedCustomAttributes, response.getActivationId(), userId, response.getApplicationId(), ActivationType.CUSTOM, context); - if (activationFlags != null && !activationFlags.isEmpty()) { - powerAuthClient.addActivationFlags(response.getActivationId(), activationFlags); - } - - // Check if activation should be committed instantly and if yes, perform commit - if (activationProvider.shouldAutoCommitActivation(identity, customAttributes, response.getActivationId(), userId, response.getApplicationId(), ActivationType.CUSTOM, context)) { - PowerAuthPortV3ServiceStub.CommitActivationResponse commitResponse = powerAuthClient.commitActivation(response.getActivationId(), null); - if (commitResponse.getActivated()) { - activationProvider.activationWasCommitted(identity, customAttributes, response.getActivationId(), userId, response.getApplicationId(), ActivationType.CUSTOM, context); - } - } - - // Prepare encrypted activation data - EciesEncryptedResponse encryptedActivationData = new EciesEncryptedResponse(response.getEncryptedData(), response.getMac()); - - // Prepare the created activation response data - ActivationLayer1Response responseL1 = new ActivationLayer1Response(); - responseL1.setCustomAttributes(processedCustomAttributes); - responseL1.setActivationData(encryptedActivationData); - - // Return response - return responseL1; - } - - // Activation using recovery code - case RECOVERY: { - - // Check if identity attributes are present - if (identity == null || identity.isEmpty()) { - logger.warn("Identity attributes are missing for activation recovery"); - throw new PowerAuthActivationException(); - } - - // Extract data from request and encryption object - String recoveryCode = identity.get("recoveryCode"); - String recoveryPuk = identity.get("puk"); - - if (recoveryCode == null || recoveryCode.isEmpty()) { - logger.warn("Recovery code is missing"); - throw new PowerAuthActivationException(); - } - - if (recoveryPuk == null || recoveryPuk.isEmpty()) { - logger.warn("Recovery PUK is missing"); - throw new PowerAuthActivationException(); - } - - // Create context for passing parameters between activation provider calls - Map context = new LinkedHashMap<>(); - - // Resolve maxFailedCount, user ID is not known - Long maxFailedCount = null; - if (activationProvider != null) { - final Integer maxFailed = activationProvider.getMaxFailedAttemptCount(identity, customAttributes, null, ActivationType.RECOVERY, context); - maxFailedCount = maxFailed == null ? null : maxFailed.longValue(); - } - - // Call RecoveryCodeActivation SOAP method on PA server - PowerAuthPortV3ServiceStub.RecoveryCodeActivationResponse response = powerAuthClient.createActivationUsingRecoveryCode(recoveryCode, recoveryPuk, applicationKey, maxFailedCount, ephemeralPublicKey, encryptedData, mac, nonce); - - Map processedCustomAttributes = customAttributes; - // In case a custom activation provider is enabled, process custom attributes and save any flags - if (activationProvider != null) { - processedCustomAttributes = activationProvider.processCustomActivationAttributes(customAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.RECOVERY, context); - List activationFlags = activationProvider.getActivationFlags(identity, processedCustomAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.RECOVERY, context); - if (activationFlags != null && !activationFlags.isEmpty()) { - powerAuthClient.addActivationFlags(response.getActivationId(), activationFlags); - } - } - - // Automatically commit activation by default, the optional activation provider can override automatic commit - if (activationProvider == null || activationProvider.shouldAutoCommitActivation(identity, customAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.RECOVERY, context)) { - PowerAuthPortV3ServiceStub.CommitActivationResponse commitResponse = powerAuthClient.commitActivation(response.getActivationId(), null); - if (activationProvider != null && commitResponse.getActivated()) { - activationProvider.activationWasCommitted(identity, customAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.RECOVERY, context); - } - } - - // Prepare and return encrypted response - return prepareEncryptedResponse(response.getEncryptedData(), response.getMac(), processedCustomAttributes); - } - - default: - logger.warn("Invalid activation request"); - throw new PowerAuthInvalidRequestException(); - } - } catch (AxisFault ex) { - if (ex.getFaultDetailElement() != null) { - handleInvalidRecoveryError(ex.getFaultDetailElement()); - } - logger.warn("Creating PowerAuth activation failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthActivationException(); - } catch (PowerAuthActivationException ex) { - // Do not swallow PowerAuthActivationException for custom activations. - // See: https://github.com/wultra/powerauth-restful-integration/issues/199 - logger.warn("Creating PowerAuth activation failed, error: {}", ex.getMessage()); - throw ex; - } catch (Exception ex) { - logger.warn("Creating PowerAuth activation failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthActivationException(); - } - } - - /** - * Get activation status. - * - * @param request Activation status request. - * @return Activation status response. - * @throws PowerAuthActivationException In case retrieving activation status fails. - */ - public ActivationStatusResponse getActivationStatus(ActivationStatusRequest request) throws PowerAuthActivationException { - try { - String activationId = request.getActivationId(); - String challenge = request.getChallenge(); - PowerAuthPortV3ServiceStub.GetActivationStatusResponse soapResponse = powerAuthClient.getActivationStatusWithEncryptedStatusBlob(activationId, challenge); - ActivationStatusResponse response = new ActivationStatusResponse(); - response.setActivationId(soapResponse.getActivationId()); - response.setEncryptedStatusBlob(soapResponse.getEncryptedStatusBlob()); - response.setNonce(soapResponse.getEncryptedStatusBlobNonce()); - if (applicationConfiguration != null) { - response.setCustomObject(applicationConfiguration.statusServiceCustomObject()); - } - return response; - } catch (Exception ex) { - logger.warn("PowerAuth activation status check failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthActivationException(); - } - } - - /** - * Remove activation. - * - * @param apiAuthentication PowerAuth API authentication object. - * @return Activation remove response. - * @throws PowerAuthActivationException In case remove activation fails. - */ - public ActivationRemoveResponse removeActivation(PowerAuthApiAuthentication apiAuthentication) throws PowerAuthActivationException { - try { - - // Fetch context information - final String activationId = apiAuthentication.getActivationId(); - final String userId = apiAuthentication.getUserId(); - final Long applicationId = apiAuthentication.getApplicationId(); - - // Call other application specific cleanup logic - final PowerAuthPortV3ServiceStub.RemoveActivationResponse soapResponse; - if (activationProvider != null) { - final boolean revokeCodes = activationProvider.shouldRevokeRecoveryCodeOnRemove(activationId, userId, applicationId); - soapResponse = powerAuthClient.removeActivation(activationId, null, revokeCodes); - activationProvider.activationWasRemoved(activationId, userId, applicationId); - } else { - soapResponse = powerAuthClient.removeActivation(activationId, null); // do not revoke recovery codes - } - - // Prepare and return the response - ActivationRemoveResponse response = new ActivationRemoveResponse(); - response.setActivationId(soapResponse.getActivationId()); - return response; - } catch (Exception ex) { - logger.warn("PowerAuth activation removal failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthActivationException(); - } - } - - /** - * Handle SOAP fault for recovery error which may contain additional details about current recovery PUK index. - * @param faultDetail SOAP fault detail. - * @throws PowerAuthRecoveryException Thrown in case recovery error is handled using this method. - */ - private void handleInvalidRecoveryError(SOAPFaultDetail faultDetail) throws PowerAuthRecoveryException { - String errorCode = null; - String errorMessage = null; - Integer currentRecoveryPukIndex = null; - Iterator iter = faultDetail.getAllDetailEntries(); - while (iter.hasNext()) { - OMElement node = (OMElement) iter.next(); - switch (node.getLocalName()) { - case "errorCode": - errorCode = node.getText(); - break; - case "localizedMessage": - errorMessage = node.getText(); - break; - case "currentRecoveryPukIndex": - try { - currentRecoveryPukIndex = Integer.parseInt(node.getText()); - } catch (NumberFormatException ex) { - logger.warn("Invalid puk index, error: {}", ex.getMessage()); - logger.debug("Error details", ex); - // Ignore invalid index - } - break; - } - } - if ("ERR0028".equals(errorCode)) { - logger.debug("Invalid recovery code, current PUK index: {}", currentRecoveryPukIndex); - throw new PowerAuthRecoveryException(errorMessage, "INVALID_RECOVERY_CODE", currentRecoveryPukIndex); - } - } - - /** - * Prepare payload for the encrypted response. - * - * @param encryptedData Encrypted data. - * @param mac MAC code of the encrypted data. - * @param processedCustomAttributes Custom attributes to be returned. - * @return Encrypted response object. - */ - private ActivationLayer1Response prepareEncryptedResponse(String encryptedData, String mac, Map processedCustomAttributes) { - // Prepare encrypted response object for layer 2 - EciesEncryptedResponse encryptedResponseL2 = new EciesEncryptedResponse(); - encryptedResponseL2.setEncryptedData(encryptedData); - encryptedResponseL2.setMac(mac); - - // The response is encrypted once more before sent to client using ResponseBodyAdvice - ActivationLayer1Response responseL1 = new ActivationLayer1Response(); - responseL1.setCustomAttributes(processedCustomAttributes); - responseL1.setActivationData(encryptedResponseL2); - return responseL1; - } - -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/RecoveryService.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/RecoveryService.java deleted file mode 100644 index 54b7eb57..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/RecoveryService.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2019 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.service.v3; - -import com.wultra.security.powerauth.client.v3.PowerAuthPortV3ServiceStub; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthInvalidRequestException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthRecoveryConfirmationException; -import io.getlime.security.powerauth.rest.api.model.request.v3.EciesEncryptedRequest; -import io.getlime.security.powerauth.rest.api.model.response.v3.EciesEncryptedResponse; -import io.getlime.security.powerauth.soap.axis.client.PowerAuthServiceClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ejb.Stateless; -import javax.inject.Inject; - -/** - * Service implementing recovery functionality. - * - *

PowerAuth protocol versions: - *

    - *
  • 3.0
  • - *
- * - * @author Roman Strobl, roman.strobl@wultra.com - */ -@Stateless() -public class RecoveryService { - - @Inject - private PowerAuthServiceClient powerAuthClient; - - private static final Logger logger = LoggerFactory.getLogger(RecoveryService.class); - - /** - * Confirm recovery code. - * @param request ECIES encrypted request. - * @param authentication PowerAuth API authentication object. - * @return ECIES encrypted response. - * @throws PowerAuthAuthenticationException In case confirm recovery fails. - */ - public EciesEncryptedResponse confirmRecoveryCode(EciesEncryptedRequest request, - PowerAuthApiAuthentication authentication) throws PowerAuthAuthenticationException { - try { - final String activationId = authentication.getActivationId(); - final PowerAuthSignatureHttpHeader httpHeader = (PowerAuthSignatureHttpHeader) authentication.getHttpHeader(); - final String applicationKey = httpHeader.getApplicationKey(); - if (activationId == null || applicationKey == null || request.getEphemeralPublicKey() == null - || request.getEncryptedData() == null || request.getMac() == null) { - logger.warn("PowerAuth confirm recovery failed because of invalid request"); - throw new PowerAuthInvalidRequestException(); - } - PowerAuthPortV3ServiceStub.ConfirmRecoveryCodeResponse paResponse = powerAuthClient.confirmRecoveryCode(activationId, applicationKey, - request.getEphemeralPublicKey(), request.getEncryptedData(), request.getMac(), request.getNonce()); - if (!paResponse.getActivationId().equals(activationId)) { - logger.warn("PowerAuth confirm recovery failed because of invalid activation ID in response"); - throw new PowerAuthInvalidRequestException(); - } - return new EciesEncryptedResponse(paResponse.getEncryptedData(), paResponse.getMac()); - } catch (Exception ex) { - logger.warn("PowerAuth confirm recovery failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthRecoveryConfirmationException(); - } - } -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/SecureVaultService.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/SecureVaultService.java deleted file mode 100644 index e1a18cb0..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/SecureVaultService.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.service.v3; - -import com.google.common.io.BaseEncoding; -import com.wultra.security.powerauth.client.v3.PowerAuthPortV3ServiceStub; -import io.getlime.security.powerauth.http.PowerAuthHttpBody; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthSecureVaultException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureInvalidException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureTypeInvalidException; -import io.getlime.security.powerauth.rest.api.jaxrs.converter.v3.SignatureTypeConverter; -import io.getlime.security.powerauth.rest.api.jaxrs.provider.PowerAuthAuthenticationProvider; -import io.getlime.security.powerauth.rest.api.model.request.v3.EciesEncryptedRequest; -import io.getlime.security.powerauth.rest.api.model.response.v3.EciesEncryptedResponse; -import io.getlime.security.powerauth.soap.axis.client.PowerAuthServiceClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ejb.Stateless; -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; - -/** - * Service implementing secure vault functionality. - * - *

PowerAuth protocol versions: - *

    - *
  • 3.0
  • - *
- * - * @author Roman Strobl, roman.strobl@wultra.com - * - */ -@Stateless(name = "SecureVaultServiceV3") -public class SecureVaultService { - - @Inject - private PowerAuthServiceClient powerAuthClient; - - @Inject - private PowerAuthAuthenticationProvider authenticationProvider; - - private static final Logger logger = LoggerFactory.getLogger(SecureVaultService.class); - - /** - * Unlock secure vault. - * @param header PowerAuth signature HTTP header. - * @param request ECIES encrypted vault unlock request. - * @param httpServletRequest HTTP servlet request. - * @return ECIES encrypted vault unlock response. - * @throws PowerAuthSecureVaultException In case vault unlock request fails. - * @throws PowerAuthAuthenticationException In case authentication fails. - */ - public EciesEncryptedResponse vaultUnlock(PowerAuthSignatureHttpHeader header, - EciesEncryptedRequest request, - HttpServletRequest httpServletRequest) throws PowerAuthSecureVaultException, PowerAuthAuthenticationException { - try { - SignatureTypeConverter converter = new SignatureTypeConverter(); - - String activationId = header.getActivationId(); - String applicationKey = header.getApplicationKey(); - String signature = header.getSignature(); - PowerAuthPortV3ServiceStub.SignatureType signatureType = converter.convertFrom(header.getSignatureType()); - if (signatureType == null) { - logger.warn("Invalid signature type: {}", header.getSignatureType()); - throw new PowerAuthSignatureTypeInvalidException(); - } - - String signatureVersion = header.getVersion(); - String nonce = header.getNonce(); - - // Fetch data from the request - final String ephemeralPublicKey = request.getEphemeralPublicKey(); - final String encryptedData = request.getEncryptedData(); - final String mac = request.getMac(); - final String eciesNonce = request.getNonce(); - - // Prepare data for signature to allow signature verification on PowerAuth server - byte[] requestBodyBytes = authenticationProvider.extractRequestBodyBytes(httpServletRequest); - String data = PowerAuthHttpBody.getSignatureBaseString("POST", "/pa/vault/unlock", BaseEncoding.base64().decode(nonce), requestBodyBytes); - - // Verify signature and get encrypted vault encryption key from PowerAuth server - PowerAuthPortV3ServiceStub.VaultUnlockResponse soapResponse = powerAuthClient.unlockVault(activationId, applicationKey, signature, - signatureType, signatureVersion, data, ephemeralPublicKey, encryptedData, mac, eciesNonce); - - if (!soapResponse.getSignatureValid()) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - - return new EciesEncryptedResponse(soapResponse.getEncryptedData(), soapResponse.getMac()); - } catch (PowerAuthAuthenticationException ex) { - throw ex; - } catch (Exception ex) { - logger.warn("PowerAuth vault unlock failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthSecureVaultException(); - } - } -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/TokenService.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/TokenService.java deleted file mode 100644 index dd0293e3..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/TokenService.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.service.v3; - -import com.wultra.security.powerauth.client.v3.PowerAuthPortV3ServiceStub; -import io.getlime.security.powerauth.crypto.lib.enums.PowerAuthSignatureTypes; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureTypeInvalidException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthTokenErrorException; -import io.getlime.security.powerauth.rest.api.jaxrs.converter.v3.SignatureTypeConverter; -import io.getlime.security.powerauth.rest.api.model.request.v3.EciesEncryptedRequest; -import io.getlime.security.powerauth.rest.api.model.request.v3.TokenRemoveRequest; -import io.getlime.security.powerauth.rest.api.model.response.v3.EciesEncryptedResponse; -import io.getlime.security.powerauth.rest.api.model.response.v3.TokenRemoveResponse; -import io.getlime.security.powerauth.soap.axis.client.PowerAuthServiceClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ejb.Stateless; -import javax.inject.Inject; - -/** - * Service implementing token functionality. - * - *

PowerAuth protocol versions: - *

    - *
  • 3.0
  • - *
- * - * @author Roman Strobl, roman.strobl@wultra.com - */ -@Stateless(name = "TokenServiceV3") -public class TokenService { - - private static final Logger logger = LoggerFactory.getLogger(TokenService.class); - - @Inject - private PowerAuthServiceClient powerAuthClient; - - /** - * Create token. - * - * @param request ECIES encrypted create token request. - * @param authentication PowerAuth API authentication object. - * @return ECIES encrypted create token response. - * @throws PowerAuthAuthenticationException In case token could not be created. - */ - public EciesEncryptedResponse createToken(EciesEncryptedRequest request, - PowerAuthApiAuthentication authentication) - throws PowerAuthAuthenticationException { - try { - // Fetch activation ID and signature type - final PowerAuthSignatureTypes signatureFactors = authentication.getSignatureFactors(); - - // Fetch data from the request - final String ephemeralPublicKey = request.getEphemeralPublicKey(); - final String encryptedData = request.getEncryptedData(); - final String mac = request.getMac(); - final String nonce = request.getNonce(); - - // Prepare a signature type converter - SignatureTypeConverter converter = new SignatureTypeConverter(); - - // Convert signature type - PowerAuthPortV3ServiceStub.SignatureType signatureType = converter.convertFrom(signatureFactors); - if (signatureType == null) { - logger.warn("Invalid signature type: {}", signatureFactors); - throw new PowerAuthSignatureTypeInvalidException(); - } - - // Get ECIES headers - String activationId = authentication.getActivationId(); - PowerAuthSignatureHttpHeader httpHeader = (PowerAuthSignatureHttpHeader) authentication.getHttpHeader(); - String applicationKey = httpHeader.getApplicationKey(); - - // Create a token - final PowerAuthPortV3ServiceStub.CreateTokenResponse token = powerAuthClient.createToken(activationId, applicationKey, ephemeralPublicKey, - encryptedData, mac, nonce, signatureType); - - // Prepare a response - final EciesEncryptedResponse response = new EciesEncryptedResponse(); - response.setMac(token.getMac()); - response.setEncryptedData(token.getEncryptedData()); - return response; - } catch (Exception ex) { - logger.warn("Creating PowerAuth token failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthTokenErrorException(); - } - } - - /** - * Remove token. - * - * @param request Remove token request. - * @param authentication PowerAuth API authentication object. - * @return Remove token response. - * @throws PowerAuthAuthenticationException In case authentication fails. - */ - public TokenRemoveResponse removeToken(TokenRemoveRequest request, PowerAuthApiAuthentication authentication) throws PowerAuthAuthenticationException { - try { - // Fetch activation ID - final String activationId = authentication.getActivationId(); - - // Fetch token ID from the request - final String tokenId = request.getTokenId(); - - // Remove a token, ignore response, since the endpoint should quietly return - powerAuthClient.removeToken(tokenId, activationId); - - // Prepare a response - final TokenRemoveResponse response = new TokenRemoveResponse(); - response.setTokenId(tokenId); - return response; - } catch (Exception ex) { - logger.warn("Removing PowerAuth token failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthTokenErrorException(); - } - } -} diff --git a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/UpgradeService.java b/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/UpgradeService.java deleted file mode 100644 index 3091eef7..00000000 --- a/powerauth-restful-security-javaee/src/main/java/io/getlime/security/powerauth/rest/api/jaxrs/service/v3/UpgradeService.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.rest.api.jaxrs.service.v3; - -import com.wultra.security.powerauth.client.v3.PowerAuthPortV3ServiceStub; -import io.getlime.core.rest.model.base.response.Response; -import io.getlime.security.powerauth.crypto.lib.enums.PowerAuthSignatureTypes; -import io.getlime.security.powerauth.http.PowerAuthEncryptionHttpHeader; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthUpgradeException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthInvalidRequestException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureInvalidException; -import io.getlime.security.powerauth.rest.api.jaxrs.provider.PowerAuthAuthenticationProvider; -import io.getlime.security.powerauth.rest.api.model.request.v3.EciesEncryptedRequest; -import io.getlime.security.powerauth.rest.api.model.response.v3.EciesEncryptedResponse; -import io.getlime.security.powerauth.soap.axis.client.PowerAuthServiceClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ejb.Stateless; -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import java.util.Collections; -import java.util.List; - -/** - * Service implementing upgrade functionality. - * - *

PowerAuth protocol versions: - *

    - *
  • 3.0
  • - *
- * - * @author Roman Strobl, roman.strobl@wultra.com - * - */ -@Stateless -public class UpgradeService { - - private static final Logger logger = LoggerFactory.getLogger(UpgradeService.class); - - @Inject - private PowerAuthServiceClient powerAuthClient; - - @Inject - private PowerAuthAuthenticationProvider authenticationProvider; - - /** - * Start upgrade of activation to version 3. - * @param request ECIES encrypted upgrade start request. - * @param header PowerAuth encryption HTTP header. - * @return ECIES encrypted upgrade activation response. - * @throws PowerAuthUpgradeException In case upgrade start fails. - */ - public EciesEncryptedResponse upgradeStart(EciesEncryptedRequest request, PowerAuthEncryptionHttpHeader header) - throws PowerAuthUpgradeException { - - try { - // Fetch data from the request - final String ephemeralPublicKey = request.getEphemeralPublicKey(); - final String encryptedData = request.getEncryptedData(); - final String mac = request.getMac(); - final String nonce = request.getNonce(); - - // Get ECIES headers - final String activationId = header.getActivationId(); - final String applicationKey = header.getApplicationKey(); - - // Start upgrade on PowerAuth server - PowerAuthPortV3ServiceStub.StartUpgradeResponse upgradeResponse = powerAuthClient.startUpgrade(activationId, applicationKey, ephemeralPublicKey, encryptedData, mac, nonce); - - // Prepare a response - final EciesEncryptedResponse response = new EciesEncryptedResponse(); - response.setMac(upgradeResponse.getMac()); - response.setEncryptedData(upgradeResponse.getEncryptedData()); - return response; - } catch (Exception ex) { - logger.warn("PowerAuth upgrade start failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthUpgradeException(); - } - } - - /** - * Commit upgrade of activation to version 3. - * @param signatureHeader PowerAuth signature HTTP header. - * @param httpServletRequest HTTP servlet request. - * @return Commit upgrade response. - * @throws PowerAuthAuthenticationException in case authentication fails. - * @throws PowerAuthUpgradeException In case upgrade commit fails. - */ - public Response upgradeCommit(String signatureHeader, - HttpServletRequest httpServletRequest) - throws PowerAuthAuthenticationException, PowerAuthUpgradeException { - - try { - // Extract request body - byte[] requestBodyBytes = authenticationProvider.extractRequestBodyBytes(httpServletRequest); - if (requestBodyBytes == null || requestBodyBytes.length == 0) { - // Expected request body is {}, do not accept empty body - logger.warn("Empty request body"); - throw new PowerAuthInvalidRequestException(); - } - - // Verify signature, force signature version during upgrade to version 3 - List allowedSignatureTypes = Collections.singletonList(PowerAuthSignatureTypes.POSSESSION); - PowerAuthApiAuthentication authentication = authenticationProvider.validateRequestSignature("POST", requestBodyBytes, "/pa/upgrade/commit", signatureHeader, allowedSignatureTypes, 3); - - // In case signature verification fails, upgrade fails, too - if (authentication == null || authentication.getActivationId() == null) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - - // Get signature HTTP headers - final String activationId = authentication.getActivationId(); - final PowerAuthSignatureHttpHeader httpHeader = (PowerAuthSignatureHttpHeader) authentication.getHttpHeader(); - final String applicationKey = httpHeader.getApplicationKey(); - - // Commit upgrade on PowerAuth server - PowerAuthPortV3ServiceStub.CommitUpgradeResponse upgradeResponse = powerAuthClient.commitUpgrade(activationId, applicationKey); - - if (upgradeResponse.getCommitted()) { - return new Response(); - } else { - logger.debug("Upgrade commit failed"); - throw new PowerAuthUpgradeException(); - } - } catch (PowerAuthAuthenticationException ex) { - throw ex; - } catch (Exception ex) { - logger.warn("PowerAuth upgrade commit failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthUpgradeException(); - } - } -} diff --git a/powerauth-restful-security-spring-annotation/pom.xml b/powerauth-restful-security-spring-annotation/pom.xml index e33fc79a..d8f58463 100644 --- a/powerauth-restful-security-spring-annotation/pom.xml +++ b/powerauth-restful-security-spring-annotation/pom.xml @@ -24,14 +24,14 @@ 4.0.0 powerauth-restful-security-spring-annotation - 1.0.0 + 1.1.0-SNAPSHOT powerauth-restful-security-spring-annotation PowerAuth RESTful API Security Annotations for Spring io.getlime.security powerauth-restful-integration-parent - 1.0.0 + 1.1.0-SNAPSHOT ../pom.xml @@ -53,12 +53,12 @@ io.getlime.security powerauth-restful-security-base - 1.0.0 + 1.1.0-SNAPSHOT io.getlime.security - powerauth-java-client-spring - 1.0.0 + powerauth-rest-client-spring + 1.1.0-SNAPSHOT diff --git a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthAnnotationInterceptor.java b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthAnnotationInterceptor.java index dff48d98..abb648b8 100644 --- a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthAnnotationInterceptor.java +++ b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthAnnotationInterceptor.java @@ -19,6 +19,7 @@ */ package io.getlime.security.powerauth.rest.api.spring.annotation; +import io.getlime.security.powerauth.crypto.lib.enums.PowerAuthSignatureTypes; import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; import io.getlime.security.powerauth.http.PowerAuthTokenHttpHeader; import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; @@ -27,21 +28,28 @@ import io.getlime.security.powerauth.rest.api.base.model.PowerAuthRequestObjects; import io.getlime.security.powerauth.rest.api.spring.provider.PowerAuthAuthenticationProvider; import io.getlime.security.powerauth.rest.api.spring.provider.PowerAuthEncryptionProvider; +import org.apache.commons.text.StringSubstitutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.MethodParameter; +import org.springframework.lang.NonNull; import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; +import org.springframework.web.servlet.AsyncHandlerInterceptor; +import org.springframework.web.servlet.HandlerMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.util.ArrayList; import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; @Component -public class PowerAuthAnnotationInterceptor extends HandlerInterceptorAdapter { +public class PowerAuthAnnotationInterceptor implements AsyncHandlerInterceptor { private static final Logger logger = LoggerFactory.getLogger(PowerAuthAnnotationInterceptor.class); @@ -59,7 +67,7 @@ public void setEncryptionProvider(PowerAuthEncryptionProvider encryptionProvider } @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) { // Check if the provided handler is related to handler method. // This is to avoid issues with possible CORS requests )in case of @@ -67,7 +75,7 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons // requests before the actual requests. if (handler instanceof HandlerMethod) { - HandlerMethod handlerMethod = (HandlerMethod) handler; + final HandlerMethod handlerMethod = (HandlerMethod) handler; // Obtain annotations PowerAuth powerAuthSignatureAnnotation = handlerMethod.getMethodAnnotation(PowerAuth.class); @@ -84,7 +92,7 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons // Resolve @PowerAuthEncryption annotation. The order of processing is important, PowerAuth expects // sign-then-encrypt sequence in case both authorization and encryption are used. if (powerAuthEncryptionAnnotation != null) { - Class requestType = resolveGenericParameterTypeForEcies(handlerMethod); + final Class requestType = resolveGenericParameterTypeForEcies(handlerMethod); try { encryptionProvider.decryptRequest(request, requestType, powerAuthEncryptionAnnotation.scope()); // Encryption object is saved in HTTP servlet request by encryption provider, so that it is available for both Spring and Java EE @@ -96,28 +104,27 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons // Resolve @PowerAuth annotation if (powerAuthSignatureAnnotation != null) { - try { - PowerAuthApiAuthentication authentication = authenticationProvider.validateRequestSignature( - request, - powerAuthSignatureAnnotation.resourceId(), - request.getHeader(PowerAuthSignatureHttpHeader.HEADER_NAME), - new ArrayList<>(Arrays.asList(powerAuthSignatureAnnotation.signatureType())) + final String resourceId = expandResourceId(powerAuthSignatureAnnotation.resourceId(), request, handlerMethod); + final String header = request.getHeader(PowerAuthSignatureHttpHeader.HEADER_NAME); + final List signatureTypes = Arrays.asList(powerAuthSignatureAnnotation.signatureType()); + final PowerAuthApiAuthentication authentication = authenticationProvider.validateRequestSignature( + request, resourceId, header, signatureTypes ); request.setAttribute(PowerAuthRequestObjects.AUTHENTICATION_OBJECT, authentication); } catch (PowerAuthAuthenticationException ex) { logger.warn("Invalid request signature, authentication object was removed"); request.setAttribute(PowerAuthRequestObjects.AUTHENTICATION_OBJECT, null); } - } // Resolve @PowerAuthToken annotation if (powerAuthTokenAnnotation != null) { try { - PowerAuthApiAuthentication authentication = authenticationProvider.validateToken( - request.getHeader(PowerAuthTokenHttpHeader.HEADER_NAME), - new ArrayList<>(Arrays.asList(powerAuthTokenAnnotation.signatureType())) + final String header = request.getHeader(PowerAuthTokenHttpHeader.HEADER_NAME); + final List signatureTypes = Arrays.asList(powerAuthTokenAnnotation.signatureType()); + final PowerAuthApiAuthentication authentication = authenticationProvider.validateToken( + header, signatureTypes ); request.setAttribute(PowerAuthRequestObjects.AUTHENTICATION_OBJECT, authentication); } catch (PowerAuthAuthenticationException ex) { @@ -128,7 +135,7 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons } - return super.preHandle(request, response, handler); + return true; } /** @@ -147,4 +154,53 @@ private Class resolveGenericParameterTypeForEcies(HandlerMethod handlerMethod return Object.class; } + /** + * The method substitutes placeholders (marked via "${placeholder}") in resourceID attribute value by + * the actual parameters of the handler method. The implementation takes into account all method parameters + * that are annotated via @RequestParam or @PathVariable annotations and extracts values from the request + * parameter map. + * + * @param resourceId Resource ID with possible placeholders. + * @param request HttpServletRequest for the current execution. + * @param handlerMethod Handler method that is responsible for the request processing. + * @return Resource ID with substituted placeholders. + */ + @SuppressWarnings("unchecked") + private String expandResourceId(String resourceId, HttpServletRequest request, HandlerMethod handlerMethod) { + // Get method parameters that could be replaced in the context of resource ID + final Map parameters = new TreeMap<>(); + final MethodParameter[] methodParameters = handlerMethod.getMethodParameters(); + for (MethodParameter mp : methodParameters) { + // Handle parameters annotated by @RequestParam annotation. + // These are stored in the servlet request parameter map. + final RequestParam requestParam = mp.getParameterAnnotation(RequestParam.class); + if (requestParam != null) { + final String name = requestParam.name(); + final String value = request.getParameter(name); + if (value != null) { + parameters.put(name, value); + } + } else { + // Handle parameters annotated by @PathVariable annotation. + // These are stored by Spring in the servlet request attributes map, under a special + // URI_TEMPLATE_VARIABLES_ATTRIBUTE key that contains Map with path + // variable mapping. + final PathVariable pathVariable = mp.getParameterAnnotation(PathVariable.class); + if (pathVariable != null) { + final String name = pathVariable.name(); + final Map pathVariableMap = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); + if (pathVariableMap != null) { + final String value = pathVariableMap.get(name); + if (value != null) { + parameters.put(name, value); + } + } + } + } + } + // Substitute the placeholders + final StringSubstitutor sub = new StringSubstitutor(parameters); + return sub.replace(resourceId); + } + } diff --git a/powerauth-restful-security-spring/pom.xml b/powerauth-restful-security-spring/pom.xml index 429fce84..2684f6dd 100644 --- a/powerauth-restful-security-spring/pom.xml +++ b/powerauth-restful-security-spring/pom.xml @@ -24,14 +24,14 @@ 4.0.0 powerauth-restful-security-spring - 1.0.0 + 1.1.0-SNAPSHOT powerauth-restful-security-spring PowerAuth RESTful API Security Additions for Spring io.getlime.security powerauth-restful-integration-parent - 1.0.0 + 1.1.0-SNAPSHOT ../pom.xml @@ -41,12 +41,12 @@ io.getlime.security powerauth-restful-security-spring-annotation - 1.0.0 + 1.1.0-SNAPSHOT io.getlime.security powerauth-rest-client-spring - 1.0.0 + 1.1.0-SNAPSHOT diff --git a/powerauth-restful-server-javaee/META-INF/application.xml b/powerauth-restful-server-javaee/META-INF/application.xml deleted file mode 100644 index 64ef1f6f..00000000 --- a/powerauth-restful-server-javaee/META-INF/application.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - diff --git a/powerauth-restful-server-javaee/pom.xml b/powerauth-restful-server-javaee/pom.xml deleted file mode 100644 index 64cf8916..00000000 --- a/powerauth-restful-server-javaee/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - 4.0.0 - powerauth-restful-server-javaee - powerauth-restful-server-javaee - war - 1.0.0 - - - powerauth-restful-integration-parent - io.getlime.security - 1.0.0 - ../pom.xml - - - - - javax - javaee-api - ${javaee-api.version} - provided - - - io.getlime.security - powerauth-restful-security-javaee - 1.0.0 - - - org.bouncycastle - bcprov-jdk15on - ${bcprov.version} - provided - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - ${maven-deploy-plugin.version} - - true - - - - - - diff --git a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/JavaEEApplication.java b/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/JavaEEApplication.java deleted file mode 100644 index b0206ff3..00000000 --- a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/JavaEEApplication.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.app.rest.api.javaee; - -import io.getlime.security.powerauth.app.rest.api.javaee.configuration.DefaultJacksonJsonProvider; -import io.getlime.security.powerauth.app.rest.api.javaee.controller.AuthenticationController; -import io.getlime.security.powerauth.app.rest.api.javaee.controller.TokenController; -import io.getlime.security.powerauth.rest.api.jaxrs.exception.*; -import io.getlime.security.powerauth.rest.api.jaxrs.filter.PowerAuthRequestFilter; -import org.bouncycastle.jce.provider.BouncyCastleProvider; - -import javax.ws.rs.ApplicationPath; -import javax.ws.rs.core.Application; -import java.security.Security; -import java.util.HashSet; -import java.util.Set; - -/** - * PowerAuth Standard RESTful API application class. - * - * @author Petr Dvorak, petr@wultra.com - */ -@ApplicationPath("/") -public class JavaEEApplication extends Application { - - public JavaEEApplication() { - super(); - Security.addProvider(new BouncyCastleProvider()); - } - - @Override - public Set> getClasses() { - Set> resources = new HashSet<>(); - - // Jackson - resources.add(DefaultJacksonJsonProvider.class); - - // PowerAuth Controllers - resources.add(AuthenticationController.class); - resources.add(TokenController.class); - resources.add(io.getlime.security.powerauth.app.rest.api.javaee.controller.v2.CustomActivationController.class); - resources.add(io.getlime.security.powerauth.app.rest.api.javaee.controller.v2.EncryptedDataExchangeController.class); - resources.add(io.getlime.security.powerauth.app.rest.api.javaee.controller.v3.EncryptedDataExchangeController.class); - resources.add(io.getlime.security.powerauth.rest.api.jaxrs.controller.v2.ActivationController.class); - resources.add(io.getlime.security.powerauth.rest.api.jaxrs.controller.v2.SignatureController.class); - resources.add(io.getlime.security.powerauth.rest.api.jaxrs.controller.v2.SecureVaultController.class); - resources.add(io.getlime.security.powerauth.rest.api.jaxrs.controller.v2.TokenController.class); - resources.add(io.getlime.security.powerauth.rest.api.jaxrs.controller.v3.ActivationController.class); - resources.add(io.getlime.security.powerauth.rest.api.jaxrs.controller.v3.SecureVaultController.class); - resources.add(io.getlime.security.powerauth.rest.api.jaxrs.controller.v3.SignatureController.class); - resources.add(io.getlime.security.powerauth.rest.api.jaxrs.controller.v3.TokenController.class); - resources.add(io.getlime.security.powerauth.rest.api.jaxrs.controller.v3.UpgradeController.class); - resources.add(io.getlime.security.powerauth.rest.api.jaxrs.controller.v3.RecoveryController.class); - - // PowerAuth Exception Resolvers - resources.add(PowerAuthActivationExceptionResolver.class); - resources.add(PowerAuthRecoveryExceptionResolver.class); - resources.add(PowerAuthAuthenticationExceptionResolver.class); - resources.add(PowerAuthEncryptionExceptionResolver.class); - resources.add(PowerAuthSecureVaultExceptionResolver.class); - resources.add(PowerAuthUpgradeExceptionResolver.class); - - // PowerAuth Filters - resources.add(PowerAuthRequestFilter.class); - return resources; - } - -} diff --git a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/configuration/DefaultJacksonJsonProvider.java b/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/configuration/DefaultJacksonJsonProvider.java deleted file mode 100644 index 845459d7..00000000 --- a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/configuration/DefaultJacksonJsonProvider.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.app.rest.api.javaee.configuration; - -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - -import javax.ws.rs.ext.ContextResolver; -import javax.ws.rs.ext.Provider; - -/** - * Default provider for the RESTful request / response Jackson mapping. - * - * @author Petr Dvorak, petr@wultra.com - */ -@Provider -public class DefaultJacksonJsonProvider implements ContextResolver { - - private static final ObjectMapper MAPPER = new ObjectMapper(); - - static { - MAPPER.setSerializationInclusion(Include.NON_EMPTY); - MAPPER.disable(MapperFeature.USE_GETTERS_AS_SETTERS); - } - - public DefaultJacksonJsonProvider() { - } - - @Override - public ObjectMapper getContext(Class type) { - return MAPPER; - } -} \ No newline at end of file diff --git a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/configuration/PowerAuthBeanFactory.java b/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/configuration/PowerAuthBeanFactory.java deleted file mode 100644 index c3ccda51..00000000 --- a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/configuration/PowerAuthBeanFactory.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.app.rest.api.javaee.configuration; - -import io.getlime.security.powerauth.rest.api.base.application.PowerAuthApplicationConfiguration; -import io.getlime.security.powerauth.rest.api.jaxrs.application.DefaultApplicationConfiguration; -import io.getlime.security.powerauth.soap.axis.client.PowerAuthServiceClient; -import org.apache.axis2.AxisFault; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.enterprise.context.Dependent; -import javax.enterprise.inject.Produces; - -/** - * Class responsible for bean auto-wiring. - * - * @author Petr Dvorak, petr@wultra.com - */ -@Dependent -public class PowerAuthBeanFactory { - - private static final Logger logger = LoggerFactory.getLogger(PowerAuthBeanFactory.class); - - @Produces - public PowerAuthServiceClient buildClient() { - try { - return new PowerAuthServiceClient("http://localhost:8080/powerauth-java-server/soap"); - } catch (AxisFault ex) { - logger.warn("Failed to build client, error: {}", ex.getMessage()); - logger.debug("Error details", ex); - return null; - } - } - - @Produces - public PowerAuthApplicationConfiguration buildApplicationConfiguration() { - return new DefaultApplicationConfiguration(); - } - -} diff --git a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/AuthenticationController.java b/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/AuthenticationController.java deleted file mode 100644 index 7790f24d..00000000 --- a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/AuthenticationController.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.app.rest.api.javaee.controller; - -import io.getlime.core.rest.model.base.response.ObjectResponse; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureInvalidException; -import io.getlime.security.powerauth.rest.api.jaxrs.provider.PowerAuthAuthenticationProvider; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - -/** - * Simple demo controller class for signature validation purposes. - * - * @author Petr Dvorak, petr@wultra.com - */ -@Produces(MediaType.APPLICATION_JSON) -public class AuthenticationController { - - @Context - private HttpServletRequest request; - - @Inject - private PowerAuthAuthenticationProvider authenticationProvider; - - @POST - @Path("login") - @Consumes("*/*") - @Produces(MediaType.APPLICATION_JSON) - public ObjectResponse login(String body, @HeaderParam(value = PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader - ) throws PowerAuthAuthenticationException { - - // ##EXAMPLE: Here, we could store the authentication in the session like this: - // ##EXAMPLE: SecurityContextHolder.getContext().setAuthentication(apiAuthentication); - // ##EXAMPLE: ... or you can grab a user ID like this and use it for querying back-end: - // ##EXAMPLE: String userId = apiAuthentication.getUserId(); - - PowerAuthApiAuthentication auth = authenticationProvider.validateRequestSignature( - request, - "/login", - authHeader - ); - - if (auth == null || auth.getUserId() == null) { - throw new PowerAuthSignatureInvalidException(); - } - return new ObjectResponse<>("Hooray! " - + " User: " + auth.getUserId() - + " (activation: " + auth.getActivationId() + ")" - + " successfully verified via app with ID: " + auth.getApplicationId() - + " using factor: " + auth.getSignatureFactors() - ); - } - -} diff --git a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/TokenController.java b/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/TokenController.java deleted file mode 100644 index 0a35bf1b..00000000 --- a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/TokenController.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.app.rest.api.javaee.controller; - -import io.getlime.core.rest.model.base.response.Response; -import io.getlime.security.powerauth.http.PowerAuthTokenHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthTokenInvalidException; -import io.getlime.security.powerauth.rest.api.jaxrs.provider.PowerAuthAuthenticationProvider; - -import javax.inject.Inject; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; - -/** - * Simple demo controller class for token validation purposes. - * - * @author Roman Strobl, roman.strobl@wultra.com - */ -@Path("token") -@Produces(MediaType.APPLICATION_JSON) -public class TokenController { - - @Inject - private PowerAuthAuthenticationProvider authenticationProvider; - - @POST - @Path("authorize") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response authorize(@HeaderParam(value = PowerAuthTokenHttpHeader.HEADER_NAME) String tokenHeader) throws PowerAuthAuthenticationException { - PowerAuthApiAuthentication auth = authenticationProvider.validateToken(tokenHeader); - if (auth == null || auth.getUserId() == null) { - throw new PowerAuthTokenInvalidException(); - } - return new Response(); - } - -} diff --git a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/v2/CustomActivationController.java b/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/v2/CustomActivationController.java deleted file mode 100644 index 74ff29e3..00000000 --- a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/v2/CustomActivationController.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.app.rest.api.javaee.controller.v2; - -import com.wultra.security.powerauth.client.v2.PowerAuthPortV2ServiceStub; -import io.getlime.core.rest.model.base.request.ObjectRequest; -import io.getlime.core.rest.model.base.response.ObjectResponse; -import io.getlime.security.powerauth.rest.api.base.encryption.PowerAuthNonPersonalizedEncryptor; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthActivationException; -import io.getlime.security.powerauth.rest.api.base.provider.CustomActivationProvider; -import io.getlime.security.powerauth.rest.api.jaxrs.encryption.EncryptorFactory; -import io.getlime.security.powerauth.rest.api.model.entity.ActivationType; -import io.getlime.security.powerauth.rest.api.model.entity.NonPersonalizedEncryptedPayloadModel; -import io.getlime.security.powerauth.rest.api.model.request.v2.ActivationCreateCustomRequest; -import io.getlime.security.powerauth.rest.api.model.request.v2.ActivationCreateRequest; -import io.getlime.security.powerauth.rest.api.model.response.v2.ActivationCreateResponse; -import io.getlime.security.powerauth.soap.axis.client.PowerAuthServiceClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * Sample controller for a custom activation implementation. - * - *

PowerAuth protocol versions: - *

    - *
  • 2.0
  • - *
  • 2.1
  • - *
- * - * @author Petr Dvorak, petr@wultra.com - */ -@Path("/pa/activation/direct") -@Produces(MediaType.APPLICATION_JSON) -public class CustomActivationController { - - private static final Logger logger = LoggerFactory.getLogger(CustomActivationController.class); - - @Inject - private PowerAuthServiceClient powerAuthClient; - - @Inject - private EncryptorFactory encryptorFactory; - - @Inject - private CustomActivationProvider activationProvider; - - /** - * Sample custom activation implementation for version 2 of activations. - * - * @param object Encrypted activation request. - * @return Encrypted activation response. - * @throws PowerAuthActivationException In case activation fails. - */ - @POST - @Path("create") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public ObjectResponse createActivationV2(ObjectRequest object) throws PowerAuthActivationException { - try { - - final PowerAuthNonPersonalizedEncryptor encryptor = encryptorFactory.buildNonPersonalizedEncryptor(object); - - if (encryptor == null) { - logger.warn("Activation provider is missing"); - throw new PowerAuthActivationException(); - } - - ActivationCreateCustomRequest request = encryptor.decrypt(object, ActivationCreateCustomRequest.class); - - if (request == null) { - logger.warn("Encryptor is not available"); - throw new PowerAuthActivationException(); - } - - // Create context for passing parameters between activation provider calls - Map context = new LinkedHashMap<>(); - - final Map identity = request.getIdentity(); - String userId = activationProvider.lookupUserIdForAttributes(identity, context); - - // If no user was found or user ID is invalid, return error - if (userId == null || userId.equals("") || userId.length() > 255) { - logger.warn("User ID is invalid: {}", userId); - throw new PowerAuthActivationException(); - } - - ActivationCreateRequest acr = request.getPowerauth(); - PowerAuthPortV2ServiceStub.CreateActivationResponse response = powerAuthClient.v2().createActivation( - acr.getApplicationKey(), - userId, - acr.getActivationIdShort(), - acr.getActivationName(), - acr.getActivationNonce(), - acr.getEphemeralPublicKey(), - acr.getEncryptedDevicePublicKey(), - acr.getExtras(), - acr.getApplicationSignature() - ); - - final Map customAttributes = request.getCustomAttributes(); - activationProvider.processCustomActivationAttributes(customAttributes, response.getActivationId(), userId, null, ActivationType.CUSTOM, context); - - ActivationCreateResponse createResponse = new ActivationCreateResponse(); - createResponse.setActivationId(response.getActivationId()); - createResponse.setEphemeralPublicKey(response.getEphemeralPublicKey()); - createResponse.setActivationNonce(response.getActivationNonce()); - createResponse.setEncryptedServerPublicKey(response.getEncryptedServerPublicKey()); - createResponse.setEncryptedServerPublicKeySignature(response.getEncryptedServerPublicKeySignature()); - - final ObjectResponse powerAuthApiResponse = encryptor.encrypt(createResponse); - - if (activationProvider.shouldAutoCommitActivation(identity, customAttributes, response.getActivationId(), userId, null, ActivationType.CUSTOM, context)) { - powerAuthClient.commitActivation(response.getActivationId(), null); - } - - return powerAuthApiResponse; - - } catch (Exception ex) { - logger.warn("Create activation failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthActivationException(); - } - - } - -} diff --git a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/v2/EncryptedDataExchangeController.java b/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/v2/EncryptedDataExchangeController.java deleted file mode 100644 index f4505918..00000000 --- a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/v2/EncryptedDataExchangeController.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.app.rest.api.javaee.controller.v2; - -import io.getlime.core.rest.model.base.request.ObjectRequest; -import io.getlime.core.rest.model.base.response.ObjectResponse; -import io.getlime.security.powerauth.crypto.lib.model.exception.CryptoProviderException; -import io.getlime.security.powerauth.crypto.lib.model.exception.GenericCryptoException; -import io.getlime.security.powerauth.rest.api.base.encryption.PowerAuthNonPersonalizedEncryptor; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthEncryptionException; -import io.getlime.security.powerauth.rest.api.jaxrs.encryption.EncryptorFactory; -import io.getlime.security.powerauth.rest.api.model.entity.NonPersonalizedEncryptedPayloadModel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import java.rmi.RemoteException; -import java.security.InvalidKeyException; - -/** - * Sample end-point demonstrating how to receive and send encrypted data. - * - *

PowerAuth protocol versions: - *

    - *
  • 2.0
  • - *
  • 2.1
  • - *
- * - * @author Roman Strobl, roman.strobl@wultra.com - */ -@Produces(MediaType.APPLICATION_JSON) -public class EncryptedDataExchangeController { - - private static final Logger logger = LoggerFactory.getLogger(EncryptedDataExchangeController.class); - - @Context - private HttpServletRequest httpServletRequest; - - @Inject - private EncryptorFactory encryptorFactory; - - /** - * Sample encrypted data exchange. - * - * @param request Encrypted request. - * @return Encrypted response. - * @throws PowerAuthEncryptionException In case encryption or decryption fails. - */ - @POST - @Path("exchange") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public ObjectResponse exchange(ObjectRequest request) throws PowerAuthEncryptionException { - if (request == null) { - logger.warn("Invalid request in exchange method"); - throw new PowerAuthEncryptionException(); - } - - // Prepare an encryptor - PowerAuthNonPersonalizedEncryptor encryptor; - try { - encryptor = encryptorFactory.buildNonPersonalizedEncryptor(request); - } catch (RemoteException ex) { - logger.warn("Remote communication failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthEncryptionException(); - } - - // Decrypt the request object - byte[] requestDataBytes; - try { - requestDataBytes = encryptor.decrypt(request); - } catch (GenericCryptoException | CryptoProviderException | InvalidKeyException ex) { - logger.warn("Encryption failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthEncryptionException(); - } - - if (requestDataBytes == null) { - logger.warn("Invalid request data in exchange method"); - throw new PowerAuthEncryptionException(); - } - - String requestData = new String(requestDataBytes); - - // Return a slightly different String containing original data in response - String responseData = "Server successfully decrypted data: " + requestData; - - // Encrypt response data - ObjectResponse encryptedResponse; - try { - encryptedResponse = encryptor.encrypt(responseData.getBytes()); - } catch (GenericCryptoException | CryptoProviderException | InvalidKeyException ex) { - logger.warn("Encryption failed, error: {}", ex.getMessage()); - logger.debug(ex.getMessage(), ex); - throw new PowerAuthEncryptionException(); - } - - return encryptedResponse; - } - -} diff --git a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/v3/EncryptedDataExchangeController.java b/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/v3/EncryptedDataExchangeController.java deleted file mode 100644 index 198d7cfd..00000000 --- a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/controller/v3/EncryptedDataExchangeController.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.app.rest.api.javaee.controller.v3; - -import io.getlime.security.powerauth.app.rest.api.javaee.model.request.DataExchangeRequest; -import io.getlime.security.powerauth.app.rest.api.javaee.model.response.DataExchangeResponse; -import io.getlime.security.powerauth.crypto.lib.encryptor.ecies.model.EciesScope; -import io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader; -import io.getlime.security.powerauth.rest.api.base.authentication.PowerAuthApiAuthentication; -import io.getlime.security.powerauth.rest.api.base.encryption.EciesEncryptionContext; -import io.getlime.security.powerauth.rest.api.base.encryption.PowerAuthEciesEncryption; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthAuthenticationException; -import io.getlime.security.powerauth.rest.api.base.exception.PowerAuthEncryptionException; -import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureInvalidException; -import io.getlime.security.powerauth.rest.api.jaxrs.provider.PowerAuthAuthenticationProvider; -import io.getlime.security.powerauth.rest.api.jaxrs.provider.PowerAuthEncryptionProvider; -import io.getlime.security.powerauth.rest.api.model.response.v3.EciesEncryptedResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - -/** - * Sample end-point demonstrating how to receive and send encrypted data. - * - *

PowerAuth protocol versions: - *

    - *
  • 3.0
  • - *
- * - * @author Roman Strobl, roman.strobl@wultra.com - */ -@Path("/exchange") -@Produces(MediaType.APPLICATION_JSON) -public class EncryptedDataExchangeController { - - private static final Logger logger = LoggerFactory.getLogger(EncryptedDataExchangeController.class); - - @Inject - private PowerAuthEncryptionProvider encryptionProvider; - - @Context - private HttpServletRequest httpServletRequest; - - @Inject - private PowerAuthAuthenticationProvider authenticationProvider; - - /** - * Sample encrypted data exchange in application scope. - * - * @return ECIES encrypted response. - * @throws PowerAuthEncryptionException In case encryption fails. - */ - @POST - @Path("v3/application") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public EciesEncryptedResponse exchangeInApplicationScope() throws PowerAuthEncryptionException { - // Decrypt request - PowerAuthEciesEncryption eciesEncryption = encryptionProvider.decryptRequest(httpServletRequest, - DataExchangeRequest.class, EciesScope.APPLICATION_SCOPE); - DataExchangeRequest request = eciesEncryption.getRequestObject(); - EciesEncryptionContext eciesContext = eciesEncryption.getContext(); - - if (eciesContext == null) { - logger.debug("Encryption failed"); - throw new PowerAuthEncryptionException(); - } - - // Prepare response object - DataExchangeResponse exchangeResponse = new DataExchangeResponse("Server successfully decrypted signed data: " + (request == null ? "''" : request.getData()) + ", scope: " + eciesContext.getEciesScope()); - - // Encrypt response - return encryptionProvider.encryptResponse(exchangeResponse, eciesEncryption); - } - - - /** - * Sample encrypted data exchange in activation scope. - * - * @return ECIES encrypted response. - * @throws PowerAuthEncryptionException In case encryption fails. - */ - @POST - @Path("v3/activation") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public EciesEncryptedResponse exchangeInActivationScope() throws PowerAuthEncryptionException { - // Decrypt request - PowerAuthEciesEncryption eciesEncryption = encryptionProvider.decryptRequest(httpServletRequest, - DataExchangeRequest.class, EciesScope.ACTIVATION_SCOPE); - DataExchangeRequest request = eciesEncryption.getRequestObject(); - EciesEncryptionContext eciesContext = eciesEncryption.getContext(); - - if (eciesContext == null) { - logger.debug("Encryption failed"); - throw new PowerAuthEncryptionException(); - } - - // Prepare response object - DataExchangeResponse exchangeResponse = new DataExchangeResponse("Server successfully decrypted signed data: " + (request == null ? "''" : request.getData()) + ", scope: " + eciesContext.getEciesScope()); - - // Encrypt response - return encryptionProvider.encryptResponse(exchangeResponse, eciesEncryption); - } - - /** - * Sample signed and encrypted data exchange. - * - * @param authHeader PowerAuth signature HTTP header. - * @return ECIES encrypted response. - * @throws PowerAuthAuthenticationException In case signature validation fails - * @throws PowerAuthEncryptionException In case encryption fails. - */ - @POST - @Path("v3/signed") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public EciesEncryptedResponse exchangeSignedAndEncryptedData(@HeaderParam(value = PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthEncryptionException, PowerAuthAuthenticationException { - // Decrypt request - PowerAuthEciesEncryption eciesEncryption = encryptionProvider.decryptRequest(httpServletRequest, - DataExchangeRequest.class, EciesScope.ACTIVATION_SCOPE); - DataExchangeRequest request = eciesEncryption.getRequestObject(); - - if (eciesEncryption.getContext() == null) { - logger.debug("Encryption failed"); - throw new PowerAuthEncryptionException(); - } - - // Verify PowerAuth signature - PowerAuthApiAuthentication auth = authenticationProvider.validateRequestSignature( - httpServletRequest, - "/exchange/v3/signed", - authHeader - ); - - if (auth == null || auth.getUserId() == null) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - // Prepare response object - DataExchangeResponse exchangeResponse = new DataExchangeResponse("Server successfully decrypted data and verified signature, request data: " + (request == null ? "''" : request.getData()) + ", user ID: " + auth.getUserId()); - - // Encrypt response - return encryptionProvider.encryptResponse(exchangeResponse, eciesEncryption); - } - - /** - * Sample signed and encrypted data exchange of String data. - * - * @param authHeader PowerAuth signature HTTP header. - * @return ECIES encrypted response. - * @throws PowerAuthAuthenticationException In case signature validation fails - * @throws PowerAuthEncryptionException In case encryption fails. - */ - @POST - @Path("v3/signed/string") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public EciesEncryptedResponse exchangeSignedAndEncryptedDataString(@HeaderParam(value = PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthEncryptionException, PowerAuthAuthenticationException { - // Decrypt request - PowerAuthEciesEncryption eciesEncryption = encryptionProvider.decryptRequest(httpServletRequest, - String.class, EciesScope.ACTIVATION_SCOPE); - String requestData = eciesEncryption.getRequestObject(); - - if (eciesEncryption.getContext() == null) { - logger.debug("Encryption failed"); - throw new PowerAuthEncryptionException(); - } - - // Verify PowerAuth signature - PowerAuthApiAuthentication auth = authenticationProvider.validateRequestSignature( - httpServletRequest, - "/exchange/v3/signed/string", - authHeader - ); - - if (auth == null || auth.getUserId() == null) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - // Prepare response String - String exchangeResponse = "Server successfully decrypted data and verified signature, request data: " + (requestData == null ? "''" : requestData) + ", user ID: " + auth.getUserId(); - - // Encrypt response - return encryptionProvider.encryptResponse(exchangeResponse, eciesEncryption); - } - - /** - * Sample signed and encrypted data exchange of String data. - * - * @param authHeader PowerAuth signature HTTP header. - * @return ECIES encrypted response. - * @throws PowerAuthAuthenticationException In case signature validation fails - * @throws PowerAuthEncryptionException In case encryption fails. - */ - @POST - @Path("v3/signed/raw") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public EciesEncryptedResponse exchangeSignedAndEncryptedDataRaw(@HeaderParam(value = PowerAuthSignatureHttpHeader.HEADER_NAME) String authHeader) throws PowerAuthEncryptionException, PowerAuthAuthenticationException { - // Decrypt request - PowerAuthEciesEncryption eciesEncryption = encryptionProvider.decryptRequest(httpServletRequest, - byte[].class, EciesScope.ACTIVATION_SCOPE); - byte[] requestData = eciesEncryption.getRequestObject(); - - if (eciesEncryption.getContext() == null) { - logger.debug("Encryption failed"); - throw new PowerAuthEncryptionException(); - } - - // Verify PowerAuth signature - PowerAuthApiAuthentication auth = authenticationProvider.validateRequestSignature( - httpServletRequest, - "/exchange/v3/signed/raw", - authHeader - ); - - if (auth == null || auth.getUserId() == null) { - logger.debug("Signature validation failed"); - throw new PowerAuthSignatureInvalidException(); - } - // Encrypt response - return the same data as in request - return encryptionProvider.encryptResponse(requestData, eciesEncryption); - } - -} diff --git a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/model/request/DataExchangeRequest.java b/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/model/request/DataExchangeRequest.java deleted file mode 100644 index 5e6834a0..00000000 --- a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/model/request/DataExchangeRequest.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.getlime.security.powerauth.app.rest.api.javaee.model.request; - -/** - * Sample model class with request data. - * - * @author Roman Strobl, roman.strobl@wultra.com - */ -public class DataExchangeRequest { - - private String data; - - /** - * Default constructor. - */ - public DataExchangeRequest() { - } - - /** - * Constructor with data. - * @param data Data. - */ - public DataExchangeRequest(String data) { - this.data = data; - } - - /** - * Get data. - * @return Data. - */ - public String getData() { - return data; - } - - /** - * Set data. - * @param data Data. - */ - public void setData(String data) { - this.data = data; - } -} diff --git a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/model/response/DataExchangeResponse.java b/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/model/response/DataExchangeResponse.java deleted file mode 100644 index e07e8655..00000000 --- a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/model/response/DataExchangeResponse.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.getlime.security.powerauth.app.rest.api.javaee.model.response; - -/** - * Sample model class with response data. - * - * @author Roman Strobl, roman.strobl@wultra.com - */ -public class DataExchangeResponse { - - private String data; - - /** - * Default constructor. - */ - public DataExchangeResponse() { - } - - /** - * Constructor with data. - * @param data Data. - */ - public DataExchangeResponse(String data) { - this.data = data; - } - - /** - * Get data. - * @return Data. - */ - public String getData() { - return data; - } - - /** - * Set data. - * @param data Data. - */ - public void setData(String data) { - this.data = data; - } -} diff --git a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/provider/DefaultCustomActivationProvider.java b/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/provider/DefaultCustomActivationProvider.java deleted file mode 100644 index 457a25a3..00000000 --- a/powerauth-restful-server-javaee/src/main/java/io/getlime/security/powerauth/app/rest/api/javaee/provider/DefaultCustomActivationProvider.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * PowerAuth integration libraries for RESTful API applications, examples and - * related software components - * - * Copyright (C) 2018 Wultra s.r.o. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package io.getlime.security.powerauth.app.rest.api.javaee.provider; - -import io.getlime.security.powerauth.rest.api.base.provider.CustomActivationProvider; -import io.getlime.security.powerauth.rest.api.model.entity.ActivationType; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -/** - * @author Petr Dvorak, petr@wultra.com - */ -public class DefaultCustomActivationProvider implements CustomActivationProvider { - - @Override - public String lookupUserIdForAttributes(Map identityAttributes, Map context) { - return identityAttributes.get("username"); - } - - @Override - public Map processCustomActivationAttributes(Map customAttributes, String activationId, String userId, Long applId, ActivationType activationType, Map context) { - if (customAttributes != null) { - // Copy custom attributes - return new HashMap<>(customAttributes); - } else { - return Collections.emptyMap(); - } - } - - @Override - public boolean shouldAutoCommitActivation(Map identityAttributes, Map customAttributes, String activationId, String userId, Long applId, ActivationType activationType, Map context) { - return true; - } - - @Override - public void activationWasCommitted(Map identityAttributes, Map customAttributes, String activationId, String userId, Long applId, ActivationType activationType, Map context) { - } - - @Override - public Integer getMaxFailedAttemptCount(Map identityAttributes, Map customAttributes, String userId, ActivationType activationType, Map context) { - // Null value means use value configured on PowerAuth server - return null; - } - - @Override - public Long getValidityPeriodDuringActivation(Map identityAttributes, Map customAttributes, String userId, ActivationType activationType, Map context) { - // Null value means use value configured on PowerAuth server - return null; - } -} diff --git a/powerauth-restful-server-javaee/src/main/webapp/WEB-INF/beans.xml b/powerauth-restful-server-javaee/src/main/webapp/WEB-INF/beans.xml deleted file mode 100644 index e8daf3da..00000000 --- a/powerauth-restful-server-javaee/src/main/webapp/WEB-INF/beans.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - \ No newline at end of file diff --git a/powerauth-restful-server-spring/pom.xml b/powerauth-restful-server-spring/pom.xml index 2d0f3f5f..f761d427 100644 --- a/powerauth-restful-server-spring/pom.xml +++ b/powerauth-restful-server-spring/pom.xml @@ -26,7 +26,7 @@ powerauth-restful-server-spring PowerAuth Standard RESTful API powerauth-restful-server-spring - 1.0.0 + 1.1.0-SNAPSHOT war @@ -72,7 +72,7 @@ io.getlime.security powerauth-restful-security-spring - 1.0.0 + 1.1.0-SNAPSHOT @@ -84,7 +84,7 @@ org.bouncycastle bcprov-jdk15on - 1.67 + 1.68 provided diff --git a/powerauth-restful-server-spring/src/main/java/io/getlime/security/powerauth/app/rest/api/spring/controller/AuthenticationController.java b/powerauth-restful-server-spring/src/main/java/io/getlime/security/powerauth/app/rest/api/spring/controller/AuthenticationController.java index 62b228f1..f50d665a 100644 --- a/powerauth-restful-server-spring/src/main/java/io/getlime/security/powerauth/app/rest/api/spring/controller/AuthenticationController.java +++ b/powerauth-restful-server-spring/src/main/java/io/getlime/security/powerauth/app/rest/api/spring/controller/AuthenticationController.java @@ -25,9 +25,10 @@ import io.getlime.security.powerauth.rest.api.base.exception.authentication.PowerAuthSignatureInvalidException; import io.getlime.security.powerauth.rest.api.spring.annotation.PowerAuth; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.Map; /** * Sample end-point demonstrating how PowerAuth signature validation works. @@ -85,4 +86,33 @@ public class AuthenticationController { return new ObjectResponse<>("Hooray! User: " + auth.getUserId()); } + /** + * Validate any data sent to this end-point, uses substitutes in resource ID. + * @param id Identifier - testing object for @PathVariable annotation. + * @param value Value - testing object for @RequestParam annotation. + * @param auth Automatically injected PowerAuth authentication object. + * @return API response with success. + * @throws PowerAuthAuthenticationException In case any error occurs, including during signature validation. + */ + @RequestMapping(value = "submit/{id}/test", method = RequestMethod.POST) + @PowerAuth(resourceId = "/submit/${id}/test?value=${value}") + public @ResponseBody ObjectResponse dynamicResourceId(@PathVariable("id") String id, @RequestParam("value") String value, PowerAuthApiAuthentication auth) throws PowerAuthAuthenticationException { + + // ##EXAMPLE: Here, we could store the authentication in the session like this: + // ##EXAMPLE: SecurityContextHolder.getContext().setAuthentication(apiAuthentication); + // ##EXAMPLE: ... or you can grab a user ID like this and use it for querying back-end: + // ##EXAMPLE: String userId = apiAuthentication.getUserId(); + + if (auth == null || auth.getUserId() == null) { + throw new PowerAuthSignatureInvalidException(); + } + + final Map map = new HashMap<>(); + map.put("user", auth.getUserId()); + map.put("id", id); + map.put("value", value); + + return new ObjectResponse<>(map); + } + } From 1f2036781b6e6146d3b1a88f19f4db2b5bcb32ca Mon Sep 17 00:00:00 2001 From: Petr Dvorak Date: Wed, 5 May 2021 22:51:35 +0200 Subject: [PATCH 4/8] Fix results of code inspection --- .../filter/PowerAuthRequestFilterBase.java | 8 +++---- .../provider/CustomActivationProvider.java | 6 ++--- .../PowerAuthAuthenticationProviderBase.java | 2 +- .../PowerAuthEncryptionProviderBase.java | 3 +-- .../PowerAuthEncryptionArgumentResolver.java | 2 +- .../filter/EncryptionResponseBodyAdvice.java | 4 ++-- .../PowerAuthAuthenticationProvider.java | 24 ++++++++----------- .../configuration/WebApplicationConfig.java | 2 +- 8 files changed, 23 insertions(+), 28 deletions(-) diff --git a/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/filter/PowerAuthRequestFilterBase.java b/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/filter/PowerAuthRequestFilterBase.java index cdbf2e26..bb1a3ad6 100644 --- a/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/filter/PowerAuthRequestFilterBase.java +++ b/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/filter/PowerAuthRequestFilterBase.java @@ -45,7 +45,7 @@ public class PowerAuthRequestFilterBase { * @throws IOException In case request body extraction fails. */ public static ResettableStreamHttpServletRequest filterRequest(HttpServletRequest httpRequest) throws IOException { - ResettableStreamHttpServletRequest resettableRequest = new ResettableStreamHttpServletRequest(httpRequest); + final ResettableStreamHttpServletRequest resettableRequest = new ResettableStreamHttpServletRequest(httpRequest); if (httpRequest.getHeader(PowerAuthSignatureHttpHeader.HEADER_NAME) == null && httpRequest.getHeader(PowerAuthEncryptionHttpHeader.HEADER_NAME) == null) { // PowerAuth HTTP headers are not present, store empty request body in request attribute @@ -56,7 +56,7 @@ public static ResettableStreamHttpServletRequest filterRequest(HttpServletReques return resettableRequest; } - if (httpRequest.getMethod().toUpperCase().equals("GET")) { + if (httpRequest.getMethod().equalsIgnoreCase("GET")) { // Parse the query parameters String queryString = httpRequest.getQueryString(); @@ -66,7 +66,7 @@ public static ResettableStreamHttpServletRequest filterRequest(HttpServletReques queryString = URLDecoder.decode(queryString, "UTF-8"); // Get the canonized form - String signatureBaseStringData = PowerAuthRequestCanonizationUtils.canonizeGetParameters(queryString); + final String signatureBaseStringData = PowerAuthRequestCanonizationUtils.canonizeGetParameters(queryString); // Pass the signature base string as the request attribute if (signatureBaseStringData != null) { @@ -92,7 +92,7 @@ public static ResettableStreamHttpServletRequest filterRequest(HttpServletReques } else { // ... handle POST, PUT, DELETE, ... method // Get the request body and pass it as the signature base string as the request attribute - byte[] body = resettableRequest.getRequestBody(); + final byte[] body = resettableRequest.getRequestBody(); if (body != null) { resettableRequest.setAttribute( PowerAuthRequestObjects.REQUEST_BODY, diff --git a/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/CustomActivationProvider.java b/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/CustomActivationProvider.java index db7960de..125eb735 100644 --- a/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/CustomActivationProvider.java +++ b/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/CustomActivationProvider.java @@ -64,7 +64,7 @@ public interface CustomActivationProvider { */ default Map processCustomActivationAttributes(Map customAttributes, String activationId, String userId, Long appId, ActivationType activationType, Map context) throws PowerAuthActivationException { return customAttributes; - }; + } /** * Variable that specifies if the activation should be automatically committed based on provided attributes. @@ -105,7 +105,7 @@ default boolean shouldAutoCommitActivation(Map identityAttribute * @param context Context for passing parameters between activation provider calls. * @throws PowerAuthActivationException In case of error in custom activation business logic that should terminate the rest of the activation. */ - default void activationWasCommitted(Map identityAttributes, Map customAttributes, String activationId, String userId, Long appId, ActivationType activationType, Map context) throws PowerAuthActivationException {}; + default void activationWasCommitted(Map identityAttributes, Map customAttributes, String activationId, String userId, Long appId, ActivationType activationType, Map context) throws PowerAuthActivationException {} /** * Method that indicates if the recovery codes should be revoked when an activation is removed. @@ -129,7 +129,7 @@ default boolean shouldRevokeRecoveryCodeOnRemove(String activationId, String use * @param appId Application ID. * @throws PowerAuthActivationException In case of error in custom activation business logic that should terminate the rest of the activation. */ - default void activationWasRemoved(String activationId, String userId, Long appId) throws PowerAuthActivationException {}; + default void activationWasRemoved(String activationId, String userId, Long appId) throws PowerAuthActivationException {} /** * Get maximum failed attempt count for activations. diff --git a/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/PowerAuthAuthenticationProviderBase.java b/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/PowerAuthAuthenticationProviderBase.java index 2f67ddcd..9f21f113 100644 --- a/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/PowerAuthAuthenticationProviderBase.java +++ b/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/PowerAuthAuthenticationProviderBase.java @@ -156,7 +156,7 @@ public PowerAuthApiAuthentication validateToken(String tokenHeader) throws Power public byte[] extractRequestBodyBytes(HttpServletRequest servletRequest) throws PowerAuthAuthenticationException { if (servletRequest.getAttribute(PowerAuthRequestObjects.ENCRYPTION_OBJECT) != null) { // Implementation of sign-then-encrypt - in case the encryption object is present and signature is validate, use decrypted request data - PowerAuthEciesEncryption eciesEncryption = (PowerAuthEciesEncryption) servletRequest.getAttribute(PowerAuthRequestObjects.ENCRYPTION_OBJECT); + PowerAuthEciesEncryption eciesEncryption = (PowerAuthEciesEncryption) servletRequest.getAttribute(PowerAuthRequestObjects.ENCRYPTION_OBJECT); return eciesEncryption.getDecryptedRequest(); } else { // Request data was not encrypted - use regular PowerAuth request body for signature validation diff --git a/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/PowerAuthEncryptionProviderBase.java b/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/PowerAuthEncryptionProviderBase.java index ded7dcb4..a6c1d63d 100644 --- a/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/PowerAuthEncryptionProviderBase.java +++ b/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/PowerAuthEncryptionProviderBase.java @@ -192,7 +192,7 @@ public PowerAuthEciesEncryption decryptRequest(HttpServletRequest request * @param eciesEncryption PowerAuth encryption object. * @return ECIES encrypted response. */ - public EciesEncryptedResponse encryptResponse(Object responseObject, PowerAuthEciesEncryption eciesEncryption) { + public EciesEncryptedResponse encryptResponse(Object responseObject, PowerAuthEciesEncryption eciesEncryption) { try { byte[] responseData = serializeResponseData(responseObject); // Encrypt response using decryptor and return ECIES cryptogram @@ -215,7 +215,6 @@ public EciesEncryptedResponse encryptResponse(Object responseObject, PowerAuthEc * @return Request object. * @throws IOException In case request object could not be deserialized. */ - @SuppressWarnings("unchecked") private T deserializeRequestData(byte[] requestData, Class requestType) throws IOException { if (requestType.equals(byte[].class)) { // Raw data without deserialization from JSON diff --git a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthEncryptionArgumentResolver.java b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthEncryptionArgumentResolver.java index 7e9cff22..99258508 100644 --- a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthEncryptionArgumentResolver.java +++ b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthEncryptionArgumentResolver.java @@ -56,7 +56,7 @@ public boolean supportsParameter(@NonNull MethodParameter parameter) { @Override public Object resolveArgument(@NonNull MethodParameter parameter, ModelAndViewContainer mavContainer, @NonNull NativeWebRequest webRequest, WebDataBinderFactory binderFactory) { final HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest(); - final PowerAuthEciesEncryption eciesObject = (PowerAuthEciesEncryption) request.getAttribute(PowerAuthRequestObjects.ENCRYPTION_OBJECT); + final PowerAuthEciesEncryption eciesObject = (PowerAuthEciesEncryption) request.getAttribute(PowerAuthRequestObjects.ENCRYPTION_OBJECT); // Decrypted object is inserted into parameter annotated by @EncryptedRequestBody annotation if (parameter.hasParameterAnnotation(EncryptedRequestBody.class) && eciesObject != null && eciesObject.getDecryptedRequest() != null) { final Class parameterType = parameter.getParameterType(); diff --git a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/filter/EncryptionResponseBodyAdvice.java b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/filter/EncryptionResponseBodyAdvice.java index bd9fee59..b6f16372 100644 --- a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/filter/EncryptionResponseBodyAdvice.java +++ b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/filter/EncryptionResponseBodyAdvice.java @@ -107,7 +107,7 @@ public Object beforeBodyWrite(Object response, @NonNull MethodParameter methodPa // Extract ECIES encryption object from HTTP request final HttpServletRequest httpServletRequest = ((ServletServerHttpRequest) serverHttpRequest).getServletRequest(); - final PowerAuthEciesEncryption eciesEncryption = (PowerAuthEciesEncryption) httpServletRequest.getAttribute(PowerAuthRequestObjects.ENCRYPTION_OBJECT); + final PowerAuthEciesEncryption eciesEncryption = (PowerAuthEciesEncryption) httpServletRequest.getAttribute(PowerAuthRequestObjects.ENCRYPTION_OBJECT); if (eciesEncryption == null) { return null; } @@ -183,7 +183,7 @@ private byte[] convertEncryptedResponse(EciesEncryptedResponse encryptedResponse throw new IOException("Response message conversion failed, no applicable HTTP message converter found"); } - private class BasicHttpOutputMessage implements HttpOutputMessage { + private static class BasicHttpOutputMessage implements HttpOutputMessage { private final ByteArrayOutputStream os = new ByteArrayOutputStream(); private final HttpHeaders httpHeaders = new HttpHeaders(); diff --git a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/provider/PowerAuthAuthenticationProvider.java b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/provider/PowerAuthAuthenticationProvider.java index 1b188e6d..83c795bd 100644 --- a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/provider/PowerAuthAuthenticationProvider.java +++ b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/provider/PowerAuthAuthenticationProvider.java @@ -66,18 +66,11 @@ public class PowerAuthAuthenticationProvider extends PowerAuthAuthenticationProv private PowerAuthClient powerAuthClient; - private PowerAuthApplicationConfiguration applicationConfiguration; - @Autowired public void setPowerAuthClient(PowerAuthClient powerAuthClient) { this.powerAuthClient = powerAuthClient; } - @Autowired(required=false) - public void setApplicationConfiguration(PowerAuthApplicationConfiguration applicationConfiguration) { - this.applicationConfiguration = applicationConfiguration; - } - public Authentication authenticate(Authentication authentication) throws AuthenticationException { // Handle signature based authentications if (authentication instanceof PowerAuthSignatureAuthenticationImpl) { @@ -154,14 +147,13 @@ private PowerAuthApiAuthenticationImpl validateSignatureAuthentication(PowerAuth * @return API authentication object in case of successful authentication, null otherwise. */ private PowerAuthApiAuthenticationImpl validateTokenAuthentication(PowerAuthTokenAuthenticationImpl authentication) { - - ValidateTokenRequest soapRequest = new ValidateTokenRequest(); - soapRequest.setTokenId(authentication.getTokenId()); - soapRequest.setTokenDigest(authentication.getTokenDigest()); - soapRequest.setNonce(authentication.getNonce()); - soapRequest.setTimestamp(Long.valueOf(authentication.getTimestamp())); - try { + ValidateTokenRequest soapRequest = new ValidateTokenRequest(); + soapRequest.setTokenId(authentication.getTokenId()); + soapRequest.setTokenDigest(authentication.getTokenDigest()); + soapRequest.setNonce(authentication.getNonce()); + soapRequest.setTimestamp(Long.parseLong(authentication.getTimestamp())); + final ValidateTokenResponse soapResponse = powerAuthClient.validateToken(soapRequest); if (soapResponse.isTokenValid()) { return copyAuthenticationAttributes(soapResponse.getActivationId(), soapResponse.getUserId(), @@ -170,6 +162,10 @@ private PowerAuthApiAuthenticationImpl validateTokenAuthentication(PowerAuthToke } else { return null; } + } catch (NumberFormatException ex) { + logger.warn("Invalid timestamp format, error: {}", ex.getMessage()); + logger.debug("Error details", ex); + return null; } catch (Exception ex) { logger.warn("Token validation failed, error: {}", ex.getMessage()); logger.debug("Error details", ex); diff --git a/powerauth-restful-server-spring/src/main/java/io/getlime/security/powerauth/app/rest/api/spring/configuration/WebApplicationConfig.java b/powerauth-restful-server-spring/src/main/java/io/getlime/security/powerauth/app/rest/api/spring/configuration/WebApplicationConfig.java index 79e3dcb6..cb468dad 100644 --- a/powerauth-restful-server-spring/src/main/java/io/getlime/security/powerauth/app/rest/api/spring/configuration/WebApplicationConfig.java +++ b/powerauth-restful-server-spring/src/main/java/io/getlime/security/powerauth/app/rest/api/spring/configuration/WebApplicationConfig.java @@ -75,7 +75,7 @@ public PowerAuthEncryptionArgumentResolver powerAuthEncryptionArgumentResolver() * @return PowerAuthRequestFilter instance. */ @Bean - public FilterRegistrationBean powerAuthFilterRegistration() { + public FilterRegistrationBean powerAuthFilterRegistration() { FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(new PowerAuthRequestFilter()); registrationBean.setMatchAfter(true); From d571ce3004f1b2d17ba0c1183472b9216d7cfaaa Mon Sep 17 00:00:00 2001 From: Petr Dvorak Date: Mon, 17 May 2021 17:58:38 +0200 Subject: [PATCH 5/8] Fix code review comments --- docs/RESTful-API-for-Spring.md | 148 ++++++++---------- .../PowerAuthAnnotationInterceptor.java | 17 +- 2 files changed, 78 insertions(+), 87 deletions(-) diff --git a/docs/RESTful-API-for-Spring.md b/docs/RESTful-API-for-Spring.md index c4158cc0..44e27375 100644 --- a/docs/RESTful-API-for-Spring.md +++ b/docs/RESTful-API-for-Spring.md @@ -27,7 +27,7 @@ This step is technically required only in case your server uses end-to-end encry ```xml org.bouncycastle - bcprov-ext-jdk15on + bcprov-jdk15on ${bouncycastle.version} ``` @@ -94,6 +94,7 @@ public PowerAuthClient powerAuthClient() { ## Advanced PowerAuth REST Client Configuration The following REST client options are available: + - `maxMemorySize` - configures maximum memory size per request, default 1 MB - `connectTimeout` - configures connection timeout, default 5000 ms - `proxyEnabled` - enables proxy, disabled by default @@ -156,13 +157,13 @@ public class WebApplicationConfig implements WebMvcConfigurer { `PowerAuthInterceptor` bean is responsible for the `@PowerAuth` annotation handling (see example in [Verify Signatures Chapter](#verify-signatures)). You need to add it to the interceptor registry. -And finally, the `FilterRegistrationBean` (with the `PowerAuthRequestFilter` filter) is a technical component that passes the HTTP request body as an attribute of `HttpServletRequest`, so that it can be used for signature validation. +Finally, the `FilterRegistrationBean` (with the `PowerAuthRequestFilter` filter) is a technical component that passes the HTTP request body as an attribute of `HttpServletRequest`, so that it can be used for signature validation. ### Register a PowerAuth Application Configuration _(optional)_ -PowerAuth uses the concept of `application ID` and `application secret`. While `applicationId` attribute is transmitted with requests in `X-PowerAuth-Authorization` header, `applicationSecret` is shared implicitly between client and server and is a part of the actual signature value. Applications are a first class citizen in PowerAuth protocol. Intermediate application, however, may influence which applications are accepted by implementing following configuration. +PowerAuth uses the concept of `application ID` and `application secret`. While `applicationId` attribute is transmitted with requests in `X-PowerAuth-Authorization` header, `applicationSecret` is shared implicitly between the client and server and is a part of the actual signature value. Applications are a first class citizen in PowerAuth protocol. Intermediate application, however, may influence which applications are accepted by implementing following configuration. ```java @Configuration @@ -211,7 +212,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { This sample `@Controller` implementation illustrates how to use `@PowerAuth` annotation to verify that the request signature matches what is expected - in this case, to establish an authenticated session. In case the authentication is not successful, the `PowerAuthApiAuthentication` object is `null`. You may check for the `null` value and raise `PowerAuthAuthenticationException` that is handled alongside other application exceptions via default `@ControllerAdvice`. -_Note: Controllers that establish a session must not be on a context that is protected by Spring Security (for example "/secured/", in our example), otherwise context could never be reached and session will never be established._ + +Note: Controllers that establish a session must not be on a context that is protected by Spring Security (for example `/secured/`, in our example), otherwise context could never be reached and session will never be established. + ```java @Controller @@ -227,7 +230,7 @@ public class AuthenticationController { throw new PowerAuthSignatureInvalidException(); } // use userId if needed ... - String userId = auth.getUserId(); + final String userId = auth.getUserId(); // create authenticated session SecurityContextHolder.getContext().setAuthentication((Authentication) auth); @@ -239,6 +242,41 @@ public class AuthenticationController { } ``` +The `resourceId` parameter of the `@PowerAuth` annotation can substitute placeholders (marked via "${placeholder}") with the actual parameters of the handler method. Mobile client can construct resource ID values in a dynamic way accordingly. The implementation takes into account all handler method parameters that are annotated via `@RequestParam` or `@PathVariable` annotations and extracts values from the request parameter map. + + +In case both `@RequestParam` and `@PathVariable` with the same name exist, the value of `@RequestParam` takes precedence. This is because `@RequestParam` usually maps to the HTTP GET query parameter that cannot be easily changed in existing API, while `@PathVariable` is just a URL placeholder that can be renamed in the code with no impact on functionality. + + +Example of using dynamic resource ID: + +```java +@Controller +@RequestMapping(value = "secured") +public class AuthenticationController { + + @RequestMapping(value = "account/{id}", method = RequestMethod.POST) + @PowerAuth(resourceId = "/secured/account/${id}?filter=${filter}") + @ResponseBody + public MyAccountApiResponse changeAccountSettings( + @PathVariable("id") String accountId, @RequestParam("filter") String filter, PowerAuthApiAuthentication auth) { + + if (auth == null) { + // handle authentication failure + throw new PowerAuthSignatureInvalidException(); + } + + // use userId for business logic ... + final String userId = auth.getUserId(); + final Account account = myService.updateAccount(accountId, userId, filter); + + // return OK response + return new MyAccountApiResponse(Status.OK, userId); + } + +} +``` + In case you need a more low-level access to the signature verification, you can verify the signature manually using the `PowerAuthAuthenticationProvider` like this: ```java @@ -250,15 +288,16 @@ public class AuthenticationController { private PowerAuthAuthenticationProvider authenticationProvider; @RequestMapping(value = "login", method = RequestMethod.POST) - public @ResponseBody PowerAuthAPIResponse login( - @RequestHeader(value = PowerAuthSignatureHttpHeader.HEADER_NAME, required = true) String signatureHeader, - HttpServletRequest servletRequest) throws Exception { - - PowerAuthApiAuthentication apiAuthentication = authenticationProvider.validateRequestSignature( - "POST", - "Any data".getBytes(StandardCharsets.UTF_8), - "/session/login", - signatureHeader + @ResponseBody + public PowerAuthAPIResponse login( + @RequestHeader(value = PowerAuthSignatureHttpHeader.HEADER_NAME, required = true) String signatureHeader, + HttpServletRequest servletRequest) throws Exception { + + final PowerAuthApiAuthentication apiAuthentication = authenticationProvider.validateRequestSignature( + "POST", + "Any data".getBytes(StandardCharsets.UTF_8), + "/session/login", + signatureHeader ); if (apiAuthentication == null || apiAuthentication.getUserId() == null) { @@ -302,9 +341,9 @@ public class AuthenticationController { ## Use End-To-End Encryption -You can use end-to-end encryption to add an additional encryption layer on top of the basic HTTPS encryption to protect the request body contents better. +You can use end-to-end encryption to add additional encryption layer on top of the basic HTTPS encryption to protect the request body contents better. -End-to-end encryption provided by PowerAuth uses `POST` method for all data transport and it requires predefined request / response structure. +End-to-end encryption provided by PowerAuth uses `POST` method for all data transport, and it requires a predefined request / response structure. ### Encryption in Application Scope @@ -330,9 +369,9 @@ public class EncryptedDataExchangeController { } ``` -The method argument annotated by the `@EncryptedRequestBody` annotation is set with decrypted request data. The data is decrypted using ECIES decryptor initialized in `application` scope. +The method argument annotated by the `@EncryptedRequestBody` annotation is set with decrypted request data. The data is decrypted using an ECIES decryptor initialized in `application` scope. -The response data is automatically encrypted using the previously created ECIES decryptor which was used for decrypting the request data. +The response data is automatically encrypted using the previously created an ECIES decryptor which was used for decrypting the request data. ### Encryption in Activation Scope @@ -358,9 +397,9 @@ public class EncryptedDataExchangeController { } ``` -The method argument annotated by the `@EncryptedRequestBody` annotation is set with decrypted request data. The data is decrypted using ECIES decryptor initialized in `activation` scope. +The method argument annotated by the `@EncryptedRequestBody` annotation is set with decrypted request data. The data is decrypted using an ECIES decryptor initialized in `activation` scope. -The response data is automatically encrypted using the previously created ECIES decryptor which was used for decrypting the request data. +The response data is automatically encrypted using the previously created an ECIES decryptor which was used for decrypting the request data. ### Signed and Encrypted Requests @@ -393,69 +432,10 @@ public class EncryptedDataExchangeController { } ``` -The method argument annotated by the `@EncryptedRequestBody` annotation is set with decrypted request data. The data is decrypted using ECIES decryptor initialized in `activation` scope. The signature received in PowerAuth HTTP signature header is verified. - -The response data is automatically encrypted using the previously created ECIES decryptor which was used for decrypting the request data. - -_Note: You can also use `String` or `byte[]` data types instead of using request/response objects for encryption of raw data._ - -### Non-Personalized End-To-End Encryption (v2 - legacy) +The method argument annotated by the `@EncryptedRequestBody` annotation is set with decrypted request data. The data is decrypted using an ECIES decryptor initialized in `activation` scope. The signature received in PowerAuth HTTP signature header is verified. -To use the legacy non-personalized (application specific) encryption, use following pattern: +The response data is automatically encrypted using the previously created an ECIES decryptor which was used for decrypting the request data. -```java -@RestController -@RequestMapping(value = "encrypted") -public class EncryptedController { - - private EncryptorFactory encryptorFactory; - - @Autowired - public void setEncryptorFactory(EncryptorFactory encryptorFactory) { - this.encryptorFactory = encryptorFactory; - } - - - @RequestMapping(value = "hello", method = RequestMethod.POST) - public PowerAuthApiResponse createNewActivation(@RequestBody PowerAuthApiRequest encryptedRequest) throws PowerAuthActivationException { - try { - - // Prepare an encryptor - final PowerAuthNonPersonalizedEncryptor encryptor = encryptorFactory.buildNonPersonalizedEncryptor(encryptedRequest); - if (encryptor == null) { - throw new PowerAuthEncryptionException(); - } - - // Decrypt the request object - OriginalRequest request = encryptor.decrypt(object, OriginalRequest.class); - - if (request == null) { - throw new PowerAuthEncryptionException(); - } - - // ... do your business logic with OriginalRequest instance - - // Create original response object - OriginalResponse response = new OriginalResponse(); - response.setAttribute1("attribute1"); - response.setAttribute2("attribute2"); - response.setAttribute3("attribute3"); - - // Encrypt response object - final PowerAuthApiResponse encryptedResponse = encryptor.encrypt(response); - - if (encryptedResponse == null) { - throw new PowerAuthEncryptionException(); - } - - // Return response - return encryptedResponse; - - } catch (IOException ex) { - throw new PowerAuthActivationException(); - } - - } - -} -``` + +Note: You can use `String` or `byte[]` data types instead of using request/response objects for encryption of raw data. + diff --git a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthAnnotationInterceptor.java b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthAnnotationInterceptor.java index abb648b8..fff22dec 100644 --- a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthAnnotationInterceptor.java +++ b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthAnnotationInterceptor.java @@ -158,7 +158,14 @@ private Class resolveGenericParameterTypeForEcies(HandlerMethod handlerMethod * The method substitutes placeholders (marked via "${placeholder}") in resourceID attribute value by * the actual parameters of the handler method. The implementation takes into account all method parameters * that are annotated via @RequestParam or @PathVariable annotations and extracts values from the request - * parameter map. + * parameter map.
+ *
+ * + * Note: In case both @RequestParam and @PathVariable with the same name exist, the value of @RequestParam + * takes precedence. This is because @RequestParam usually maps to the HTTP GET query parameter that cannot + * be easily changed in existing API, while @PathVariable is just a URL placeholder that can be renamed in + * the code with no impact on functionality. + * * * @param resourceId Resource ID with possible placeholders. * @param request HttpServletRequest for the current execution. @@ -173,11 +180,15 @@ private String expandResourceId(String resourceId, HttpServletRequest request, H for (MethodParameter mp : methodParameters) { // Handle parameters annotated by @RequestParam annotation. // These are stored in the servlet request parameter map. + // Note: @RequestParam must be processed before @PathVariable since + // in API, it cannot be renamed (the path variable is just + // a placeholder and can have arbitrary name). final RequestParam requestParam = mp.getParameterAnnotation(RequestParam.class); if (requestParam != null) { final String name = requestParam.name(); final String value = request.getParameter(name); - if (value != null) { + if (value != null) { // do not check "&& !parameters.containsKey(name)" because in the case of + // a name conflict, we want @RequestParam to overwrite @PathVariable value parameters.put(name, value); } } else { @@ -189,7 +200,7 @@ private String expandResourceId(String resourceId, HttpServletRequest request, H if (pathVariable != null) { final String name = pathVariable.name(); final Map pathVariableMap = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); - if (pathVariableMap != null) { + if (pathVariableMap != null && !parameters.containsKey(name)) { // prevent overwriting value that is already assigned final String value = pathVariableMap.get(name); if (value != null) { parameters.put(name, value); From 005649aaf57853e16587810e276bff51cdfe489e Mon Sep 17 00:00:00 2001 From: Roman Strobl Date: Thu, 20 May 2021 16:49:50 +0200 Subject: [PATCH 6/8] Fix #279: Update dependencies for release --- pom.xml | 6 +++--- powerauth-restful-server-spring/pom.xml | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/pom.xml b/pom.xml index d97182b8..f6112d01 100644 --- a/pom.xml +++ b/pom.xml @@ -84,12 +84,12 @@ 3.2.0 3.2.1 3.3.1 - 3.1.0 + 4.0.1 2.4.5 1.9 2.12.3 1.68 - 1.2.0 + 1.3.0-SNAPSHOT @@ -184,7 +184,7 @@ ossrh-snapshots - http://oss.sonatype.org/content/repositories/snapshots/ + https://oss.sonatype.org/content/repositories/snapshots/ false diff --git a/powerauth-restful-server-spring/pom.xml b/powerauth-restful-server-spring/pom.xml index f761d427..8e6c8e96 100644 --- a/powerauth-restful-server-spring/pom.xml +++ b/powerauth-restful-server-spring/pom.xml @@ -32,7 +32,7 @@ org.springframework.boot spring-boot-starter-parent - 2.3.7.RELEASE + 2.4.5 @@ -79,7 +79,7 @@ com.google.guava guava - 30.0-jre + 30.1.1-jre org.bouncycastle @@ -107,7 +107,7 @@ org.apache.maven.plugins maven-deploy-plugin - 2.8.2 + 3.0.0-M1 true From 91bb2283d48de67ee0910f4c8b4df351692d2669 Mon Sep 17 00:00:00 2001 From: Petr Dvorak Date: Mon, 31 May 2021 19:17:54 +0200 Subject: [PATCH 7/8] Fix #255: Add JavaDoc for all methods --- pom.xml | 2 +- .../rest/api/model/entity/ActivationType.java | 12 ++++ .../NonPersonalizedEncryptedPayloadModel.java | 64 +++++++++++++++++ .../v2/ActivationCreateCustomRequest.java | 24 +++++++ .../PowerAuthNonPersonalizedEncryptor.java | 70 ++++++++++++++++--- .../exception/PowerAuthRecoveryException.java | 7 ++ .../PowerAuthEncryptionProviderBase.java | 35 +++++----- .../PowerAuthAnnotationInterceptor.java | 13 ++++ .../annotation/PowerAuthEncryption.java | 5 ++ .../PowerAuthApiAuthenticationImpl.java | 31 ++++++++ .../PowerAuthSignatureAuthenticationImpl.java | 44 ++++++++++++ .../PowerAuthTokenAuthenticationImpl.java | 23 ++++++ .../spring/encryption/EncryptorFactory.java | 7 ++ .../filter/EncryptionResponseBodyAdvice.java | 18 +++-- .../PowerAuthAuthenticationProvider.java | 44 ++++++++---- .../provider/PowerAuthEncryptionProvider.java | 5 ++ .../controller/v2/ActivationController.java | 12 ++++ .../controller/v2/SecureVaultController.java | 4 ++ .../spring/controller/v2/TokenController.java | 8 +++ .../controller/v3/ActivationController.java | 8 +++ .../controller/v3/SecureVaultController.java | 4 ++ .../spring/controller/v3/TokenController.java | 4 ++ .../controller/v3/UpgradeController.java | 4 ++ .../exception/PowerAuthExceptionHandler.java | 3 + .../spring/service/v2/ActivationService.java | 24 ++++--- .../spring/service/v2/SecureVaultService.java | 28 +++++--- .../api/spring/service/v2/TokenService.java | 4 ++ .../spring/service/v3/ActivationService.java | 60 +++++++++------- .../spring/service/v3/RecoveryService.java | 2 +- .../spring/service/v3/SecureVaultService.java | 28 +++++--- .../api/spring/service/v3/TokenService.java | 14 ++-- .../api/spring/service/v3/UpgradeService.java | 18 +++-- 32 files changed, 517 insertions(+), 112 deletions(-) diff --git a/pom.xml b/pom.xml index f6112d01..a533d9c8 100644 --- a/pom.xml +++ b/pom.xml @@ -81,7 +81,7 @@ 1.8 3.2.0 3.0.0-M1 - 3.2.0 + 3.3.0 3.2.1 3.3.1 4.0.1 diff --git a/powerauth-restful-model/src/main/java/io/getlime/security/powerauth/rest/api/model/entity/ActivationType.java b/powerauth-restful-model/src/main/java/io/getlime/security/powerauth/rest/api/model/entity/ActivationType.java index 542d8358..395b16de 100644 --- a/powerauth-restful-model/src/main/java/io/getlime/security/powerauth/rest/api/model/entity/ActivationType.java +++ b/powerauth-restful-model/src/main/java/io/getlime/security/powerauth/rest/api/model/entity/ActivationType.java @@ -25,7 +25,19 @@ * @author Roman Strobl, roman.strobl@wultra.com */ public enum ActivationType { + + /** + * Activation via activation code. + */ CODE, + + /** + * Activation via custom credentials. + */ CUSTOM, + + /** + * Activation via recovery code. + */ RECOVERY } diff --git a/powerauth-restful-model/src/main/java/io/getlime/security/powerauth/rest/api/model/entity/NonPersonalizedEncryptedPayloadModel.java b/powerauth-restful-model/src/main/java/io/getlime/security/powerauth/rest/api/model/entity/NonPersonalizedEncryptedPayloadModel.java index 4e605e26..a6f3d8fd 100644 --- a/powerauth-restful-model/src/main/java/io/getlime/security/powerauth/rest/api/model/entity/NonPersonalizedEncryptedPayloadModel.java +++ b/powerauth-restful-model/src/main/java/io/getlime/security/powerauth/rest/api/model/entity/NonPersonalizedEncryptedPayloadModel.java @@ -35,66 +35,130 @@ public class NonPersonalizedEncryptedPayloadModel { private String mac; private String encryptedData; + /** + * Get application key. + * @return Application key. + */ public String getApplicationKey() { return applicationKey; } + /** + * Set application key. + * @param applicationKey Application key. + */ public void setApplicationKey(String applicationKey) { this.applicationKey = applicationKey; } + /** + * Get session index. + * @return Session index. + */ public String getSessionIndex() { return sessionIndex; } + /** + * Set session index. + * @param sessionIndex Session index. + */ public void setSessionIndex(String sessionIndex) { this.sessionIndex = sessionIndex; } + /** + * Get ad-hoc index. + * @return Ad-hoc index. + */ public String getAdHocIndex() { return adHocIndex; } + /** + * Set ad-hoc index. + * @param adHocIndex Ad-hoc index. + */ public void setAdHocIndex(String adHocIndex) { this.adHocIndex = adHocIndex; } + /** + * Get MAC index. + * @return MAC index. + */ public String getMacIndex() { return macIndex; } + /** + * Set MAC index. + * @param macIndex MAC index. + */ public void setMacIndex(String macIndex) { this.macIndex = macIndex; } + /** + * Get nonce. + * @return Nonce. + */ public String getNonce() { return nonce; } + /** + * Set nonce. + * @param nonce Nonce. + */ public void setNonce(String nonce) { this.nonce = nonce; } + /** + * Get ephemeral public key. + * @return Ephemeral public key. + */ public String getEphemeralPublicKey() { return ephemeralPublicKey; } + /** + * Set ephemeral public key. + * @param ephemeralPublicKey Ephemeral public key. + */ public void setEphemeralPublicKey(String ephemeralPublicKey) { this.ephemeralPublicKey = ephemeralPublicKey; } + /** + * Get MAC. + * @return MAC. + */ public String getMac() { return mac; } + /** + * Set MAC. + * @param mac MAC. + */ public void setMac(String mac) { this.mac = mac; } + /** + * Get encrypted data. + * @return Encrypted data. + */ public String getEncryptedData() { return encryptedData; } + /** + * Set encrypted data. + * @param encryptedData Encrypted data. + */ public void setEncryptedData(String encryptedData) { this.encryptedData = encryptedData; } diff --git a/powerauth-restful-model/src/main/java/io/getlime/security/powerauth/rest/api/model/request/v2/ActivationCreateCustomRequest.java b/powerauth-restful-model/src/main/java/io/getlime/security/powerauth/rest/api/model/request/v2/ActivationCreateCustomRequest.java index ca962010..2d6c278a 100644 --- a/powerauth-restful-model/src/main/java/io/getlime/security/powerauth/rest/api/model/request/v2/ActivationCreateCustomRequest.java +++ b/powerauth-restful-model/src/main/java/io/getlime/security/powerauth/rest/api/model/request/v2/ActivationCreateCustomRequest.java @@ -35,26 +35,50 @@ public class ActivationCreateCustomRequest { private Map customAttributes; private ActivationCreateRequest powerauth; + /** + * Get identity attributes. + * @return Identity attributes. + */ public Map getIdentity() { return identity; } + /** + * Set identity attributes. + * @param identity Identity attributes. + */ public void setIdentity(Map identity) { this.identity = identity; } + /** + * Get custom attributes. + * @return Custom attributes. + */ public Map getCustomAttributes() { return customAttributes; } + /** + * Set custom attributes. + * @param customAttributes Custom attributes. + */ public void setCustomAttributes(Map customAttributes) { this.customAttributes = customAttributes; } + /** + * Get PowerAuth activation data. + * @return PowerAuth activation data. + */ public ActivationCreateRequest getPowerauth() { return powerauth; } + /** + * Set PowerAuth activation data. + * @param powerauth PowerAuth activation data. + */ public void setPowerauth(ActivationCreateRequest powerauth) { this.powerauth = powerauth; } diff --git a/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/encryption/PowerAuthNonPersonalizedEncryptor.java b/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/encryption/PowerAuthNonPersonalizedEncryptor.java index 2a12b735..820722cc 100644 --- a/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/encryption/PowerAuthNonPersonalizedEncryptor.java +++ b/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/encryption/PowerAuthNonPersonalizedEncryptor.java @@ -34,6 +34,8 @@ import java.security.InvalidKeyException; /** + * Non-personalized encryptor class. + * * @author Petr Dvorak, petr@wultra.com */ public class PowerAuthNonPersonalizedEncryptor { @@ -42,35 +44,62 @@ public class PowerAuthNonPersonalizedEncryptor { private final ObjectMapper mapper = new ObjectMapper(); + /** + * Constructor with all mandatory parameters. + * + * @param applicationKeyBase64 Application key. + * @param sessionKeyBytesBase64 Session key. + * @param sessionIndexBase64 Session index. + * @param ephemeralPublicKeyBase64 Ephemeral public key. + */ public PowerAuthNonPersonalizedEncryptor(String applicationKeyBase64, String sessionKeyBytesBase64, String sessionIndexBase64, String ephemeralPublicKeyBase64) { - byte[] applicationKey = BaseEncoding.base64().decode(applicationKeyBase64); - byte[] sessionIndex = BaseEncoding.base64().decode(sessionIndexBase64); - byte[] sessionKeyBytes = BaseEncoding.base64().decode(sessionKeyBytesBase64); - byte[] ephemeralKeyBytes = BaseEncoding.base64().decode(ephemeralPublicKeyBase64); + final byte[] applicationKey = BaseEncoding.base64().decode(applicationKeyBase64); + final byte[] sessionIndex = BaseEncoding.base64().decode(sessionIndexBase64); + final byte[] sessionKeyBytes = BaseEncoding.base64().decode(sessionKeyBytesBase64); + final byte[] ephemeralKeyBytes = BaseEncoding.base64().decode(ephemeralPublicKeyBase64); this.encryptor = new NonPersonalizedEncryptor(applicationKey, sessionKeyBytes, sessionIndex, ephemeralKeyBytes); } + /** + * Encrypt object. + * + * @param object Object to be encrypted. + * @return Encrypted object. + * @throws JsonProcessingException In case the resulting object cannot be encoded as JSON. + * @throws GenericCryptoException In case of a cryptography error. + * @throws CryptoProviderException In case of a cryptographic provider error. + * @throws InvalidKeyException In case the key provided for encryption is invalid. + */ public ObjectResponse encrypt(Object object) throws JsonProcessingException, GenericCryptoException, CryptoProviderException, InvalidKeyException { if (object == null) { return null; } - byte[] originalData = mapper.writeValueAsBytes(object); + final byte[] originalData = mapper.writeValueAsBytes(object); return this.encrypt(originalData); } + /** + * Encrypt data. + * + * @param originalData Bytes to be encrypted. + * @return Encrypted object. + * @throws GenericCryptoException In case of a cryptography error. + * @throws CryptoProviderException In case of a cryptographic provider error. + * @throws InvalidKeyException In case the key provided for encryption is invalid. + */ public ObjectResponse encrypt(byte[] originalData) throws GenericCryptoException, CryptoProviderException, InvalidKeyException { if (originalData == null) { return null; } - NonPersonalizedEncryptedMessage message = encryptor.encrypt(originalData); + final NonPersonalizedEncryptedMessage message = encryptor.encrypt(originalData); if (message == null) { // this will happen only in case of an unlikely randomness error, or if keys are corrupted return null; } - NonPersonalizedEncryptedPayloadModel responseObject = new NonPersonalizedEncryptedPayloadModel(); + final NonPersonalizedEncryptedPayloadModel responseObject = new NonPersonalizedEncryptedPayloadModel(); responseObject.setApplicationKey(BaseEncoding.base64().encode(message.getApplicationKey())); responseObject.setEphemeralPublicKey(BaseEncoding.base64().encode(message.getEphemeralPublicKey())); responseObject.setSessionIndex(BaseEncoding.base64().encode(message.getSessionIndex())); @@ -83,19 +112,28 @@ public ObjectResponse encrypt(byte[] origi return new ObjectResponse<>(responseObject); } + /** + * Decrypt an object. + * + * @param request Object with encrypted payload. + * @return Decrypted bytes. + * @throws GenericCryptoException In case of a cryptography error. + * @throws CryptoProviderException In case of a cryptographic provider error. + * @throws InvalidKeyException In case the key provided for encryption is invalid. + */ public byte[] decrypt(ObjectRequest request) throws GenericCryptoException, CryptoProviderException, InvalidKeyException { if (request == null) { return null; } - NonPersonalizedEncryptedPayloadModel requestObject = request.getRequestObject(); + final NonPersonalizedEncryptedPayloadModel requestObject = request.getRequestObject(); if (requestObject == null) { return null; } - NonPersonalizedEncryptedMessage message = new NonPersonalizedEncryptedMessage(); + final NonPersonalizedEncryptedMessage message = new NonPersonalizedEncryptedMessage(); message.setApplicationKey(BaseEncoding.base64().decode(requestObject.getApplicationKey())); message.setEphemeralPublicKey(BaseEncoding.base64().decode(requestObject.getEphemeralPublicKey())); message.setSessionIndex(BaseEncoding.base64().decode(requestObject.getSessionIndex())); @@ -108,8 +146,20 @@ public byte[] decrypt(ObjectRequest reques return encryptor.decrypt(message); } + /** + * Decrypt data and serialize object. + * + * @param request Request with encrypted data. + * @param resultClass Result deserialized class. + * @param Specific type of the result class. + * @return Decrypted object of a provided type T. + * @throws IOException In case the JSON deserialization fails. + * @throws GenericCryptoException In case of a cryptography error. + * @throws CryptoProviderException In case of a cryptographic provider error. + * @throws InvalidKeyException In case the key provided for encryption is invalid. + */ public T decrypt(ObjectRequest request, Class resultClass) throws IOException, GenericCryptoException, CryptoProviderException, InvalidKeyException { - byte[] result = this.decrypt(request); + final byte[] result = this.decrypt(request); if (result == null) { return null; } diff --git a/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/exception/PowerAuthRecoveryException.java b/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/exception/PowerAuthRecoveryException.java index 3198491d..33bed644 100644 --- a/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/exception/PowerAuthRecoveryException.java +++ b/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/exception/PowerAuthRecoveryException.java @@ -31,7 +31,14 @@ public class PowerAuthRecoveryException extends Exception { private static final String DEFAULT_CODE = "ERR_RECOVERY"; private static final String DEFAULT_ERROR = "POWER_AUTH_RECOVERY_INVALID"; + /** + * Error code. + */ private String errorCode; + + /** + * Index of the recovery PUK index. + */ private Integer currentRecoveryPukIndex; /** diff --git a/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/PowerAuthEncryptionProviderBase.java b/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/PowerAuthEncryptionProviderBase.java index a6c1d63d..904ade93 100644 --- a/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/PowerAuthEncryptionProviderBase.java +++ b/powerauth-restful-security-base/src/main/java/io/getlime/security/powerauth/rest/api/base/provider/PowerAuthEncryptionProviderBase.java @@ -90,7 +90,7 @@ public PowerAuthEciesEncryption decryptRequest(HttpServletRequest request } // Resolve either signature or encryption HTTP header for ECIES - EciesEncryptionContext encryptionContext = extractEciesEncryptionContext(request); + final EciesEncryptionContext encryptionContext = extractEciesEncryptionContext(request); // Construct ECIES encryption object from HTTP header final PowerAuthEciesEncryption eciesEncryption = new PowerAuthEciesEncryption<>(encryptionContext); @@ -100,12 +100,12 @@ public PowerAuthEciesEncryption decryptRequest(HttpServletRequest request try { // Parse ECIES cryptogram from request body - PowerAuthRequestBody requestBody = ((PowerAuthRequestBody) request.getAttribute(PowerAuthRequestObjects.REQUEST_BODY)); + final PowerAuthRequestBody requestBody = ((PowerAuthRequestBody) request.getAttribute(PowerAuthRequestObjects.REQUEST_BODY)); if (requestBody == null) { logger.warn("The X-PowerAuth-Request-Body request attribute is missing. Register the PowerAuthRequestFilter to fix this error."); throw new PowerAuthEncryptionException(); } - byte[] requestBodyBytes = requestBody.getRequestBytes(); + final byte[] requestBodyBytes = requestBody.getRequestBytes(); if (requestBodyBytes == null || requestBodyBytes.length == 0) { logger.warn("Invalid HTTP request"); throw new PowerAuthEncryptionException(); @@ -167,8 +167,8 @@ public PowerAuthEciesEncryption decryptRequest(HttpServletRequest request eciesEncryption.setEciesDecryptor(eciesDecryptor); // Decrypt request data - EciesCryptogram cryptogram = new EciesCryptogram(ephemeralPublicKeyBytes, macBytes, encryptedDataBytes, nonceBytes); - byte[] decryptedData = eciesDecryptor.decryptRequest(cryptogram); + final EciesCryptogram cryptogram = new EciesCryptogram(ephemeralPublicKeyBytes, macBytes, encryptedDataBytes, nonceBytes); + final byte[] decryptedData = eciesDecryptor.decryptRequest(cryptogram); eciesEncryption.setEncryptedRequest(encryptedDataBytes); eciesEncryption.setDecryptedRequest(decryptedData); // Set the request object only in case when request data is sent @@ -194,11 +194,11 @@ public PowerAuthEciesEncryption decryptRequest(HttpServletRequest request */ public EciesEncryptedResponse encryptResponse(Object responseObject, PowerAuthEciesEncryption eciesEncryption) { try { - byte[] responseData = serializeResponseData(responseObject); + final byte[] responseData = serializeResponseData(responseObject); // Encrypt response using decryptor and return ECIES cryptogram - EciesCryptogram cryptogram = eciesEncryption.getEciesDecryptor().encryptResponse(responseData); - String encryptedDataBase64 = BaseEncoding.base64().encode(cryptogram.getEncryptedData()); - String macBase64 = BaseEncoding.base64().encode(cryptogram.getMac()); + final EciesCryptogram cryptogram = eciesEncryption.getEciesDecryptor().encryptResponse(responseData); + final String encryptedDataBase64 = BaseEncoding.base64().encode(cryptogram.getEncryptedData()); + final String macBase64 = BaseEncoding.base64().encode(cryptogram.getMac()); return new EciesEncryptedResponse(encryptedDataBase64, macBase64); } catch (Exception ex) { logger.debug("Response encryption failed, error: " + ex.getMessage(), ex); @@ -215,6 +215,7 @@ public EciesEncryptedResponse encryptResponse(Object responseObject, PowerAuthEc * @return Request object. * @throws IOException In case request object could not be deserialized. */ + @SuppressWarnings("unchecked") // byte[] conversion to T is unchecked, detected when compiling with new Java private T deserializeRequestData(byte[] requestData, Class requestType) throws IOException { if (requestType.equals(byte[].class)) { // Raw data without deserialization from JSON @@ -262,7 +263,7 @@ private EciesEncryptionContext extractEciesEncryptionContext(HttpServletRequest // In case the PowerAuth signature HTTP header is present, use it for ECIES if (signatureHttpHeader != null) { // Parse signature HTTP header - PowerAuthSignatureHttpHeader header = new PowerAuthSignatureHttpHeader().fromValue(signatureHttpHeader); + final PowerAuthSignatureHttpHeader header = new PowerAuthSignatureHttpHeader().fromValue(signatureHttpHeader); // Validate the signature HTTP header try { @@ -274,13 +275,13 @@ private EciesEncryptionContext extractEciesEncryptionContext(HttpServletRequest } // Construct encryption parameters object - String applicationKey = header.getApplicationKey(); - String activationId = header.getActivationId(); - String version = header.getVersion(); + final String applicationKey = header.getApplicationKey(); + final String activationId = header.getActivationId(); + final String version = header.getVersion(); return new EciesEncryptionContext(applicationKey, activationId, version, header); } else { // Parse encryption HTTP header - PowerAuthEncryptionHttpHeader header = new PowerAuthEncryptionHttpHeader().fromValue(encryptionHttpHeader); + final PowerAuthEncryptionHttpHeader header = new PowerAuthEncryptionHttpHeader().fromValue(encryptionHttpHeader); // Validate the encryption HTTP header try { @@ -292,9 +293,9 @@ private EciesEncryptionContext extractEciesEncryptionContext(HttpServletRequest } // Construct encryption parameters object - String applicationKey = header.getApplicationKey(); - String activationId = header.getActivationId(); - String version = header.getVersion(); + final String applicationKey = header.getApplicationKey(); + final String activationId = header.getActivationId(); + final String version = header.getVersion(); return new EciesEncryptionContext(applicationKey, activationId, version, header); } } diff --git a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthAnnotationInterceptor.java b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthAnnotationInterceptor.java index fff22dec..715b76a0 100644 --- a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthAnnotationInterceptor.java +++ b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthAnnotationInterceptor.java @@ -48,6 +48,11 @@ import java.util.Map; import java.util.TreeMap; +/** + * Interceptor class for the PowerAuth related annotations: @PowerAuth, @PowerAuthToken and @PowerAuthEncryption. + * + * @author Petr Dvorak, petr@wultra.com + */ @Component public class PowerAuthAnnotationInterceptor implements AsyncHandlerInterceptor { @@ -56,11 +61,19 @@ public class PowerAuthAnnotationInterceptor implements AsyncHandlerInterceptor { private PowerAuthAuthenticationProvider authenticationProvider; private PowerAuthEncryptionProvider encryptionProvider; + /** + * Set authentication provider via setter injection. + * @param authenticationProvider Authentication provider. + */ @Autowired public void setAuthenticationProvider(PowerAuthAuthenticationProvider authenticationProvider) { this.authenticationProvider = authenticationProvider; } + /** + * Set encryption provider via setter injection. + * @param encryptionProvider Encryption provider. + */ @Autowired public void setEncryptionProvider(PowerAuthEncryptionProvider encryptionProvider) { this.encryptionProvider = encryptionProvider; diff --git a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthEncryption.java b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthEncryption.java index 7570f5b0..f186fda5 100644 --- a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthEncryption.java +++ b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/annotation/PowerAuthEncryption.java @@ -35,6 +35,11 @@ @Target(ElementType.METHOD) public @interface PowerAuthEncryption { + /** + * Encryption scope, either EciesScope.ACTIVATION_SCOPE or EciesScope.APPLICATION_SCOPE. + * @see EciesScope + * @return Encryption scope. + */ EciesScope scope() default EciesScope.ACTIVATION_SCOPE; } diff --git a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/authentication/PowerAuthApiAuthenticationImpl.java b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/authentication/PowerAuthApiAuthenticationImpl.java index 42aa203b..c150b188 100644 --- a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/authentication/PowerAuthApiAuthenticationImpl.java +++ b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/authentication/PowerAuthApiAuthenticationImpl.java @@ -43,13 +43,44 @@ public class PowerAuthApiAuthenticationImpl extends AbstractAuthenticationToken private static final long serialVersionUID = -3790516505615465445L; + /** + * Activation ID. + */ private String activationId; + + /** + * User ID. + */ private String userId; + + /** + * Application ID. + */ private Long applicationId; + + /** + * List of application roles. + */ private List applicationRoles; + + /** + * List of activation flags. + */ private List activationFlags; + + /** + * Signature type, representing used authentication factor. + */ private PowerAuthSignatureTypes factors; + + /** + * Signature version. + */ private String version; + + /** + * Reference to the original HTTP header. + */ private PowerAuthHttpHeader httpHeader; /** diff --git a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/authentication/PowerAuthSignatureAuthenticationImpl.java b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/authentication/PowerAuthSignatureAuthenticationImpl.java index 543a82a8..c9bf4d3b 100644 --- a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/authentication/PowerAuthSignatureAuthenticationImpl.java +++ b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/authentication/PowerAuthSignatureAuthenticationImpl.java @@ -34,16 +34,60 @@ public class PowerAuthSignatureAuthenticationImpl extends AbstractAuthentication private static final long serialVersionUID = 6495166873663643144L; + /** + * Activation ID. + */ private String activationId; + + /** + * Application key. + */ private String applicationKey; + + /** + * Signature value. + */ private String signature; + + /** + * Signature type. + */ private String signatureType; + + /** + * Request URI identifier. + */ private String requestUri; + + /** + * Used HTTP method. + */ private String httpMethod; + + /** + * Cryptographic nonce. + */ private byte[] nonce; + + /** + * Signed data. + */ private byte[] data; + + /** + * Signature version. + */ private String version; + + /** + * Forced signature version. Used during scheme upgrade, when the element already uses new signature type but + * some parts of the process still need to work with the old one. + */ private Integer forcedSignatureVersion; + + /** + * Reference to the original HTTP header. + */ private PowerAuthHttpHeader httpHeader; /** diff --git a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/authentication/PowerAuthTokenAuthenticationImpl.java b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/authentication/PowerAuthTokenAuthenticationImpl.java index 61886df0..b2659d81 100644 --- a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/authentication/PowerAuthTokenAuthenticationImpl.java +++ b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/authentication/PowerAuthTokenAuthenticationImpl.java @@ -30,11 +30,34 @@ */ public class PowerAuthTokenAuthenticationImpl extends AbstractAuthenticationToken implements PowerAuthTokenAuthentication { + /** + * Token ID. + */ private String tokenId; + + /** + * Token digest value. + */ private String tokenDigest; + + /** + * Cryptographic nonce. + */ private String nonce; + + /** + * Current timestamp. + */ private String timestamp; + + /** + * Signature version. + */ private String version; + + /** + * Reference to the original HTTP header. + */ private PowerAuthHttpHeader httpHeader; /** diff --git a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/encryption/EncryptorFactory.java b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/encryption/EncryptorFactory.java index 0a2f8ecd..7e81b2fb 100644 --- a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/encryption/EncryptorFactory.java +++ b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/encryption/EncryptorFactory.java @@ -42,9 +42,16 @@ public class EncryptorFactory { private static final Logger logger = LoggerFactory.getLogger(EncryptorFactory.class); private PowerAuthClient powerAuthClient; + /** + * Default constructor. + */ public EncryptorFactory() { } + /** + * Set PowerAuth client via the setter injection. + * @param powerAuthClient PowerAuth client. + */ @Autowired public void setPowerAuthClient(PowerAuthClient powerAuthClient) { this.powerAuthClient = powerAuthClient; diff --git a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/filter/EncryptionResponseBodyAdvice.java b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/filter/EncryptionResponseBodyAdvice.java index b6f16372..c3488ea9 100644 --- a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/filter/EncryptionResponseBodyAdvice.java +++ b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/filter/EncryptionResponseBodyAdvice.java @@ -67,7 +67,11 @@ public class EncryptionResponseBodyAdvice implements ResponseBodyAdvice private RequestMappingHandlerAdapter requestMappingHandlerAdapter; - // Autowiring in constructor cannot be used due to circular dependency + /** + * Set request mapping handler adapter via setter injection. Note: Autowiring in constructor cannot be + * used due to circular dependency. + * @param requestMappingHandlerAdapter Request mapping handler adapter. + */ @Autowired public void setRequestMappingHandlerAdapter(RequestMappingHandlerAdapter requestMappingHandlerAdapter) { this.requestMappingHandlerAdapter = requestMappingHandlerAdapter; @@ -118,12 +122,12 @@ public Object beforeBodyWrite(Object response, @NonNull MethodParameter methodPa // Encrypt response using decryptor and return ECIES cryptogram final EciesDecryptor eciesDecryptor = eciesEncryption.getEciesDecryptor(); - EciesCryptogram cryptogram = eciesDecryptor.encryptResponse(responseBytes); - String encryptedDataBase64 = BaseEncoding.base64().encode(cryptogram.getEncryptedData()); - String macBase64 = BaseEncoding.base64().encode(cryptogram.getMac()); + final EciesCryptogram cryptogram = eciesDecryptor.encryptResponse(responseBytes); + final String encryptedDataBase64 = BaseEncoding.base64().encode(cryptogram.getEncryptedData()); + final String macBase64 = BaseEncoding.base64().encode(cryptogram.getMac()); // Return encrypted response with type given by converter class - EciesEncryptedResponse encryptedResponse = new EciesEncryptedResponse(encryptedDataBase64, macBase64); + final EciesEncryptedResponse encryptedResponse = new EciesEncryptedResponse(encryptedDataBase64, macBase64); if (converterClass.isAssignableFrom(MappingJackson2HttpMessageConverter.class)) { // Object conversion is done automatically using MappingJackson2HttpMessageConverter return encryptedResponse; @@ -170,11 +174,11 @@ private byte[] serializeResponseObject(Object response) throws IOException { */ @SuppressWarnings("unchecked") private byte[] convertEncryptedResponse(EciesEncryptedResponse encryptedResponse, MediaType mediaType) throws IOException { - List> httpMessageConverters = requestMappingHandlerAdapter.getMessageConverters(); + final List> httpMessageConverters = requestMappingHandlerAdapter.getMessageConverters(); // Find the first applicable HTTP message converter for conversion for (HttpMessageConverter converter: httpMessageConverters) { if (converter.canWrite(encryptedResponse.getClass(), mediaType)) { - BasicHttpOutputMessage httpOutputMessage = new BasicHttpOutputMessage(); + final BasicHttpOutputMessage httpOutputMessage = new BasicHttpOutputMessage(); ((HttpMessageConverter) converter).write(encryptedResponse, mediaType, httpOutputMessage); return httpOutputMessage.getBodyBytes(); } diff --git a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/provider/PowerAuthAuthenticationProvider.java b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/provider/PowerAuthAuthenticationProvider.java index 83c795bd..3a54dfc7 100644 --- a/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/provider/PowerAuthAuthenticationProvider.java +++ b/powerauth-restful-security-spring-annotation/src/main/java/io/getlime/security/powerauth/rest/api/spring/provider/PowerAuthAuthenticationProvider.java @@ -66,11 +66,23 @@ public class PowerAuthAuthenticationProvider extends PowerAuthAuthenticationProv private PowerAuthClient powerAuthClient; + /** + * Set PowerAuth service client via setter injection. + * + * @param powerAuthClient PowerAuth service client. + */ @Autowired public void setPowerAuthClient(PowerAuthClient powerAuthClient) { this.powerAuthClient = powerAuthClient; } + /** + * Authenticate user using the provided authentication. + * + * @param authentication Authentication used to verify the user. + * @return Authentication with the authenticated user details. + * @throws AuthenticationException In case authentication fails. + */ public Authentication authenticate(Authentication authentication) throws AuthenticationException { // Handle signature based authentications if (authentication instanceof PowerAuthSignatureAuthenticationImpl) { @@ -94,13 +106,13 @@ private PowerAuthApiAuthenticationImpl validateSignatureAuthentication(PowerAuth if (authentication.getSignatureType() != null) { - SignatureTypeConverter converter = new SignatureTypeConverter(); + final SignatureTypeConverter converter = new SignatureTypeConverter(); final SignatureType signatureType = converter.convertFrom(authentication.getSignatureType()); if (signatureType == null) { return null; } - VerifySignatureRequest request = new VerifySignatureRequest(); + final VerifySignatureRequest request = new VerifySignatureRequest(); request.setActivationId(authentication.getActivationId()); request.setApplicationKey(authentication.getApplicationKey()); request.setSignature(authentication.getSignature()); @@ -119,7 +131,7 @@ private PowerAuthApiAuthenticationImpl validateSignatureAuthentication(PowerAuth request.setForcedSignatureVersion(authentication.getForcedSignatureVersion().longValue()); } - VerifySignatureResponse response; + final VerifySignatureResponse response; try { response = powerAuthClient.verifySignature(request); } catch (PowerAuthClientException ex) { @@ -148,7 +160,7 @@ private PowerAuthApiAuthenticationImpl validateSignatureAuthentication(PowerAuth */ private PowerAuthApiAuthenticationImpl validateTokenAuthentication(PowerAuthTokenAuthenticationImpl authentication) { try { - ValidateTokenRequest soapRequest = new ValidateTokenRequest(); + final ValidateTokenRequest soapRequest = new ValidateTokenRequest(); soapRequest.setTokenId(authentication.getTokenId()); soapRequest.setTokenDigest(authentication.getTokenDigest()); soapRequest.setNonce(authentication.getNonce()); @@ -188,7 +200,7 @@ private PowerAuthApiAuthenticationImpl validateTokenAuthentication(PowerAuthToke private PowerAuthApiAuthenticationImpl copyAuthenticationAttributes(String activationId, String userId, Long applicationId, List applicationRoles, List activationFlags, PowerAuthSignatureTypes signatureType, String version, PowerAuthHttpHeader httpHeader) { - PowerAuthApiAuthenticationImpl apiAuthentication = new PowerAuthApiAuthenticationImpl(); + final PowerAuthApiAuthenticationImpl apiAuthentication = new PowerAuthApiAuthenticationImpl(); apiAuthentication.setActivationId(activationId); apiAuthentication.setUserId(userId); apiAuthentication.setApplicationId(applicationId); @@ -229,7 +241,7 @@ public PowerAuthApiAuthentication validateRequestSignature( } // Parse HTTP header - PowerAuthSignatureHttpHeader header = new PowerAuthSignatureHttpHeader().fromValue(httpAuthorizationHeader); + final PowerAuthSignatureHttpHeader header = new PowerAuthSignatureHttpHeader().fromValue(httpAuthorizationHeader); // Validate the header try { @@ -241,14 +253,14 @@ public PowerAuthApiAuthentication validateRequestSignature( } // Check if the signature type is allowed - PowerAuthSignatureTypes expectedSignatureType = PowerAuthSignatureTypes.getEnumFromString(header.getSignatureType()); + final PowerAuthSignatureTypes expectedSignatureType = PowerAuthSignatureTypes.getEnumFromString(header.getSignatureType()); if (expectedSignatureType == null || !allowedSignatureTypes.contains(expectedSignatureType)) { logger.warn("Invalid signature type: {}", expectedSignatureType); throw new PowerAuthSignatureTypeInvalidException(); } // Configure PowerAuth authentication object - PowerAuthSignatureAuthenticationImpl powerAuthAuthentication = new PowerAuthSignatureAuthenticationImpl(); + final PowerAuthSignatureAuthenticationImpl powerAuthAuthentication = new PowerAuthSignatureAuthenticationImpl(); powerAuthAuthentication.setActivationId(header.getActivationId()); powerAuthAuthentication.setApplicationKey(header.getApplicationKey()); powerAuthAuthentication.setNonce(BaseEncoding.base64().decode(header.getNonce())); @@ -262,7 +274,7 @@ public PowerAuthApiAuthentication validateRequestSignature( powerAuthAuthentication.setForcedSignatureVersion(forcedSignatureVersion); // Call the authentication based on signature authentication object - PowerAuthApiAuthentication auth = (PowerAuthApiAuthentication) this.authenticate(powerAuthAuthentication); + final PowerAuthApiAuthentication auth = (PowerAuthApiAuthentication) this.authenticate(powerAuthAuthentication); // In case authentication is null, throw PowerAuth exception if (auth == null) { @@ -273,6 +285,14 @@ public PowerAuthApiAuthentication validateRequestSignature( return auth; } + /** + * Validate token header for simple token-based authentication. + * + * @param tokenHeader Token header. + * @param allowedSignatureTypes Allowed types of the signature. + * @return Authentication object in case authentication is correctly obtained. + * @throws PowerAuthAuthenticationException In case of authentication failure. + */ public PowerAuthApiAuthentication validateToken(String tokenHeader, List allowedSignatureTypes) throws PowerAuthAuthenticationException { // Check for HTTP PowerAuth signature header @@ -282,7 +302,7 @@ public PowerAuthApiAuthentication validateToken(String tokenHeader, List context = new LinkedHashMap<>(); + final Map context = new LinkedHashMap<>(); Map processedCustomAttributes = customAttributes; // In case a custom activation provider is enabled, process custom attributes and save any flags @@ -178,10 +190,10 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request } // Create context for passing parameters between activation provider calls - Map context = new LinkedHashMap<>(); + final Map context = new LinkedHashMap<>(); // Lookup user ID using a provided identity attributes - String userId = activationProvider.lookupUserIdForAttributes(identity, context); + final String userId = activationProvider.lookupUserIdForAttributes(identity, context); // If no user was found or user ID is invalid, return an error if (userId == null || userId.equals("") || userId.length() > 255) { @@ -201,7 +213,7 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request } // Create activation for a looked up user and application related to the given application key - CreateActivationResponse response = powerAuthClient.createActivation( + final CreateActivationResponse response = powerAuthClient.createActivation( userId, activationExpireTimestamp, maxFailedCount, @@ -216,24 +228,24 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request final Map processedCustomAttributes = activationProvider.processCustomActivationAttributes(customAttributes, response.getActivationId(), userId, response.getApplicationId(), ActivationType.CUSTOM, context); // Save activation flags in case the provider specified any flags - List activationFlags = activationProvider.getActivationFlags(identity, processedCustomAttributes, response.getActivationId(), userId, response.getApplicationId(), ActivationType.CUSTOM, context); + final List activationFlags = activationProvider.getActivationFlags(identity, processedCustomAttributes, response.getActivationId(), userId, response.getApplicationId(), ActivationType.CUSTOM, context); if (activationFlags != null && !activationFlags.isEmpty()) { powerAuthClient.addActivationFlags(response.getActivationId(), activationFlags); } // Check if activation should be committed instantly and if yes, perform commit if (activationProvider.shouldAutoCommitActivation(identity, customAttributes, response.getActivationId(), userId, response.getApplicationId(), ActivationType.CUSTOM, context)) { - CommitActivationResponse commitResponse = powerAuthClient.commitActivation(response.getActivationId(), null); + final CommitActivationResponse commitResponse = powerAuthClient.commitActivation(response.getActivationId(), null); if (commitResponse.isActivated()) { activationProvider.activationWasCommitted(identity, customAttributes, response.getActivationId(), userId, response.getApplicationId(), ActivationType.CUSTOM, context); } } // Prepare encrypted activation data - EciesEncryptedResponse encryptedActivationData = new EciesEncryptedResponse(response.getEncryptedData(), response.getMac()); + final EciesEncryptedResponse encryptedActivationData = new EciesEncryptedResponse(response.getEncryptedData(), response.getMac()); // Prepare the created activation response data - ActivationLayer1Response responseL1 = new ActivationLayer1Response(); + final ActivationLayer1Response responseL1 = new ActivationLayer1Response(); responseL1.setCustomAttributes(processedCustomAttributes); responseL1.setActivationData(encryptedActivationData); @@ -251,8 +263,8 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request } // Extract data from request and encryption object - String recoveryCode = identity.get("recoveryCode"); - String recoveryPuk = identity.get("puk"); + final String recoveryCode = identity.get("recoveryCode"); + final String recoveryPuk = identity.get("puk"); if (recoveryCode == null || recoveryCode.isEmpty()) { logger.warn("Recovery code is missing"); @@ -265,7 +277,7 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request } // Create context for passing parameters between activation provider calls - Map context = new LinkedHashMap<>(); + final Map context = new LinkedHashMap<>(); // Resolve maxFailedCount, user ID is not known Long maxFailedCount = null; @@ -275,13 +287,13 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request } // Call RecoveryCodeActivation method on PA server - RecoveryCodeActivationResponse response = powerAuthClient.createActivationUsingRecoveryCode(recoveryCode, recoveryPuk, applicationKey, maxFailedCount, ephemeralPublicKey, encryptedData, mac, nonce); + final RecoveryCodeActivationResponse response = powerAuthClient.createActivationUsingRecoveryCode(recoveryCode, recoveryPuk, applicationKey, maxFailedCount, ephemeralPublicKey, encryptedData, mac, nonce); Map processedCustomAttributes = customAttributes; // In case a custom activation provider is enabled, process custom attributes and save any flags if (activationProvider != null) { processedCustomAttributes = activationProvider.processCustomActivationAttributes(customAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.RECOVERY, context); - List activationFlags = activationProvider.getActivationFlags(identity, processedCustomAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.RECOVERY, context); + final List activationFlags = activationProvider.getActivationFlags(identity, processedCustomAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.RECOVERY, context); if (activationFlags != null && !activationFlags.isEmpty()) { powerAuthClient.addActivationFlags(response.getActivationId(), activationFlags); } @@ -289,7 +301,7 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request // Automatically commit activation by default, the optional activation provider can override automatic commit if (activationProvider == null || activationProvider.shouldAutoCommitActivation(identity, customAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.RECOVERY, context)) { - CommitActivationResponse commitResponse = powerAuthClient.commitActivation(response.getActivationId(), null); + final CommitActivationResponse commitResponse = powerAuthClient.commitActivation(response.getActivationId(), null); if (activationProvider != null && commitResponse.isActivated()) { activationProvider.activationWasCommitted(identity, customAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.RECOVERY, context); } @@ -305,7 +317,7 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request } } catch (PowerAuthClientException ex) { if (ex.getPowerAuthError() instanceof PowerAuthErrorRecovery) { - PowerAuthErrorRecovery errorRecovery = (PowerAuthErrorRecovery) ex.getPowerAuthError(); + final PowerAuthErrorRecovery errorRecovery = (PowerAuthErrorRecovery) ex.getPowerAuthError(); logger.debug("Invalid recovery code, current PUK index: {}", errorRecovery.getCurrentRecoveryPukIndex()); throw new PowerAuthRecoveryException(ex.getMessage(), "INVALID_RECOVERY_CODE", errorRecovery.getCurrentRecoveryPukIndex()); } @@ -333,10 +345,10 @@ public ActivationLayer1Response createActivation(ActivationLayer1Request request */ public ActivationStatusResponse getActivationStatus(ActivationStatusRequest request) throws PowerAuthActivationException { try { - String activationId = request.getActivationId(); - String challenge = request.getChallenge(); - GetActivationStatusResponse paResponse = powerAuthClient.getActivationStatusWithEncryptedStatusBlob(activationId, challenge); - ActivationStatusResponse response = new ActivationStatusResponse(); + final String activationId = request.getActivationId(); + final String challenge = request.getChallenge(); + final GetActivationStatusResponse paResponse = powerAuthClient.getActivationStatusWithEncryptedStatusBlob(activationId, challenge); + final ActivationStatusResponse response = new ActivationStatusResponse(); response.setActivationId(paResponse.getActivationId()); response.setEncryptedStatusBlob(paResponse.getEncryptedStatusBlob()); response.setNonce(paResponse.getEncryptedStatusBlobNonce()); @@ -377,7 +389,7 @@ public ActivationRemoveResponse removeActivation(PowerAuthApiAuthentication apiA } // Prepare and return the response - ActivationRemoveResponse response = new ActivationRemoveResponse(); + final ActivationRemoveResponse response = new ActivationRemoveResponse(); response.setActivationId(paResponse.getActivationId()); return response; } catch (Exception ex) { @@ -397,12 +409,12 @@ public ActivationRemoveResponse removeActivation(PowerAuthApiAuthentication apiA */ private ActivationLayer1Response prepareEncryptedResponse(String encryptedData, String mac, Map processedCustomAttributes) { // Prepare encrypted response object for layer 2 - EciesEncryptedResponse encryptedResponseL2 = new EciesEncryptedResponse(); + final EciesEncryptedResponse encryptedResponseL2 = new EciesEncryptedResponse(); encryptedResponseL2.setEncryptedData(encryptedData); encryptedResponseL2.setMac(mac); // The response is encrypted once more before sent to client using ResponseBodyAdvice - ActivationLayer1Response responseL1 = new ActivationLayer1Response(); + final ActivationLayer1Response responseL1 = new ActivationLayer1Response(); responseL1.setCustomAttributes(processedCustomAttributes); responseL1.setActivationData(encryptedResponseL2); return responseL1; diff --git a/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/RecoveryService.java b/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/RecoveryService.java index d658146e..bc6e0054 100644 --- a/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/RecoveryService.java +++ b/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/RecoveryService.java @@ -77,7 +77,7 @@ public EciesEncryptedResponse confirmRecoveryCode(EciesEncryptedRequest request, logger.warn("PowerAuth confirm recovery failed because of invalid request"); throw new PowerAuthInvalidRequestException(); } - ConfirmRecoveryCodeResponse paResponse = powerAuthClient.confirmRecoveryCode(activationId, applicationKey, + final ConfirmRecoveryCodeResponse paResponse = powerAuthClient.confirmRecoveryCode(activationId, applicationKey, request.getEphemeralPublicKey(), request.getEncryptedData(), request.getMac(), request.getNonce()); if (!paResponse.getActivationId().equals(activationId)) { logger.warn("PowerAuth confirm recovery failed because of invalid activation ID in response"); diff --git a/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/SecureVaultService.java b/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/SecureVaultService.java index 34c5637f..6941eda9 100644 --- a/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/SecureVaultService.java +++ b/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/SecureVaultService.java @@ -60,11 +60,19 @@ public class SecureVaultService { private static final Logger logger = LoggerFactory.getLogger(SecureVaultService.class); + /** + * Set PowerAuth service client via setter injection. + * @param powerAuthClient PowerAuth service client. + */ @Autowired public void setPowerAuthClient(PowerAuthClient powerAuthClient) { this.powerAuthClient = powerAuthClient; } + /** + * Set PowerAuth authentication provider via setter injection. + * @param authenticationProvider PowerAuth authentication provider. + */ @Autowired public void setAuthenticationProvider(PowerAuthAuthenticationProvider authenticationProvider) { this.authenticationProvider = authenticationProvider; @@ -83,18 +91,18 @@ public EciesEncryptedResponse vaultUnlock(PowerAuthSignatureHttpHeader header, EciesEncryptedRequest request, HttpServletRequest httpServletRequest) throws PowerAuthSecureVaultException, PowerAuthAuthenticationException { try { - SignatureTypeConverter converter = new SignatureTypeConverter(); + final SignatureTypeConverter converter = new SignatureTypeConverter(); - String activationId = header.getActivationId(); - String applicationKey = header.getApplicationKey(); - String signature = header.getSignature(); - SignatureType signatureType = converter.convertFrom(header.getSignatureType()); + final String activationId = header.getActivationId(); + final String applicationKey = header.getApplicationKey(); + final String signature = header.getSignature(); + final SignatureType signatureType = converter.convertFrom(header.getSignatureType()); if (signatureType == null) { logger.warn("Invalid signature type: {}", header.getSignatureType()); throw new PowerAuthSignatureTypeInvalidException(); } - String signatureVersion = header.getVersion(); - String nonce = header.getNonce(); + final String signatureVersion = header.getVersion(); + final String nonce = header.getNonce(); // Fetch data from the request final String ephemeralPublicKey = request.getEphemeralPublicKey(); @@ -103,11 +111,11 @@ public EciesEncryptedResponse vaultUnlock(PowerAuthSignatureHttpHeader header, final String eciesNonce = request.getNonce(); // Prepare data for signature to allow signature verification on PowerAuth server - byte[] requestBodyBytes = authenticationProvider.extractRequestBodyBytes(httpServletRequest); - String data = PowerAuthHttpBody.getSignatureBaseString("POST", "/pa/vault/unlock", BaseEncoding.base64().decode(nonce), requestBodyBytes); + final byte[] requestBodyBytes = authenticationProvider.extractRequestBodyBytes(httpServletRequest); + final String data = PowerAuthHttpBody.getSignatureBaseString("POST", "/pa/vault/unlock", BaseEncoding.base64().decode(nonce), requestBodyBytes); // Verify signature and get encrypted vault encryption key from PowerAuth server - VaultUnlockResponse paResponse = powerAuthClient.unlockVault(activationId, applicationKey, signature, + final VaultUnlockResponse paResponse = powerAuthClient.unlockVault(activationId, applicationKey, signature, signatureType, signatureVersion, data, ephemeralPublicKey, encryptedData, mac, eciesNonce); if (!paResponse.isSignatureValid()) { diff --git a/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/TokenService.java b/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/TokenService.java index 6d033e77..ec28f210 100644 --- a/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/TokenService.java +++ b/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/TokenService.java @@ -55,6 +55,10 @@ public class TokenService { private PowerAuthClient powerAuthClient; + /** + * Set PowerAuth service client via setter injection. + * @param powerAuthClient PowerAuth service client. + */ @Autowired public void setPowerAuthClient(PowerAuthClient powerAuthClient) { this.powerAuthClient = powerAuthClient; @@ -82,17 +86,17 @@ public EciesEncryptedResponse createToken(EciesEncryptedRequest request, final String nonce = request.getNonce(); // Prepare a signature type converter - SignatureTypeConverter converter = new SignatureTypeConverter(); - SignatureType signatureType = converter.convertFrom(signatureFactors); + final SignatureTypeConverter converter = new SignatureTypeConverter(); + final SignatureType signatureType = converter.convertFrom(signatureFactors); if (signatureType == null) { logger.warn("Invalid signature type: {}", signatureFactors); throw new PowerAuthSignatureTypeInvalidException(); } // Get ECIES headers - String activationId = authentication.getActivationId(); - PowerAuthSignatureHttpHeader httpHeader = (PowerAuthSignatureHttpHeader) authentication.getHttpHeader(); - String applicationKey = httpHeader.getApplicationKey(); + final String activationId = authentication.getActivationId(); + final PowerAuthSignatureHttpHeader httpHeader = (PowerAuthSignatureHttpHeader) authentication.getHttpHeader(); + final String applicationKey = httpHeader.getApplicationKey(); // Create a token final CreateTokenResponse token = powerAuthClient.createToken(activationId, applicationKey, ephemeralPublicKey, diff --git a/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/UpgradeService.java b/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/UpgradeService.java index 085e3490..ea59ec39 100644 --- a/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/UpgradeService.java +++ b/powerauth-restful-security-spring/src/main/java/io/getlime/security/powerauth/rest/api/spring/service/v3/UpgradeService.java @@ -62,11 +62,19 @@ public class UpgradeService { private PowerAuthClient powerAuthClient; private PowerAuthAuthenticationProvider authenticationProvider; + /** + * Set PowerAuth service client via setter injection. + * @param powerAuthClient PowerAuth service client. + */ @Autowired public void setPowerAuthClient(PowerAuthClient powerAuthClient) { this.powerAuthClient = powerAuthClient; } + /** + * Set PowerAuth authentication provider via setter injection. + * @param authenticationProvider PowerAuth authentication provider. + */ @Autowired public void setAuthenticationProvider(PowerAuthAuthenticationProvider authenticationProvider) { this.authenticationProvider = authenticationProvider; @@ -94,7 +102,7 @@ public EciesEncryptedResponse upgradeStart(EciesEncryptedRequest request, PowerA final String applicationKey = header.getApplicationKey(); // Start upgrade on PowerAuth server - StartUpgradeResponse upgradeResponse = powerAuthClient.startUpgrade(activationId, applicationKey, ephemeralPublicKey, encryptedData, mac, nonce); + final StartUpgradeResponse upgradeResponse = powerAuthClient.startUpgrade(activationId, applicationKey, ephemeralPublicKey, encryptedData, mac, nonce); // Prepare a response final EciesEncryptedResponse response = new EciesEncryptedResponse(); @@ -122,7 +130,7 @@ public Response upgradeCommit(String signatureHeader, try { // Extract request body - byte[] requestBodyBytes = authenticationProvider.extractRequestBodyBytes(httpServletRequest); + final byte[] requestBodyBytes = authenticationProvider.extractRequestBodyBytes(httpServletRequest); if (requestBodyBytes == null || requestBodyBytes.length == 0) { // Expected request body is {}, do not accept empty body logger.warn("Empty request body"); @@ -130,8 +138,8 @@ public Response upgradeCommit(String signatureHeader, } // Verify signature, force signature version during upgrade to version 3 - List allowedSignatureTypes = Collections.singletonList(PowerAuthSignatureTypes.POSSESSION); - PowerAuthApiAuthentication authentication = authenticationProvider.validateRequestSignature("POST", requestBodyBytes, "/pa/upgrade/commit", signatureHeader, allowedSignatureTypes, 3); + final List allowedSignatureTypes = Collections.singletonList(PowerAuthSignatureTypes.POSSESSION); + final PowerAuthApiAuthentication authentication = authenticationProvider.validateRequestSignature("POST", requestBodyBytes, "/pa/upgrade/commit", signatureHeader, allowedSignatureTypes, 3); // In case signature verification fails, upgrade fails, too if (authentication == null || authentication.getActivationId() == null) { @@ -145,7 +153,7 @@ public Response upgradeCommit(String signatureHeader, final String applicationKey = httpHeader.getApplicationKey(); // Commit upgrade on PowerAuth server - CommitUpgradeResponse upgradeResponse = powerAuthClient.commitUpgrade(activationId, applicationKey); + final CommitUpgradeResponse upgradeResponse = powerAuthClient.commitUpgrade(activationId, applicationKey); if (upgradeResponse.isCommitted()) { return new Response(); From 6e3f3832bcc4b06a9c49669a87b7e420a817798e Mon Sep 17 00:00:00 2001 From: Roman Strobl Date: Wed, 9 Jun 2021 10:25:35 +0200 Subject: [PATCH 8/8] Fix #282: Update version to 1.1.0 --- pom.xml | 4 ++-- powerauth-restful-model/pom.xml | 4 ++-- powerauth-restful-security-base/pom.xml | 10 +++++----- powerauth-restful-security-spring-annotation/pom.xml | 8 ++++---- powerauth-restful-security-spring/pom.xml | 8 ++++---- powerauth-restful-server-spring/pom.xml | 4 ++-- 6 files changed, 19 insertions(+), 19 deletions(-) diff --git a/pom.xml b/pom.xml index a533d9c8..9d44a3b4 100644 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,7 @@ io.getlime.security powerauth-restful-integration-parent - 1.1.0-SNAPSHOT + 1.1.0 pom 2017 @@ -89,7 +89,7 @@ 1.9 2.12.3 1.68 - 1.3.0-SNAPSHOT + 1.3.0 diff --git a/powerauth-restful-model/pom.xml b/powerauth-restful-model/pom.xml index 22affa7c..549e74f8 100644 --- a/powerauth-restful-model/pom.xml +++ b/powerauth-restful-model/pom.xml @@ -24,14 +24,14 @@ 4.0.0 powerauth-restful-model - 1.1.0-SNAPSHOT + 1.1.0 powerauth-restful-model Model classes PowerAuth Standard RESTful API io.getlime.security powerauth-restful-integration-parent - 1.1.0-SNAPSHOT + 1.1.0 ../pom.xml diff --git a/powerauth-restful-security-base/pom.xml b/powerauth-restful-security-base/pom.xml index 4bd59fec..2f2a8acf 100644 --- a/powerauth-restful-security-base/pom.xml +++ b/powerauth-restful-security-base/pom.xml @@ -25,12 +25,12 @@ 4.0.0 powerauth-restful-security-base - 1.1.0-SNAPSHOT + 1.1.0 powerauth-restful-integration-parent io.getlime.security - 1.1.0-SNAPSHOT + 1.1.0 ../pom.xml @@ -40,17 +40,17 @@ io.getlime.security powerauth-java-crypto - 1.1.0-SNAPSHOT + 1.1.0 io.getlime.security powerauth-java-http - 1.1.0-SNAPSHOT + 1.1.0 io.getlime.security powerauth-restful-model - 1.1.0-SNAPSHOT + 1.1.0 diff --git a/powerauth-restful-security-spring-annotation/pom.xml b/powerauth-restful-security-spring-annotation/pom.xml index d8f58463..6285bcd2 100644 --- a/powerauth-restful-security-spring-annotation/pom.xml +++ b/powerauth-restful-security-spring-annotation/pom.xml @@ -24,14 +24,14 @@ 4.0.0 powerauth-restful-security-spring-annotation - 1.1.0-SNAPSHOT + 1.1.0 powerauth-restful-security-spring-annotation PowerAuth RESTful API Security Annotations for Spring io.getlime.security powerauth-restful-integration-parent - 1.1.0-SNAPSHOT + 1.1.0 ../pom.xml @@ -53,12 +53,12 @@ io.getlime.security powerauth-restful-security-base - 1.1.0-SNAPSHOT + 1.1.0 io.getlime.security powerauth-rest-client-spring - 1.1.0-SNAPSHOT + 1.1.0 diff --git a/powerauth-restful-security-spring/pom.xml b/powerauth-restful-security-spring/pom.xml index 2684f6dd..fdc1afcf 100644 --- a/powerauth-restful-security-spring/pom.xml +++ b/powerauth-restful-security-spring/pom.xml @@ -24,14 +24,14 @@ 4.0.0 powerauth-restful-security-spring - 1.1.0-SNAPSHOT + 1.1.0 powerauth-restful-security-spring PowerAuth RESTful API Security Additions for Spring io.getlime.security powerauth-restful-integration-parent - 1.1.0-SNAPSHOT + 1.1.0 ../pom.xml @@ -41,12 +41,12 @@ io.getlime.security powerauth-restful-security-spring-annotation - 1.1.0-SNAPSHOT + 1.1.0 io.getlime.security powerauth-rest-client-spring - 1.1.0-SNAPSHOT + 1.1.0 diff --git a/powerauth-restful-server-spring/pom.xml b/powerauth-restful-server-spring/pom.xml index 8e6c8e96..e0a1fe87 100644 --- a/powerauth-restful-server-spring/pom.xml +++ b/powerauth-restful-server-spring/pom.xml @@ -26,7 +26,7 @@ powerauth-restful-server-spring PowerAuth Standard RESTful API powerauth-restful-server-spring - 1.1.0-SNAPSHOT + 1.1.0 war @@ -72,7 +72,7 @@ io.getlime.security powerauth-restful-security-spring - 1.1.0-SNAPSHOT + 1.1.0