├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── release ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── github │ │ └── mkopylec │ │ └── recaptcha │ │ ├── RecaptchaProperties.java │ │ ├── security │ │ ├── RecaptchaAuthenticationException.java │ │ ├── RecaptchaAuthenticationFilter.java │ │ ├── SecurityConfiguration.java │ │ └── login │ │ │ ├── FormLoginConfigurerEnhancer.java │ │ │ ├── InMemoryLoginFailuresManager.java │ │ │ ├── LoginFailuresClearingHandler.java │ │ │ ├── LoginFailuresCountingHandler.java │ │ │ ├── LoginFailuresManager.java │ │ │ └── RecaptchaAwareRedirectStrategy.java │ │ ├── testing │ │ ├── TestRecaptchaValidator.java │ │ └── TestingConfiguration.java │ │ └── validation │ │ ├── DefaultRecaptchaValidator.java │ │ ├── ErrorCode.java │ │ ├── IpAddressResolver.java │ │ ├── RecaptchaValidationException.java │ │ ├── RecaptchaValidator.java │ │ ├── ValidationConfiguration.java │ │ └── ValidationResult.java └── resources │ └── META-INF │ └── spring.factories └── test ├── groovy └── com │ └── github │ └── mkopylec │ └── recaptcha │ ├── BasicSpec.groovy │ ├── assertions │ ├── Assertions.groovy │ └── ResponseAssert.groovy │ ├── specification │ ├── SecuritySpec.groovy │ ├── TestingSpec.groovy │ └── ValidationSpec.groovy │ └── stubs │ └── RecaptchaValidationStubs.groovy ├── java └── com │ └── github │ └── mkopylec │ └── recaptcha │ ├── Strings.java │ ├── TestApplication.java │ ├── security │ ├── AccessConfiguration.java │ ├── ResponseData.java │ └── SecurityController.java │ ├── testing │ └── TestingController.java │ └── validation │ └── ValidationController.java └── resources └── application.yml /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | gradle.properties 4 | .gradle 5 | build 6 | classes 7 | out -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | after_success: 5 | - ./gradlew jacocoTestReport coveralls 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # reCAPTCHA Spring Boot Starter 2 | [![Build Status](https://travis-ci.org/mkopylec/recaptcha-spring-boot-starter.svg?branch=master)](https://travis-ci.org/mkopylec/recaptcha-spring-boot-starter) 3 | [![Coverage Status](https://coveralls.io/repos/mkopylec/recaptcha-spring-boot-starter/badge.svg?branch=master&service=github)](https://coveralls.io/github/mkopylec/recaptcha-spring-boot-starter?branch=master) 4 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.github.mkopylec/recaptcha-spring-boot-starter/badge.svg?style=flat)](https://maven-badges.herokuapp.com/maven-central/com.github.mkopylec/recaptcha-spring-boot-starter) 5 | 6 | To use the starter you will need a reCAPTCHA site key and a secret key. 7 | To get them go to the [reCAPTCHA Home Page](https://www.google.com/recaptcha/intro/index.html) and set up your reCAPTCHA. 8 | 9 | ## Installing 10 | 11 | ```gradle 12 | repositories { 13 | mavenCentral() 14 | } 15 | dependencies { 16 | compile group: 'com.github.mkopylec', name: 'recaptcha-spring-boot-starter', version: '2.3.1' 17 | } 18 | ``` 19 | 20 | ## How to use 21 | The starter can be used in 3 different modes: 22 | 23 | ### Normal web application usage 24 | Embed reCAPTCHA in HTML web page: 25 | 26 | ```html 27 | 28 | 29 | 30 | ... 31 | 32 | 33 | 34 |
35 |
36 | 37 |
38 | 39 | 40 | 41 | ``` 42 | 43 | Inject `RecaptchaValidator` into your controller and validate user reCAPTCHA response: 44 | 45 | ```java 46 | @Controller 47 | public class MainController { 48 | 49 | @Autowired 50 | private RecaptchaValidator recaptchaValidator; 51 | 52 | @PostMapping("/") 53 | public void validateCaptcha(HttpServletRequest request) { 54 | ValidationResult result = recaptchaValidator.validate(request); 55 | if (result.isSuccess()) { 56 | ... 57 | } 58 | } 59 | } 60 | ``` 61 | 62 | Set your secret key in _application.yml_ file: 63 | 64 | ```yaml 65 | recaptcha.validation.secret-key: 66 | ``` 67 | 68 | ##### Additional info 69 | `RecaptchaValidator` provides couple of useful methods to validate reCAPTCHA response. 70 | 71 | ### Spring Security web application usage 72 | Add Spring Security dependency: 73 | 74 | ```gradle 75 | dependencies { 76 | compile group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '2.1.6.RELEASE' 77 | } 78 | ``` 79 | 80 | Embed reCAPTCHA in HTML **login** web page: 81 | 82 | ```html 83 | 84 | 85 | 86 | ... 87 | 88 | 89 | 90 |
91 | User: 92 | Password: 93 | 94 |
95 | 96 | 97 |
98 | 99 | 100 | 101 | ``` 102 | 103 | Add reCAPTCHA support to your form login security configuration using `FormLoginConfigurerEnhancer`. 104 | 105 | ```java 106 | @Configuration 107 | @EnableWebSecurity 108 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 109 | 110 | @Autowired 111 | private FormLoginConfigurerEnhancer enhancer; 112 | 113 | @Override 114 | protected void configure(HttpSecurity http) throws Exception { 115 | enhancer.addRecaptchaSupport(http.formLogin()).loginPage("/login") 116 | .and() 117 | .csrf().disable() 118 | ... 119 | } 120 | } 121 | ``` 122 | 123 | Create custom login failures manager bean by extending `LoginFailuresManager`: 124 | 125 | ```java 126 | @Component 127 | public class CustomLoginFailuresManager extends LoginFailuresManager { 128 | 129 | public CustomLoginFailuresManager(RecaptchaProperties recaptcha) { 130 | super(recaptcha); 131 | } 132 | 133 | ... 134 | } 135 | ``` 136 | 137 | Set your secret key in _application.yml_ file: 138 | 139 | ```yaml 140 | recaptcha.validation.secret-key: 141 | ``` 142 | 143 | ##### Additional info 144 | After adding reCAPTCHA support to form login configuration you can only add `AuthenticationSuccessHandler` that extends 145 | `LoginFailuresClearingHandler` and `AuthenticationFailureHandler` that extends `LoginFailuresCountingHandler`. 146 | 147 | There can be 4 different query parameters in redirect to login page: 148 | - _error_ - credentials authentication error 149 | - _recaptchaError_ - reCAPTCHA authentication error 150 | - _showRecaptcha_ - reCAPTCHA must be displayed on login page 151 | - _logout_ - user has been successfully logged out 152 | 153 | There is a default `LoginFailuresManager` implementation in the starter which is `InMemoryLoginFailuresManager`. 154 | It is recommended to create your own `LoginFailuresManager` implementation that persists login failures in some storage. 155 | 156 | ### Integration testing mode usage 157 | Enable testing mode: 158 | 159 | ```yaml 160 | recaptcha.testing.enabled: true 161 | ``` 162 | 163 | Configure testing mode: 164 | 165 | ```yaml 166 | recaptcha.testing: 167 | success-result: false 168 | result-error-codes: INVALID_SECRET_KEY, INVALID_USER_CAPTCHA_RESPONSE 169 | ``` 170 | 171 | ##### Additional info 172 | In testing mode no remote reCAPTCHA validation is fired, the validation process is offline. 173 | 174 | ## Configuration properties list 175 | 176 | ```yaml 177 | recaptcha: 178 | validation: 179 | secret-key: # reCAPTCHA secret key. 180 | response-parameter: g-recaptcha-response # HTTP request parameter name containing user reCAPTCHA response. 181 | verification-url: https://www.google.com/recaptcha/api/siteverify # reCAPTCHA validation endpoint. 182 | timeout: 183 | connect: 500ms # reCAPTCHA validation request connect timeout. 184 | read: 1000ms # reCAPTCHA validation request read timeout. 185 | write: 1000ms # reCAPTCHA validation request write timeout. 186 | security: 187 | failure-url: /login # URL to redirect to when user authentication fails. 188 | login-failures-threshold: 5 # Number of allowed login failures before reCAPTCHA must be displayed. 189 | continue-on-validation-http-error: true # Permits or denies continuing user authentication process after reCAPTCHA validation fails because of HTTP error. 190 | testing: 191 | enabled: false # Flag for enabling and disabling testing mode. 192 | success-result: true # Defines successful or unsuccessful validation result, can be changed during tests. 193 | result-error-codes: # Errors in validation result, can be changed during tests. 194 | ``` 195 | 196 | ## Examples 197 | Go to [reCAPTCHA Spring Boot Starter samples](https://github.com/mkopylec/recaptcha-spring-boot-starter-samples) to view example applications. 198 | 199 | ## License 200 | reCAPTCHA Spring Boot Starter is published under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0). 201 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'groovy' 3 | id 'maven-publish' 4 | id 'jacoco' 5 | id 'com.github.kt3k.coveralls' version '2.8.4' 6 | id 'maven' 7 | id 'signing' 8 | id 'io.codearte.nexus-staging' version '0.21.0' 9 | id 'pl.allegro.tech.build.axion-release' version '1.10.1' 10 | } 11 | 12 | scmVersion { 13 | tag { 14 | prefix = '' 15 | } 16 | } 17 | 18 | group = 'com.github.mkopylec' 19 | archivesBaseName = name 20 | version = scmVersion.version 21 | 22 | sourceCompatibility = 1.8 23 | 24 | repositories { 25 | mavenCentral() 26 | } 27 | 28 | ext { 29 | springBootVersion = '2.1.6.RELEASE' 30 | } 31 | 32 | dependencies { 33 | 34 | compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: springBootVersion 35 | compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '3.14.2' 36 | 37 | compileOnly group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: springBootVersion 38 | compileOnly group: 'org.springframework.boot', name: 'spring-boot-configuration-processor', version: springBootVersion 39 | 40 | testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: springBootVersion 41 | testCompile group: 'org.spockframework', name: 'spock-spring', version: '1.3-groovy-2.5' 42 | testCompile group: 'com.github.tomakehurst', name: 'wiremock', version: '2.23.2' 43 | } 44 | 45 | configurations { 46 | testCompile.extendsFrom compileOnly 47 | } 48 | 49 | wrapper { 50 | gradleVersion = '5.5.1' 51 | } 52 | 53 | task javadocJar(type: Jar) { 54 | archiveClassifier.set('javadoc') 55 | from javadoc 56 | } 57 | 58 | task sourceJar(type: Jar) { 59 | archiveClassifier.set('sources') 60 | from sourceSets.main.allSource 61 | } 62 | 63 | artifacts { 64 | archives javadocJar, sourceJar 65 | } 66 | 67 | signing { 68 | if (project.ext.has('signArtifacts')) { 69 | sign configurations.archives 70 | } 71 | } 72 | 73 | ext { 74 | ossrhUsername = project.ext.has('ossrhUsername') ? project.ext.ossrhUsername : '' 75 | ossrhPassword = project.ext.has('ossrhPassword') ? project.ext.ossrhPassword : '' 76 | } 77 | 78 | uploadArchives { 79 | repositories { 80 | mavenDeployer { 81 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 82 | repository(url: 'https://oss.sonatype.org/service/local/staging/deploy/maven2/') { 83 | authentication(userName: ossrhUsername, password: ossrhPassword) 84 | } 85 | snapshotRepository(url: 'https://oss.sonatype.org/content/repositories/snapshots/') { 86 | authentication(userName: ossrhUsername, password: ossrhPassword) 87 | } 88 | pom.project { 89 | name 'reCAPTCHA Spring Boot Starter' 90 | packaging 'jar' 91 | description 'Spring Boot starter for Google\'s reCAPTCHA' 92 | url 'https://github.com/mkopylec/recaptcha-spring-boot-starter' 93 | scm { 94 | connection 'scm:git:https://github.com/mkopylec/recaptcha-spring-boot-starter.git' 95 | developerConnection 'scm:git:https://github.com/mkopylec/recaptcha-spring-boot-starter.git' 96 | url 'https://github.com/mkopylec/recaptcha-spring-boot-starter' 97 | } 98 | licenses { 99 | license { 100 | name 'The Apache License, Version 2.0' 101 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 102 | } 103 | } 104 | developers { 105 | developer { 106 | id 'mkopylec' 107 | name 'Mariusz Kopylec' 108 | email 'mariusz.kopylec@o2.pl' 109 | } 110 | } 111 | } 112 | } 113 | } 114 | } 115 | 116 | publishing { 117 | publications { 118 | mavenJava(MavenPublication) { 119 | from components.java 120 | artifact sourceJar 121 | artifact javadocJar 122 | } 123 | } 124 | } 125 | 126 | jacoco { 127 | toolVersion = '0.8.4' 128 | } 129 | 130 | jacocoTestReport { 131 | reports { 132 | xml.enabled = true 133 | html.enabled = true 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mkopylec/recaptcha-spring-boot-starter/7d5a1ff6dcf23e6768e72a7fc271c85cea14588d/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.5.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin, switch paths to Windows format before running java 129 | if $cygwin ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=$((i+1)) 158 | done 159 | case $i in 160 | (0) set -- ;; 161 | (1) set -- "$args0" ;; 162 | (2) set -- "$args0" "$args1" ;; 163 | (3) set -- "$args0" "$args1" "$args2" ;; 164 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=$(save "$@") 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 184 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 185 | cd "$(dirname "$0")" 186 | fi 187 | 188 | exec "$JAVACMD" "$@" 189 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem http://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /release: -------------------------------------------------------------------------------- 1 | while getopts v: opts; do 2 | case ${opts} in 3 | v) VERSION=${OPTARG} ;; 4 | esac 5 | done 6 | 7 | if [ -z "$VERSION" ]; then 8 | echo "Set release version using -v option" 9 | exit 1 10 | else 11 | ./gradlew clean test release -Prelease.forceVersion=$VERSION && ./gradlew uploadArchives -PsignArtifacts && ./gradlew closeAndReleaseRepository 12 | fi -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'recaptcha-spring-boot-starter' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/RecaptchaProperties.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha; 2 | 3 | import com.github.mkopylec.recaptcha.validation.ErrorCode; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | 6 | import java.time.Duration; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | import static java.time.Duration.ofMillis; 11 | import static org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.DEFAULT_LOGIN_PAGE_URL; 12 | 13 | /** 14 | * reCAPTCHA configuration properties. 15 | */ 16 | @ConfigurationProperties("recaptcha") 17 | public class RecaptchaProperties { 18 | 19 | /** 20 | * Properties responsible for reCAPTCHA validation on Google's servers. 21 | */ 22 | private Validation validation = new Validation(); 23 | /** 24 | * Properties responsible for integration with Spring Security. 25 | */ 26 | private Security security = new Security(); 27 | /** 28 | * Properties responsible for testing mode behaviour. 29 | */ 30 | private Testing testing = new Testing(); 31 | 32 | public Validation getValidation() { 33 | return validation; 34 | } 35 | 36 | public void setValidation(Validation validation) { 37 | this.validation = validation; 38 | } 39 | 40 | public Security getSecurity() { 41 | return security; 42 | } 43 | 44 | public void setSecurity(Security security) { 45 | this.security = security; 46 | } 47 | 48 | public Testing getTesting() { 49 | return testing; 50 | } 51 | 52 | public void setTesting(Testing testing) { 53 | this.testing = testing; 54 | } 55 | 56 | public static class Validation { 57 | 58 | /** 59 | * reCAPTCHA secret key. 60 | */ 61 | private String secretKey; 62 | /** 63 | * HTTP request parameter name containing user reCAPTCHA response. 64 | */ 65 | private String responseParameter = "g-recaptcha-response"; 66 | /** 67 | * reCAPTCHA validation endpoint. 68 | */ 69 | private String verificationUrl = "https://www.google.com/recaptcha/api/siteverify"; 70 | /** 71 | * Properties responsible for reCAPTCHA validation request timeout. 72 | */ 73 | private Timeout timeout = new Timeout(); 74 | 75 | public String getSecretKey() { 76 | return secretKey; 77 | } 78 | 79 | public void setSecretKey(String secretKey) { 80 | this.secretKey = secretKey; 81 | } 82 | 83 | public String getResponseParameter() { 84 | return responseParameter; 85 | } 86 | 87 | public void setResponseParameter(String responseParameter) { 88 | this.responseParameter = responseParameter; 89 | } 90 | 91 | public String getVerificationUrl() { 92 | return verificationUrl; 93 | } 94 | 95 | public void setVerificationUrl(String verificationUrl) { 96 | this.verificationUrl = verificationUrl; 97 | } 98 | 99 | public Timeout getTimeout() { 100 | return timeout; 101 | } 102 | 103 | public void setTimeout(Timeout timeout) { 104 | this.timeout = timeout; 105 | } 106 | 107 | public static class Timeout { 108 | 109 | /** 110 | * reCAPTCHA validation request connect timeout. 111 | */ 112 | private Duration connect = ofMillis(500); 113 | /** 114 | * reCAPTCHA validation request read timeout. 115 | */ 116 | private Duration read = ofMillis(1000); 117 | /** 118 | * reCAPTCHA validation request write timeout. 119 | */ 120 | private Duration write = ofMillis(1000); 121 | 122 | public Duration getConnect() { 123 | return connect; 124 | } 125 | 126 | public void setConnect(Duration connect) { 127 | this.connect = connect; 128 | } 129 | 130 | public Duration getRead() { 131 | return read; 132 | } 133 | 134 | public void setRead(Duration read) { 135 | this.read = read; 136 | } 137 | 138 | public Duration getWrite() { 139 | return write; 140 | } 141 | 142 | public void setWrite(Duration write) { 143 | this.write = write; 144 | } 145 | } 146 | } 147 | 148 | public static class Security { 149 | 150 | /** 151 | * URL to redirect to when user authentication fails. 152 | */ 153 | private String failureUrl = DEFAULT_LOGIN_PAGE_URL; 154 | /** 155 | * Number of allowed login failures before reCAPTCHA must be displayed. 156 | */ 157 | private int loginFailuresThreshold = 5; 158 | /** 159 | * Permits on denies continuing user authentication process after reCAPTCHA validation fails because of HTTP error. 160 | */ 161 | private boolean continueOnValidationHttpError = true; 162 | 163 | public String getFailureUrl() { 164 | return failureUrl; 165 | } 166 | 167 | public void setFailureUrl(String failureUrl) { 168 | this.failureUrl = failureUrl; 169 | } 170 | 171 | public int getLoginFailuresThreshold() { 172 | return loginFailuresThreshold; 173 | } 174 | 175 | public void setLoginFailuresThreshold(int loginFailuresThreshold) { 176 | this.loginFailuresThreshold = loginFailuresThreshold; 177 | } 178 | 179 | public boolean isContinueOnValidationHttpError() { 180 | return continueOnValidationHttpError; 181 | } 182 | 183 | public void setContinueOnValidationHttpError(boolean continueOnValidationHttpError) { 184 | this.continueOnValidationHttpError = continueOnValidationHttpError; 185 | } 186 | } 187 | 188 | public static class Testing { 189 | 190 | /** 191 | * Flag for enabling and disabling testing mode. 192 | */ 193 | private boolean enabled = false; 194 | /** 195 | * Defines successful or unsuccessful validation result, can be changed during tests. 196 | */ 197 | private boolean successResult = true; 198 | /** 199 | * Fixed errors in validation result, can be changed during tests. 200 | */ 201 | private List resultErrorCodes = new ArrayList<>(); 202 | 203 | public boolean isEnabled() { 204 | return enabled; 205 | } 206 | 207 | public void setEnabled(boolean enabled) { 208 | this.enabled = enabled; 209 | } 210 | 211 | public boolean isSuccessResult() { 212 | return successResult; 213 | } 214 | 215 | public void setSuccessResult(boolean successResult) { 216 | this.successResult = successResult; 217 | } 218 | 219 | public List getResultErrorCodes() { 220 | return resultErrorCodes; 221 | } 222 | 223 | public void setResultErrorCodes(List resultErrorCodes) { 224 | this.resultErrorCodes = resultErrorCodes; 225 | } 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/security/RecaptchaAuthenticationException.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.security; 2 | 3 | import com.github.mkopylec.recaptcha.validation.ErrorCode; 4 | import org.springframework.security.core.AuthenticationException; 5 | 6 | import java.util.List; 7 | 8 | import static java.util.Collections.unmodifiableList; 9 | 10 | public class RecaptchaAuthenticationException extends AuthenticationException { 11 | 12 | private final List errorCodes; 13 | 14 | public RecaptchaAuthenticationException(List errorCodes) { 15 | super("reCAPTCHA authentication error: " + errorCodes); 16 | this.errorCodes = errorCodes; 17 | } 18 | 19 | public List getErrorCodes() { 20 | return unmodifiableList(errorCodes); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/security/RecaptchaAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.security; 2 | 3 | import com.github.mkopylec.recaptcha.RecaptchaProperties; 4 | import com.github.mkopylec.recaptcha.security.login.LoginFailuresClearingHandler; 5 | import com.github.mkopylec.recaptcha.security.login.LoginFailuresCountingHandler; 6 | import com.github.mkopylec.recaptcha.security.login.LoginFailuresManager; 7 | import com.github.mkopylec.recaptcha.validation.RecaptchaValidationException; 8 | import com.github.mkopylec.recaptcha.validation.RecaptchaValidator; 9 | import com.github.mkopylec.recaptcha.validation.ValidationResult; 10 | import org.slf4j.Logger; 11 | import org.springframework.security.core.Authentication; 12 | import org.springframework.security.core.AuthenticationException; 13 | import org.springframework.security.web.authentication.AuthenticationFailureHandler; 14 | import org.springframework.security.web.authentication.AuthenticationSuccessHandler; 15 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 16 | 17 | import javax.servlet.http.HttpServletRequest; 18 | import javax.servlet.http.HttpServletResponse; 19 | 20 | import static com.github.mkopylec.recaptcha.validation.ErrorCode.MISSING_USERNAME_REQUEST_PARAMETER; 21 | import static com.github.mkopylec.recaptcha.validation.ErrorCode.VALIDATION_HTTP_ERROR; 22 | import static java.util.Collections.singletonList; 23 | import static org.slf4j.LoggerFactory.getLogger; 24 | import static org.springframework.util.Assert.notNull; 25 | 26 | public class RecaptchaAuthenticationFilter extends UsernamePasswordAuthenticationFilter { 27 | 28 | private static final Logger log = getLogger(RecaptchaAuthenticationFilter.class); 29 | 30 | protected final RecaptchaValidator recaptchaValidator; 31 | protected final RecaptchaProperties recaptcha; 32 | protected final LoginFailuresManager failuresManager; 33 | 34 | public RecaptchaAuthenticationFilter( 35 | RecaptchaValidator recaptchaValidator, 36 | RecaptchaProperties recaptcha, 37 | LoginFailuresManager failuresManager 38 | ) { 39 | this.recaptchaValidator = recaptchaValidator; 40 | this.recaptcha = recaptcha; 41 | this.failuresManager = failuresManager; 42 | } 43 | 44 | @Override 45 | public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { 46 | if (getUsernameParameter() == null) { 47 | throw new RecaptchaAuthenticationException(singletonList(MISSING_USERNAME_REQUEST_PARAMETER)); 48 | } 49 | if (failuresManager.isRecaptchaRequired(request)) { 50 | try { 51 | String recaptchaResponse = obtainRecaptchaResponse(request); 52 | ValidationResult result = recaptchaValidator.validate(recaptchaResponse, request); 53 | if (result.isFailure()) { 54 | throw new RecaptchaAuthenticationException(result.getErrorCodes()); 55 | } 56 | } catch (RecaptchaValidationException ex) { 57 | boolean continueAuthentication = recaptcha.getSecurity().isContinueOnValidationHttpError(); 58 | log.error("reCAPTCHA validation HTTP error. Continuing user authentication: " + continueAuthentication, ex); 59 | if (!continueAuthentication) { 60 | throw new RecaptchaAuthenticationException(singletonList(VALIDATION_HTTP_ERROR)); 61 | } 62 | } 63 | } 64 | return super.attemptAuthentication(request, response); 65 | } 66 | 67 | @Override 68 | public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler) { 69 | if (!LoginFailuresClearingHandler.class.isAssignableFrom(successHandler.getClass())) { 70 | throw new IllegalArgumentException("Invalid login success handler. Handler must be an instance of " + LoginFailuresClearingHandler.class.getName() + " but is " + successHandler); 71 | } 72 | super.setAuthenticationSuccessHandler(successHandler); 73 | } 74 | 75 | @Override 76 | public void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) { 77 | if (!LoginFailuresCountingHandler.class.isAssignableFrom(failureHandler.getClass())) { 78 | throw new IllegalArgumentException("Invalid login failure handler. Handler must be an instance of " + LoginFailuresCountingHandler.class.getName() + " but is " + failureHandler); 79 | } 80 | super.setAuthenticationFailureHandler(failureHandler); 81 | } 82 | 83 | @Override 84 | public void setUsernameParameter(String usernameParameter) { 85 | super.setUsernameParameter(usernameParameter); 86 | failuresManager.setUsernameParameter(usernameParameter); 87 | } 88 | 89 | @Override 90 | public void afterPropertiesSet() { 91 | notNull(recaptchaValidator, "Missing recaptcha validator"); 92 | notNull(recaptcha, "Missing recaptcha validation configuration properties"); 93 | notNull(failuresManager, "Missing login failure manager"); 94 | } 95 | 96 | protected String obtainRecaptchaResponse(HttpServletRequest request) { 97 | return request.getParameter(recaptcha.getValidation().getResponseParameter()); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/security/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.security; 2 | 3 | import com.github.mkopylec.recaptcha.RecaptchaProperties; 4 | import com.github.mkopylec.recaptcha.security.login.FormLoginConfigurerEnhancer; 5 | import com.github.mkopylec.recaptcha.security.login.InMemoryLoginFailuresManager; 6 | import com.github.mkopylec.recaptcha.security.login.LoginFailuresClearingHandler; 7 | import com.github.mkopylec.recaptcha.security.login.LoginFailuresCountingHandler; 8 | import com.github.mkopylec.recaptcha.security.login.LoginFailuresManager; 9 | import com.github.mkopylec.recaptcha.security.login.RecaptchaAwareRedirectStrategy; 10 | import com.github.mkopylec.recaptcha.validation.RecaptchaValidator; 11 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 12 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 13 | import org.springframework.context.annotation.Bean; 14 | import org.springframework.context.annotation.Configuration; 15 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 16 | import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; 17 | 18 | @Configuration("recaptchaSecurityConfiguration") 19 | @ConditionalOnClass({EnableWebSecurity.class, AbstractAuthenticationProcessingFilter.class}) 20 | public class SecurityConfiguration { 21 | 22 | private final RecaptchaProperties recaptcha; 23 | 24 | public SecurityConfiguration(RecaptchaProperties recaptcha) { 25 | this.recaptcha = recaptcha; 26 | } 27 | 28 | @Bean 29 | @ConditionalOnMissingBean 30 | public FormLoginConfigurerEnhancer formLoginConfigurerEnhancer(LoginFailuresClearingHandler successHandler, LoginFailuresCountingHandler failureHandler, RecaptchaValidator recaptchaValidator, LoginFailuresManager failuresManager) { 31 | RecaptchaAuthenticationFilter authenticationFilter = new RecaptchaAuthenticationFilter(recaptchaValidator, recaptcha, failuresManager); 32 | return new FormLoginConfigurerEnhancer(authenticationFilter, successHandler, failureHandler); 33 | } 34 | 35 | @Bean 36 | @ConditionalOnMissingBean 37 | public LoginFailuresManager loginFailuresManager() { 38 | return new InMemoryLoginFailuresManager(recaptcha); 39 | } 40 | 41 | @Bean 42 | @ConditionalOnMissingBean 43 | public LoginFailuresCountingHandler loginFailuresCountingHandler(LoginFailuresManager failuresManager, RecaptchaAwareRedirectStrategy redirectStrategy) { 44 | return new LoginFailuresCountingHandler(failuresManager, recaptcha, redirectStrategy); 45 | } 46 | 47 | @Bean 48 | @ConditionalOnMissingBean 49 | public LoginFailuresClearingHandler loginFailuresClearingHandler(LoginFailuresManager failuresManager) { 50 | return new LoginFailuresClearingHandler(failuresManager); 51 | } 52 | 53 | @Bean 54 | @ConditionalOnMissingBean 55 | public RecaptchaAwareRedirectStrategy recaptchaAwareRedirectStrategy(LoginFailuresManager failuresManager) { 56 | return new RecaptchaAwareRedirectStrategy(failuresManager); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/security/login/FormLoginConfigurerEnhancer.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.security.login; 2 | 3 | import com.github.mkopylec.recaptcha.security.RecaptchaAuthenticationFilter; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer; 6 | import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; 7 | 8 | import java.lang.reflect.Field; 9 | 10 | import static org.springframework.util.ReflectionUtils.findField; 11 | import static org.springframework.util.ReflectionUtils.makeAccessible; 12 | import static org.springframework.util.ReflectionUtils.setField; 13 | 14 | public class FormLoginConfigurerEnhancer { 15 | 16 | public static final String DEFAULT_USERNAME_PARAMETER = "username"; 17 | protected static final String AUTHENTICATION_PROCESSING_FILTER_FIELD = "authFilter"; 18 | 19 | protected final RecaptchaAuthenticationFilter authenticationFilter; 20 | protected final LoginFailuresClearingHandler successHandler; 21 | protected final LoginFailuresCountingHandler failureHandler; 22 | 23 | public FormLoginConfigurerEnhancer(RecaptchaAuthenticationFilter authenticationFilter, LoginFailuresClearingHandler successHandler, LoginFailuresCountingHandler failureHandler) { 24 | this.authenticationFilter = authenticationFilter; 25 | this.successHandler = successHandler; 26 | this.failureHandler = failureHandler; 27 | } 28 | 29 | public FormLoginConfigurer addRecaptchaSupport(FormLoginConfigurer loginConfigurer) { 30 | Field authFilterField = findField(loginConfigurer.getClass(), AUTHENTICATION_PROCESSING_FILTER_FIELD, AbstractAuthenticationProcessingFilter.class); 31 | makeAccessible(authFilterField); 32 | setField(authFilterField, loginConfigurer, authenticationFilter); 33 | return loginConfigurer.usernameParameter(DEFAULT_USERNAME_PARAMETER) 34 | .successHandler(successHandler) 35 | .failureHandler(failureHandler); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/security/login/InMemoryLoginFailuresManager.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.security.login; 2 | 3 | import com.github.mkopylec.recaptcha.RecaptchaProperties; 4 | import org.slf4j.Logger; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | import java.util.concurrent.ConcurrentHashMap; 8 | import java.util.concurrent.ConcurrentMap; 9 | 10 | import static org.slf4j.LoggerFactory.getLogger; 11 | 12 | public class InMemoryLoginFailuresManager extends LoginFailuresManager { 13 | 14 | private static final Logger log = getLogger(InMemoryLoginFailuresManager.class); 15 | 16 | protected final ConcurrentMap loginFailures = new ConcurrentHashMap<>(); 17 | 18 | public InMemoryLoginFailuresManager(RecaptchaProperties recaptcha) { 19 | super(recaptcha); 20 | } 21 | 22 | @Override 23 | public void addLoginFailure(HttpServletRequest request) { 24 | String username = getUsername(request); 25 | log.debug("Adding login failure for username: {}", username); 26 | loginFailures.compute(username, (name, count) -> count == null ? 1 : count + 1); 27 | } 28 | 29 | @Override 30 | public int getLoginFailuresCount(HttpServletRequest request) { 31 | String username = getUsername(request); 32 | int count = loginFailures.getOrDefault(username, 0); 33 | log.debug("Getting login failures count: {} for username: {}", count, username); 34 | return count; 35 | } 36 | 37 | @Override 38 | public void clearLoginFailures(HttpServletRequest request) { 39 | String username = getUsername(request); 40 | log.debug("Clearing login failures for username: {}", username); 41 | loginFailures.remove(username); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/security/login/LoginFailuresClearingHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.security.login; 2 | 3 | import org.springframework.security.core.Authentication; 4 | import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; 5 | 6 | import javax.servlet.ServletException; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | import java.io.IOException; 10 | 11 | public class LoginFailuresClearingHandler extends SavedRequestAwareAuthenticationSuccessHandler { 12 | 13 | protected final LoginFailuresManager failuresManager; 14 | 15 | public LoginFailuresClearingHandler(LoginFailuresManager failuresManager) { 16 | this.failuresManager = failuresManager; 17 | } 18 | 19 | @Override 20 | public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { 21 | failuresManager.clearLoginFailures(request); 22 | super.onAuthenticationSuccess(request, response, authentication); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/security/login/LoginFailuresCountingHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.security.login; 2 | 3 | import com.github.mkopylec.recaptcha.RecaptchaProperties; 4 | import org.springframework.security.core.AuthenticationException; 5 | import org.springframework.security.web.RedirectStrategy; 6 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; 7 | 8 | import javax.servlet.ServletException; 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | import java.io.IOException; 12 | 13 | public class LoginFailuresCountingHandler extends SimpleUrlAuthenticationFailureHandler { 14 | 15 | protected final LoginFailuresManager failuresManager; 16 | 17 | public LoginFailuresCountingHandler(LoginFailuresManager failuresManager, RecaptchaProperties recaptcha, RecaptchaAwareRedirectStrategy redirectStrategy) { 18 | this.failuresManager = failuresManager; 19 | setDefaultFailureUrl(recaptcha.getSecurity().getFailureUrl()); 20 | setRedirectStrategy(redirectStrategy); 21 | } 22 | 23 | @Override 24 | public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { 25 | failuresManager.addLoginFailure(request); 26 | super.onAuthenticationFailure(request, response, exception); 27 | } 28 | 29 | @Override 30 | public void setRedirectStrategy(RedirectStrategy redirectStrategy) { 31 | if (!RecaptchaAwareRedirectStrategy.class.isAssignableFrom(redirectStrategy.getClass())) { 32 | throw new IllegalArgumentException("Invalid redirect strategy. Redirect strategy must be an instance of " + RecaptchaAwareRedirectStrategy.class.getName() + " but is " + redirectStrategy); 33 | } 34 | super.setRedirectStrategy(redirectStrategy); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/security/login/LoginFailuresManager.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.security.login; 2 | 3 | import com.github.mkopylec.recaptcha.RecaptchaProperties; 4 | import com.github.mkopylec.recaptcha.RecaptchaProperties.Security; 5 | import org.slf4j.Logger; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | 9 | import static org.slf4j.LoggerFactory.getLogger; 10 | 11 | public abstract class LoginFailuresManager { 12 | 13 | private static final Logger log = getLogger(LoginFailuresManager.class); 14 | 15 | protected final Security security; 16 | protected String usernameParameter; 17 | 18 | public LoginFailuresManager(RecaptchaProperties recaptcha) { 19 | security = recaptcha.getSecurity(); 20 | } 21 | 22 | public abstract void addLoginFailure(HttpServletRequest request); 23 | 24 | public abstract int getLoginFailuresCount(HttpServletRequest request); 25 | 26 | public abstract void clearLoginFailures(HttpServletRequest request); 27 | 28 | public boolean isRecaptchaRequired(HttpServletRequest request) { 29 | boolean recaptchaRequired = getLoginFailuresCount(request) >= security.getLoginFailuresThreshold(); 30 | log.debug("Done checking is reCAPTCHA required for username: {}. Check result: {}", getUsername(request), recaptchaRequired); 31 | return recaptchaRequired; 32 | } 33 | 34 | public void setUsernameParameter(String usernameParameter) { 35 | this.usernameParameter = usernameParameter; 36 | } 37 | 38 | protected String getUsername(HttpServletRequest request) { 39 | if (usernameParameter == null) { 40 | throw new IllegalStateException("Missing username parameter name"); 41 | } 42 | String username = request.getParameter(usernameParameter); 43 | if (username == null) { 44 | throw new IllegalStateException("Missing username parameter '" + usernameParameter + "' value in HTTP request"); 45 | } 46 | return username; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/security/login/RecaptchaAwareRedirectStrategy.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.security.login; 2 | 3 | import com.github.mkopylec.recaptcha.security.RecaptchaAuthenticationException; 4 | import org.springframework.security.core.AuthenticationException; 5 | import org.springframework.security.web.DefaultRedirectStrategy; 6 | import org.springframework.web.util.UriComponentsBuilder; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | import java.io.IOException; 11 | 12 | import static org.springframework.security.web.WebAttributes.AUTHENTICATION_EXCEPTION; 13 | import static org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.ERROR_PARAMETER_NAME; 14 | import static org.springframework.web.util.UriComponentsBuilder.fromUriString; 15 | 16 | public class RecaptchaAwareRedirectStrategy extends DefaultRedirectStrategy { 17 | 18 | public static final String RECAPTCHA_ERROR_PARAMETER_NAME = "recaptchaError"; 19 | public static final String SHOW_RECAPTCHA_QUERY_PARAM = "showRecaptcha"; 20 | 21 | protected final LoginFailuresManager failuresManager; 22 | 23 | public RecaptchaAwareRedirectStrategy(LoginFailuresManager failuresManager) { 24 | this.failuresManager = failuresManager; 25 | } 26 | 27 | @Override 28 | public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException { 29 | UriComponentsBuilder urlBuilder = fromUriString(url); 30 | AuthenticationException exception = getAuthenticationException(request); 31 | if (exception instanceof RecaptchaAuthenticationException) { 32 | urlBuilder.queryParam(RECAPTCHA_ERROR_PARAMETER_NAME); 33 | } else { 34 | urlBuilder.queryParam(ERROR_PARAMETER_NAME); 35 | } 36 | if (failuresManager.isRecaptchaRequired(request)) { 37 | urlBuilder.queryParam(SHOW_RECAPTCHA_QUERY_PARAM); 38 | } 39 | super.sendRedirect(request, response, urlBuilder.build(true).toUriString()); 40 | } 41 | 42 | protected AuthenticationException getAuthenticationException(HttpServletRequest request) { 43 | Object exception = request.getSession(false).getAttribute(AUTHENTICATION_EXCEPTION); 44 | if (exception == null) { 45 | exception = request.getAttribute(AUTHENTICATION_EXCEPTION); 46 | } 47 | if (exception == null) { 48 | throw new IllegalStateException("Missing " + AUTHENTICATION_EXCEPTION + " session or request attribute"); 49 | } 50 | return (AuthenticationException) exception; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/testing/TestRecaptchaValidator.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.testing; 2 | 3 | import com.github.mkopylec.recaptcha.RecaptchaProperties; 4 | import com.github.mkopylec.recaptcha.RecaptchaProperties.Testing; 5 | import com.github.mkopylec.recaptcha.validation.RecaptchaValidator; 6 | import com.github.mkopylec.recaptcha.validation.ValidationResult; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | import java.util.ArrayList; 10 | 11 | public class TestRecaptchaValidator implements RecaptchaValidator { 12 | 13 | protected final Testing testing; 14 | 15 | public TestRecaptchaValidator(RecaptchaProperties recaptcha) { 16 | testing = recaptcha.getTesting(); 17 | } 18 | 19 | @Override 20 | public ValidationResult validate(HttpServletRequest request) { 21 | return getValidationResult(); 22 | } 23 | 24 | @Override 25 | public ValidationResult validate(HttpServletRequest request, String ipAddress) { 26 | return getValidationResult(); 27 | } 28 | 29 | @Override 30 | public ValidationResult validate(HttpServletRequest request, String ipAddress, String secretKey) { 31 | return getValidationResult(); 32 | } 33 | 34 | @Override 35 | public ValidationResult validate(String userResponse, HttpServletRequest request) { 36 | return getValidationResult(); 37 | } 38 | 39 | @Override 40 | public ValidationResult validate(String userResponse) { 41 | return getValidationResult(); 42 | } 43 | 44 | @Override 45 | public ValidationResult validate(String userResponse, String ipAddress) { 46 | return getValidationResult(); 47 | } 48 | 49 | @Override 50 | public ValidationResult validate(String userResponse, String ipAddress, String secretKey) { 51 | return getValidationResult(); 52 | } 53 | 54 | private ValidationResult getValidationResult() { 55 | if (testing.isSuccessResult()) { 56 | return new ValidationResult(true, new ArrayList<>()); 57 | } 58 | return new ValidationResult(false, testing.getResultErrorCodes()); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/testing/TestingConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.testing; 2 | 3 | import com.github.mkopylec.recaptcha.RecaptchaProperties; 4 | import com.github.mkopylec.recaptcha.validation.RecaptchaValidator; 5 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 7 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | @Configuration("recaptchaTestingConfiguration") 12 | @EnableConfigurationProperties(RecaptchaProperties.class) 13 | @ConditionalOnProperty(name = "recaptcha.testing.enabled") 14 | public class TestingConfiguration { 15 | 16 | private final RecaptchaProperties recaptcha; 17 | 18 | public TestingConfiguration(RecaptchaProperties recaptcha) { 19 | this.recaptcha = recaptcha; 20 | } 21 | 22 | @Bean 23 | @ConditionalOnMissingBean 24 | public RecaptchaValidator userResponseValidator() { 25 | return new TestRecaptchaValidator(recaptcha); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/validation/DefaultRecaptchaValidator.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.validation; 2 | 3 | import com.github.mkopylec.recaptcha.RecaptchaProperties; 4 | import com.github.mkopylec.recaptcha.RecaptchaProperties.Validation; 5 | import org.slf4j.Logger; 6 | import org.springframework.util.LinkedMultiValueMap; 7 | import org.springframework.util.MultiValueMap; 8 | import org.springframework.web.client.RestClientException; 9 | import org.springframework.web.client.RestTemplate; 10 | 11 | import javax.servlet.http.HttpServletRequest; 12 | 13 | import static org.slf4j.LoggerFactory.getLogger; 14 | 15 | public class DefaultRecaptchaValidator implements RecaptchaValidator { 16 | 17 | private static final Logger log = getLogger(DefaultRecaptchaValidator.class); 18 | 19 | protected final RestTemplate restTemplate; 20 | protected final Validation validation; 21 | protected final IpAddressResolver ipAddressResolver; 22 | 23 | public DefaultRecaptchaValidator(RestTemplate restTemplate, RecaptchaProperties recaptcha, IpAddressResolver ipAddressResolver) { 24 | this.restTemplate = restTemplate; 25 | validation = recaptcha.getValidation(); 26 | this.ipAddressResolver = ipAddressResolver; 27 | } 28 | 29 | @Override 30 | public ValidationResult validate(HttpServletRequest request) { 31 | return validate(request, ipAddressResolver.resolveClientIp(request)); 32 | } 33 | 34 | @Override 35 | public ValidationResult validate(HttpServletRequest request, String ipAddress) { 36 | return validate(request.getParameter(validation.getResponseParameter()), ipAddress); 37 | } 38 | 39 | @Override 40 | public ValidationResult validate(HttpServletRequest request, String ipAddress, String secretKey) { 41 | return validate(request.getParameter(validation.getResponseParameter()), ipAddress, secretKey); 42 | } 43 | 44 | @Override 45 | public ValidationResult validate(String userResponse, HttpServletRequest request) { 46 | return validate(userResponse, ipAddressResolver.resolveClientIp(request)); 47 | } 48 | 49 | @Override 50 | public ValidationResult validate(String userResponse) { 51 | return validate(userResponse, ""); 52 | } 53 | 54 | @Override 55 | public ValidationResult validate(String userResponse, String ipAddress) { 56 | return validate(userResponse, ipAddress, validation.getSecretKey()); 57 | } 58 | 59 | @Override 60 | public ValidationResult validate(String userResponse, String ipAddress, String secretKey) { 61 | MultiValueMap parameters = new LinkedMultiValueMap<>(); 62 | parameters.add("secret", secretKey); 63 | parameters.add("response", userResponse); 64 | parameters.add("remoteip", ipAddress); 65 | 66 | log.debug("Validating reCAPTCHA:\n verification url: {}\n verification parameters: {}", validation.getVerificationUrl(), parameters); 67 | 68 | try { 69 | ValidationResult result = restTemplate.postForEntity(validation.getVerificationUrl(), parameters, ValidationResult.class).getBody(); 70 | log.debug("reCAPTCHA validation finished: {}", result); 71 | return result; 72 | } catch (RestClientException ex) { 73 | throw new RecaptchaValidationException(userResponse, validation.getVerificationUrl(), ex); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/validation/ErrorCode.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.validation; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonValue; 5 | import org.slf4j.Logger; 6 | 7 | import static org.slf4j.LoggerFactory.getLogger; 8 | 9 | public enum ErrorCode { 10 | 11 | //reCAPTCHA verification errors 12 | MISSING_SECRET_KEY("missing-input-secret"), 13 | INVALID_SECRET_KEY("invalid-input-secret"), 14 | MISSING_USER_CAPTCHA_RESPONSE("missing-input-response"), 15 | INVALID_USER_CAPTCHA_RESPONSE("invalid-input-response"), 16 | BAD_REQUEST("bad-request"), 17 | TIMEOUT_OR_DUPLICATE("timeout-or-duplicate"), 18 | 19 | //Custom errors 20 | MISSING_USERNAME_REQUEST_PARAMETER("missing-username-request-parameter"), 21 | MISSING_CAPTCHA_RESPONSE_PARAMETER("missing-captcha-response-parameter"), 22 | VALIDATION_HTTP_ERROR("validation-http-error"), 23 | UNSUPPORTED_ERROR_CODE("unsupported_error_code"); 24 | 25 | private static final Logger log = getLogger(ErrorCode.class); 26 | 27 | private final String text; 28 | 29 | ErrorCode(String text) { 30 | this.text = text; 31 | } 32 | 33 | @JsonCreator 34 | private static ErrorCode fromValue(String value) { 35 | if (value == null) { 36 | return null; 37 | } 38 | switch (value) { 39 | case "missing-input-secret": 40 | return MISSING_SECRET_KEY; 41 | case "invalid-input-secret": 42 | return INVALID_SECRET_KEY; 43 | case "missing-input-response": 44 | return MISSING_USER_CAPTCHA_RESPONSE; 45 | case "invalid-input-response": 46 | return INVALID_USER_CAPTCHA_RESPONSE; 47 | case "bad-request": 48 | return BAD_REQUEST; 49 | case "timeout-or-duplicate": 50 | return TIMEOUT_OR_DUPLICATE; 51 | case "missing-username-request-parameter": 52 | return MISSING_USERNAME_REQUEST_PARAMETER; 53 | case "missing-captcha-response-parameter": 54 | return MISSING_CAPTCHA_RESPONSE_PARAMETER; 55 | case "validation-http-error": 56 | return VALIDATION_HTTP_ERROR; 57 | default: 58 | log.warn("Unsupported error code: {}", value); 59 | return UNSUPPORTED_ERROR_CODE; 60 | } 61 | } 62 | 63 | @JsonValue 64 | public String getText() { 65 | return text; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/validation/IpAddressResolver.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.validation; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | 5 | import static org.springframework.util.StringUtils.hasLength; 6 | 7 | public class IpAddressResolver { 8 | 9 | public static final String X_FORWARDED_FOR_HEADER = "X-Forwarded-For"; 10 | 11 | public String resolveClientIp(HttpServletRequest request) { 12 | String ipAddresses = request.getHeader(X_FORWARDED_FOR_HEADER); 13 | if (hasLength(ipAddresses)) { 14 | return ipAddresses.split(",")[0].trim(); 15 | } 16 | return request.getRemoteAddr(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/validation/RecaptchaValidationException.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.validation; 2 | 3 | import static java.lang.String.format; 4 | 5 | public class RecaptchaValidationException extends RuntimeException { 6 | 7 | public RecaptchaValidationException(String userResponse, String verificationUrl, Throwable cause) { 8 | super(format("Error validating reCAPTCHA. User response: '%s', verification URL: '%s'", userResponse, verificationUrl), cause); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/validation/RecaptchaValidator.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.validation; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | 5 | public interface RecaptchaValidator { 6 | 7 | ValidationResult validate(HttpServletRequest request); 8 | 9 | ValidationResult validate(HttpServletRequest request, String ipAddress); 10 | 11 | ValidationResult validate(HttpServletRequest request, String ipAddress, String secretKey); 12 | 13 | ValidationResult validate(String userResponse, HttpServletRequest request); 14 | 15 | ValidationResult validate(String userResponse); 16 | 17 | ValidationResult validate(String userResponse, String ipAddress); 18 | 19 | ValidationResult validate(String userResponse, String ipAddress, String secretKey); 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/validation/ValidationConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.validation; 2 | 3 | import com.github.mkopylec.recaptcha.RecaptchaProperties; 4 | import com.github.mkopylec.recaptcha.RecaptchaProperties.Validation.Timeout; 5 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 7 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.http.client.OkHttp3ClientHttpRequestFactory; 11 | import org.springframework.web.client.RestTemplate; 12 | 13 | import java.time.Duration; 14 | 15 | @Configuration("recaptchaValidationConfiguration") 16 | @EnableConfigurationProperties(RecaptchaProperties.class) 17 | @ConditionalOnProperty(name = "recaptcha.testing.enabled", havingValue = "false", matchIfMissing = true) 18 | public class ValidationConfiguration { 19 | 20 | private final RecaptchaProperties recaptcha; 21 | 22 | public ValidationConfiguration(RecaptchaProperties recaptcha) { 23 | this.recaptcha = recaptcha; 24 | } 25 | 26 | @Bean 27 | @ConditionalOnMissingBean 28 | public RecaptchaValidator userResponseValidator(IpAddressResolver ipAddressResolver) { 29 | return new DefaultRecaptchaValidator(createRestTemplate(), recaptcha, ipAddressResolver); 30 | } 31 | 32 | @Bean 33 | @ConditionalOnMissingBean 34 | public IpAddressResolver ipAddressResolver() { 35 | return new IpAddressResolver(); 36 | } 37 | 38 | protected RestTemplate createRestTemplate() { 39 | Timeout timeout = recaptcha.getValidation().getTimeout(); 40 | OkHttp3ClientHttpRequestFactory requestFactory = new OkHttp3ClientHttpRequestFactory(); 41 | requestFactory.setConnectTimeout(toMilliseconds(timeout.getConnect())); 42 | requestFactory.setReadTimeout(toMilliseconds(timeout.getRead())); 43 | requestFactory.setWriteTimeout(toMilliseconds(timeout.getWrite())); 44 | return new RestTemplate(requestFactory); 45 | } 46 | 47 | protected int toMilliseconds(Duration duration) { 48 | return (int) duration.toMillis(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/github/mkopylec/recaptcha/validation/ValidationResult.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.validation; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonIgnore; 5 | import com.fasterxml.jackson.annotation.JsonProperty; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | import static java.util.Collections.unmodifiableList; 11 | 12 | public class ValidationResult { 13 | 14 | private boolean success; 15 | private List errorCodes; 16 | 17 | @JsonCreator 18 | public ValidationResult( 19 | @JsonProperty("success") boolean success, 20 | @JsonProperty("error-codes") List errorCodes 21 | ) { 22 | this.success = success; 23 | this.errorCodes = errorCodes == null ? new ArrayList<>() : errorCodes; 24 | } 25 | 26 | public boolean isSuccess() { 27 | return success; 28 | } 29 | 30 | @JsonIgnore 31 | public boolean isFailure() { 32 | return !success; 33 | } 34 | 35 | public List getErrorCodes() { 36 | return unmodifiableList(errorCodes); 37 | } 38 | 39 | public boolean hasError(ErrorCode error) { 40 | return errorCodes.contains(error); 41 | } 42 | 43 | @Override 44 | public String toString() { 45 | return "ValidationResult{" + 46 | "success=" + success + 47 | ", errorCodes=" + errorCodes + 48 | '}'; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 2 | com.github.mkopylec.recaptcha.security.SecurityConfiguration,\ 3 | com.github.mkopylec.recaptcha.validation.ValidationConfiguration,\ 4 | com.github.mkopylec.recaptcha.testing.TestingConfiguration -------------------------------------------------------------------------------- /src/test/groovy/com/github/mkopylec/recaptcha/BasicSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha 2 | 3 | import com.github.mkopylec.recaptcha.security.ResponseData 4 | import com.github.mkopylec.recaptcha.validation.ValidationResult 5 | import com.github.tomakehurst.wiremock.junit.WireMockRule 6 | import org.junit.Rule 7 | import org.springframework.beans.factory.annotation.Autowired 8 | import org.springframework.boot.test.context.SpringBootTest 9 | import org.springframework.boot.test.web.client.TestRestTemplate 10 | import org.springframework.boot.web.server.LocalServerPort 11 | import org.springframework.http.HttpEntity 12 | import org.springframework.http.HttpHeaders 13 | import org.springframework.http.ResponseEntity 14 | import org.springframework.util.LinkedMultiValueMap 15 | import spock.lang.Specification 16 | 17 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT 18 | import static org.springframework.http.HttpHeaders.COOKIE 19 | import static org.springframework.http.HttpHeaders.SET_COOKIE 20 | 21 | @SpringBootTest(webEnvironment = RANDOM_PORT, classes = TestApplication) 22 | abstract class BasicSpec extends Specification { 23 | 24 | @Rule 25 | public WireMockRule wireMockRule = new WireMockRule(8081) 26 | 27 | @LocalServerPort 28 | protected int port 29 | @Autowired 30 | private TestRestTemplate restTemplate 31 | 32 | private ThreadLocal cookies = new ThreadLocal<>() 33 | 34 | protected ResponseEntity validateRecaptcha(String userResponse, String xForwardedFor = null) { 35 | if (userResponse == null) { 36 | return post('/testValidation/userResponse', ValidationResult, [:], xForwardedFor) 37 | } 38 | return post('/testValidation/userResponse', ValidationResult, ['g-recaptcha-response': userResponse], xForwardedFor) 39 | } 40 | 41 | protected ResponseEntity validateRecaptchaWithIp(String userResponse) { 42 | return post('/testValidation/userResponseAndIp', ValidationResult, ['g-recaptcha-response': userResponse]) 43 | } 44 | 45 | protected ResponseEntity validateRecaptchaInTestingMode() { 46 | return post('/testTesting/validate', ValidationResult) 47 | } 48 | 49 | protected ResponseEntity getSecuredData() { 50 | return post('/testSecurity/getResponse', ResponseData) 51 | } 52 | 53 | protected ResponseEntity logIn(String username, String password, String recaptchaResponse = null) { 54 | def params = ['username': username, 'password': password] 55 | if (recaptchaResponse != null) { 56 | params['g-recaptcha-response'] = recaptchaResponse 57 | } 58 | return post('/login', Object, params) 59 | } 60 | 61 | private ResponseEntity post(String path, Class responseType, Map parameters = [:], String xForwardedFor = null) { 62 | def params = new LinkedMultiValueMap<>() 63 | for (def parameter : parameters.entrySet()) { 64 | params.add(parameter.key, parameter.value) 65 | } 66 | HttpHeaders headers = new HttpHeaders() 67 | headers.set(COOKIE, cookies.get()) 68 | headers.set('X-Forwarded-For', xForwardedFor) 69 | def request = new HttpEntity<>(params, headers) 70 | def response = restTemplate.postForEntity(path, request, responseType) as ResponseEntity 71 | cookies.set(response.headers.get(SET_COOKIE) as String) 72 | 73 | return response 74 | } 75 | 76 | void cleanup() { 77 | cookies.remove() 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/test/groovy/com/github/mkopylec/recaptcha/assertions/Assertions.groovy: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.assertions 2 | 3 | import org.springframework.http.ResponseEntity 4 | 5 | class Assertions { 6 | 7 | static ResponseAssert assertThat(ResponseEntity response) { 8 | return new ResponseAssert(response) 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/test/groovy/com/github/mkopylec/recaptcha/assertions/ResponseAssert.groovy: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.assertions 2 | 3 | import com.github.mkopylec.recaptcha.security.ResponseData 4 | import com.github.mkopylec.recaptcha.validation.ErrorCode 5 | import com.github.mkopylec.recaptcha.validation.ValidationResult 6 | import org.springframework.http.HttpStatus 7 | import org.springframework.http.ResponseEntity 8 | 9 | import static org.springframework.http.HttpStatus.FOUND 10 | import static org.springframework.http.HttpStatus.OK 11 | 12 | class ResponseAssert { 13 | 14 | private ResponseEntity actual 15 | 16 | protected ResponseAssert(ResponseEntity actual) { 17 | assert actual != null 18 | this.actual = actual 19 | } 20 | 21 | ResponseAssert redirectsTo(String url) { 22 | assert actual.headers.get('Location') == [url] 23 | return this 24 | } 25 | 26 | ResponseAssert hasSuccessfulValidationResult() { 27 | assert validationResult != null 28 | assert validationResult.success 29 | return this 30 | } 31 | 32 | ResponseAssert hasUnsuccessfulValidationResult() { 33 | assert validationResult != null 34 | assert validationResult.failure 35 | return this 36 | } 37 | 38 | ResponseAssert hasNoErrorCodes() { 39 | return hasErrorCodes() 40 | } 41 | 42 | ResponseAssert hasErrorCodes(ErrorCode... errorCodes) { 43 | assert validationResult != null 44 | assert validationResult.errorCodes != null 45 | assert validationResult.errorCodes.size() == errorCodes.length 46 | assert validationResult.errorCodes.containsAll(errorCodes) 47 | return this 48 | } 49 | 50 | ResponseAssert hasMessage(String message) { 51 | assert responseData != null 52 | assert responseData.message == message 53 | return this 54 | } 55 | 56 | ResponseAssert hasFoundStatus() { 57 | return hasStatus(FOUND) 58 | } 59 | 60 | ResponseAssert hasOkStatus() { 61 | return hasStatus(OK) 62 | } 63 | 64 | private ValidationResult getValidationResult() { 65 | (ValidationResult) actual.body 66 | } 67 | 68 | private ResponseData getResponseData() { 69 | (ResponseData) actual.body 70 | } 71 | 72 | private ResponseAssert hasStatus(HttpStatus status) { 73 | assert actual.statusCode == status 74 | return this 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/test/groovy/com/github/mkopylec/recaptcha/specification/SecuritySpec.groovy: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.specification 2 | 3 | import com.github.mkopylec.recaptcha.BasicSpec 4 | import com.github.mkopylec.recaptcha.RecaptchaProperties 5 | import org.springframework.beans.factory.annotation.Autowired 6 | 7 | import static com.github.mkopylec.recaptcha.Strings.INVALID_CAPTCHA_RESPONSE 8 | import static com.github.mkopylec.recaptcha.Strings.RESPONSE_DATA_MESSAGE 9 | import static com.github.mkopylec.recaptcha.Strings.VALID_CAPTCHA_RESPONSE 10 | import static com.github.mkopylec.recaptcha.Strings.VALID_SECRET 11 | import static com.github.mkopylec.recaptcha.assertions.Assertions.assertThat 12 | import static com.github.mkopylec.recaptcha.stubs.RecaptchaValidationStubs.stubInvalidResponseRecaptchaValidation 13 | import static com.github.mkopylec.recaptcha.stubs.RecaptchaValidationStubs.stubSuccessfulRecaptchaValidation 14 | 15 | class SecuritySpec extends BasicSpec { 16 | 17 | @Autowired 18 | private RecaptchaProperties recaptcha 19 | 20 | def "Should log in a user and get response data when captcha was not displayed and user entered valid credentials"() { 21 | //Redirect to login page while trying to get secured data 22 | when: 23 | def response = getSecuredData() 24 | then: 25 | assertThat(response) 26 | .hasFoundStatus() 27 | .redirectsTo("http://localhost:$port/login") 28 | 29 | //Log in successfully 30 | when: 31 | response = logIn('user', 'password') 32 | then: 33 | assertThat(response) 34 | .hasFoundStatus() 35 | .redirectsTo("http://localhost:$port/") 36 | 37 | //Get secured data while logged in 38 | when: 39 | response = getSecuredData() 40 | then: 41 | assertThat(response) 42 | .hasOkStatus() 43 | .hasMessage(RESPONSE_DATA_MESSAGE) 44 | 45 | cleanup: 46 | resetUserLoginFailures() 47 | } 48 | 49 | def "Should log in a user and get response data when captcha was displayed and user entered a valid credentials and captcha response"() { 50 | given: 51 | stubSuccessfulRecaptchaValidation() 52 | recaptcha.validation.secretKey = VALID_SECRET 53 | 54 | //Redirect to login page while trying to get secured data 55 | when: 56 | def response = getSecuredData() 57 | then: 58 | assertThat(response) 59 | .hasFoundStatus() 60 | .redirectsTo("http://localhost:$port/login") 61 | 62 | //Log in unsuccessfully 3 times 63 | 3.times { 64 | when: 65 | response = logIn('user', 'invalid-password') 66 | then: 67 | def query = it == 2 ? '&showRecaptcha' : '' 68 | assertThat(response) 69 | .hasFoundStatus() 70 | .redirectsTo("http://localhost:$port/login?error$query") 71 | } 72 | 73 | //Log in successfully with captcha 74 | when: 75 | response = logIn('user', 'password', VALID_CAPTCHA_RESPONSE) 76 | then: 77 | assertThat(response) 78 | .hasFoundStatus() 79 | .redirectsTo("http://localhost:$port/") 80 | 81 | //Get secured data while logged in 82 | when: 83 | response = getSecuredData() 84 | then: 85 | assertThat(response) 86 | .hasOkStatus() 87 | .hasMessage(RESPONSE_DATA_MESSAGE) 88 | 89 | cleanup: 90 | resetUserLoginFailures() 91 | } 92 | 93 | def "Should not log in a user and not get response data when captcha was displayed and user entered a invalid captcha response"() { 94 | given: 95 | stubInvalidResponseRecaptchaValidation() 96 | recaptcha.validation.secretKey = VALID_SECRET 97 | 98 | //Redirect to login page while trying to get secured data 99 | when: 100 | def response = getSecuredData() 101 | then: 102 | assertThat(response) 103 | .hasFoundStatus() 104 | .redirectsTo("http://localhost:$port/login") 105 | 106 | //Log in unsuccessfully 3 times 107 | 3.times { 108 | when: 109 | response = logIn('user', 'invalid-password') 110 | then: 111 | def query = it == 2 ? '&showRecaptcha' : '' 112 | assertThat(response) 113 | .hasFoundStatus() 114 | .redirectsTo("http://localhost:$port/login?error$query") 115 | } 116 | 117 | //Log in unsuccessfully because of invalid captcha response 118 | when: 119 | response = logIn('user', 'password', INVALID_CAPTCHA_RESPONSE) 120 | then: 121 | assertThat(response) 122 | .hasFoundStatus() 123 | .redirectsTo("http://localhost:$port/login?recaptchaError&showRecaptcha") 124 | 125 | //Redirect to login page while trying to get secured data 126 | when: 127 | response = getSecuredData() 128 | then: 129 | assertThat(response) 130 | .hasFoundStatus() 131 | .redirectsTo("http://localhost:$port/login") 132 | 133 | cleanup: 134 | resetUserLoginFailures() 135 | } 136 | 137 | def "Should not log in a user and not get response data when captcha was displayed and user entered invalid credentials"() { 138 | given: 139 | stubSuccessfulRecaptchaValidation() 140 | recaptcha.validation.secretKey = VALID_SECRET 141 | 142 | //Redirect to login page while trying to get secured data 143 | when: 144 | def response = getSecuredData() 145 | then: 146 | assertThat(response) 147 | .hasFoundStatus() 148 | .redirectsTo("http://localhost:$port/login") 149 | 150 | //Log in unsuccessfully 3 times 151 | 3.times { 152 | when: 153 | response = logIn('user', 'invalid-password') 154 | then: 155 | def query = it == 2 ? '&showRecaptcha' : '' 156 | assertThat(response) 157 | .hasFoundStatus() 158 | .redirectsTo("http://localhost:$port/login?error$query") 159 | } 160 | 161 | //Log in unsuccessfully because of invalid user credentials 162 | when: 163 | response = logIn('user', 'invalid-password', VALID_CAPTCHA_RESPONSE) 164 | then: 165 | assertThat(response) 166 | .hasFoundStatus() 167 | .redirectsTo("http://localhost:$port/login?error&showRecaptcha") 168 | 169 | //Redirect to login page while trying to get secured data 170 | when: 171 | response = getSecuredData() 172 | then: 173 | assertThat(response) 174 | .hasFoundStatus() 175 | .redirectsTo("http://localhost:$port/login") 176 | 177 | cleanup: 178 | resetUserLoginFailures() 179 | } 180 | 181 | def "Should log in a user and get response data when captcha validation fails because of HTTP error"() { 182 | given: 183 | recaptcha.validation.verificationUrl = 'http://invalid.verification.url/' 184 | 185 | //Redirect to login page while trying to get secured data 186 | when: 187 | def response = getSecuredData() 188 | then: 189 | assertThat(response) 190 | .hasFoundStatus() 191 | .redirectsTo("http://localhost:$port/login") 192 | 193 | //Log in unsuccessfully 3 times 194 | 3.times { 195 | when: 196 | response = logIn('user', 'invalid-password') 197 | then: 198 | def query = it == 2 ? '&showRecaptcha' : '' 199 | assertThat(response) 200 | .hasFoundStatus() 201 | .redirectsTo("http://localhost:$port/login?error$query") 202 | } 203 | 204 | //Log in successfully with captcha 205 | when: 206 | response = logIn('user', 'password', VALID_CAPTCHA_RESPONSE) 207 | then: 208 | assertThat(response) 209 | .hasFoundStatus() 210 | .redirectsTo("http://localhost:$port/") 211 | 212 | //Get secured data while logged in 213 | when: 214 | response = getSecuredData() 215 | then: 216 | assertThat(response) 217 | .hasOkStatus() 218 | .hasMessage(RESPONSE_DATA_MESSAGE) 219 | 220 | cleanup: 221 | resetUserLoginFailures() 222 | resetVerificationEndpoint() 223 | } 224 | 225 | private void resetUserLoginFailures() { 226 | stubSuccessfulRecaptchaValidation() 227 | recaptcha.validation.secretKey = VALID_SECRET 228 | 229 | def response = logIn('user', 'password', VALID_CAPTCHA_RESPONSE) 230 | 231 | assertThat(response) 232 | .hasFoundStatus() 233 | .redirectsTo("http://localhost:$port/") 234 | } 235 | 236 | private void resetVerificationEndpoint() { 237 | recaptcha.validation.verificationUrl = 'http://localhost:8081/recaptcha/api/siteverify' 238 | } 239 | } -------------------------------------------------------------------------------- /src/test/groovy/com/github/mkopylec/recaptcha/specification/TestingSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.specification 2 | 3 | import com.github.mkopylec.recaptcha.BasicSpec 4 | import com.github.mkopylec.recaptcha.RecaptchaProperties 5 | import org.springframework.beans.factory.annotation.Autowired 6 | import org.springframework.test.context.TestPropertySource 7 | 8 | import static com.github.mkopylec.recaptcha.assertions.Assertions.assertThat 9 | import static com.github.mkopylec.recaptcha.validation.ErrorCode.INVALID_SECRET_KEY 10 | import static com.github.mkopylec.recaptcha.validation.ErrorCode.INVALID_USER_CAPTCHA_RESPONSE 11 | import static com.github.mkopylec.recaptcha.validation.ErrorCode.MISSING_USER_CAPTCHA_RESPONSE 12 | 13 | @TestPropertySource(properties = ['recaptcha.testing.enabled: true']) 14 | class TestingSpec extends BasicSpec { 15 | 16 | @Autowired 17 | private RecaptchaProperties recaptcha 18 | 19 | def "Should successfully validate reCAPTCHA when result is set to success"() { 20 | given: 21 | recaptcha.testing.successResult = true 22 | 23 | when: 24 | def response = validateRecaptchaInTestingMode() 25 | 26 | then: 27 | assertThat(response) 28 | .hasOkStatus() 29 | .hasSuccessfulValidationResult() 30 | .hasNoErrorCodes() 31 | 32 | cleanup: 33 | resetRecaptchaProperties() 34 | } 35 | 36 | def "Should unsuccessfully validate reCAPTCHA when result is set to failure"() { 37 | given: 38 | recaptcha.testing.successResult = false 39 | recaptcha.testing.resultErrorCodes = [MISSING_USER_CAPTCHA_RESPONSE] 40 | 41 | when: 42 | def response = validateRecaptchaInTestingMode() 43 | 44 | then: 45 | assertThat(response) 46 | .hasOkStatus() 47 | .hasUnsuccessfulValidationResult() 48 | .hasErrorCodes(MISSING_USER_CAPTCHA_RESPONSE) 49 | 50 | cleanup: 51 | resetRecaptchaProperties() 52 | } 53 | 54 | def "Should unsuccessfully validate reCAPTCHA with specific error codes when result is set to failure"() { 55 | given: 56 | recaptcha.testing.successResult = false 57 | recaptcha.testing.resultErrorCodes = [INVALID_SECRET_KEY, INVALID_USER_CAPTCHA_RESPONSE] 58 | 59 | when: 60 | def response = validateRecaptchaInTestingMode() 61 | 62 | then: 63 | assertThat(response) 64 | .hasOkStatus() 65 | .hasUnsuccessfulValidationResult() 66 | .hasErrorCodes(INVALID_SECRET_KEY, INVALID_USER_CAPTCHA_RESPONSE) 67 | 68 | cleanup: 69 | resetRecaptchaProperties() 70 | } 71 | 72 | private void resetRecaptchaProperties() { 73 | recaptcha.testing.resultErrorCodes = [] 74 | recaptcha.testing.successResult = true 75 | } 76 | } -------------------------------------------------------------------------------- /src/test/groovy/com/github/mkopylec/recaptcha/specification/ValidationSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.specification 2 | 3 | import com.github.mkopylec.recaptcha.BasicSpec 4 | import com.github.mkopylec.recaptcha.RecaptchaProperties 5 | import org.springframework.beans.factory.annotation.Autowired 6 | 7 | import static com.github.mkopylec.recaptcha.Strings.INVALID_SECRET 8 | import static com.github.mkopylec.recaptcha.Strings.VALID_CAPTCHA_RESPONSE 9 | import static com.github.mkopylec.recaptcha.Strings.VALID_SECRET 10 | import static com.github.mkopylec.recaptcha.assertions.Assertions.assertThat 11 | import static com.github.mkopylec.recaptcha.stubs.RecaptchaValidationStubs.stubCustomIpSuccessfulRecaptchaValidation 12 | import static com.github.mkopylec.recaptcha.stubs.RecaptchaValidationStubs.stubInvalidSecretRecaptchaValidation 13 | import static com.github.mkopylec.recaptcha.stubs.RecaptchaValidationStubs.stubMissingResponseRecaptchaValidation 14 | import static com.github.mkopylec.recaptcha.validation.ErrorCode.INVALID_SECRET_KEY 15 | import static com.github.mkopylec.recaptcha.validation.ErrorCode.MISSING_USER_CAPTCHA_RESPONSE 16 | 17 | class ValidationSpec extends BasicSpec { 18 | 19 | @Autowired 20 | private RecaptchaProperties recaptcha 21 | 22 | def "Should successfully validate reCAPTCHA when user response and secret key are valid resolving IP address from X-Forwarded-For header"() { 23 | given: 24 | stubCustomIpSuccessfulRecaptchaValidation('120.130.140.10') 25 | recaptcha.validation.secretKey = VALID_SECRET 26 | 27 | when: 28 | def response = validateRecaptcha(VALID_CAPTCHA_RESPONSE, '120.130.140.10, 320.200.100.0, 11.234.90.10') 29 | 30 | then: 31 | assertThat(response) 32 | .hasOkStatus() 33 | .hasSuccessfulValidationResult() 34 | .hasNoErrorCodes() 35 | } 36 | 37 | def "Should successfully validate reCAPTCHA with custom ip address when user response and secret key are valid"() { 38 | given: 39 | stubCustomIpSuccessfulRecaptchaValidation() 40 | recaptcha.validation.secretKey = VALID_SECRET 41 | 42 | when: 43 | def response = validateRecaptchaWithIp(VALID_CAPTCHA_RESPONSE) 44 | 45 | then: 46 | assertThat(response) 47 | .hasOkStatus() 48 | .hasSuccessfulValidationResult() 49 | .hasNoErrorCodes() 50 | } 51 | 52 | def "Should unsuccessfully validate reCAPTCHA when secret key is invalid"() { 53 | given: 54 | stubInvalidSecretRecaptchaValidation() 55 | recaptcha.validation.secretKey = INVALID_SECRET 56 | 57 | when: 58 | def response = validateRecaptcha(VALID_CAPTCHA_RESPONSE) 59 | 60 | then: 61 | assertThat(response) 62 | .hasOkStatus() 63 | .hasUnsuccessfulValidationResult() 64 | .hasErrorCodes(INVALID_SECRET_KEY) 65 | } 66 | 67 | def "Should unsuccessfully validate reCAPTCHA when user response is missing"() { 68 | given: 69 | stubMissingResponseRecaptchaValidation() 70 | recaptcha.validation.secretKey = VALID_SECRET 71 | 72 | when: 73 | def response = validateRecaptcha(null) 74 | 75 | then: 76 | assertThat(response) 77 | .hasOkStatus() 78 | .hasUnsuccessfulValidationResult() 79 | .hasErrorCodes(MISSING_USER_CAPTCHA_RESPONSE) 80 | } 81 | } -------------------------------------------------------------------------------- /src/test/groovy/com/github/mkopylec/recaptcha/stubs/RecaptchaValidationStubs.groovy: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.stubs 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper 4 | import com.github.tomakehurst.wiremock.matching.StringValuePattern 5 | 6 | import static com.github.mkopylec.recaptcha.Strings.INVALID_CAPTCHA_RESPONSE 7 | import static com.github.mkopylec.recaptcha.Strings.INVALID_SECRET 8 | import static com.github.mkopylec.recaptcha.Strings.REMOTE_IP_ADDRESS 9 | import static com.github.mkopylec.recaptcha.Strings.VALID_CAPTCHA_RESPONSE 10 | import static com.github.mkopylec.recaptcha.Strings.VALID_SECRET 11 | import static com.github.tomakehurst.wiremock.client.WireMock.aResponse 12 | import static com.github.tomakehurst.wiremock.client.WireMock.containing 13 | import static com.github.tomakehurst.wiremock.client.WireMock.post 14 | import static com.github.tomakehurst.wiremock.client.WireMock.stubFor 15 | import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo 16 | import static org.springframework.http.HttpHeaders.CONTENT_TYPE 17 | import static org.springframework.http.HttpStatus.OK 18 | import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE 19 | 20 | class RecaptchaValidationStubs { 21 | 22 | private static ObjectMapper mapper = new ObjectMapper() 23 | 24 | static void stubSuccessfulRecaptchaValidation() { 25 | stubRecaptchaValidation(VALID_CAPTCHA_RESPONSE, VALID_SECRET, '', true, []) 26 | } 27 | 28 | static void stubCustomIpSuccessfulRecaptchaValidation() { 29 | stubRecaptchaValidation(VALID_CAPTCHA_RESPONSE, VALID_SECRET, REMOTE_IP_ADDRESS, true, []) 30 | } 31 | 32 | static void stubCustomIpSuccessfulRecaptchaValidation(String clientIp) { 33 | stubRecaptchaValidation(VALID_CAPTCHA_RESPONSE, VALID_SECRET, clientIp, true, []) 34 | } 35 | 36 | static void stubInvalidSecretRecaptchaValidation() { 37 | stubRecaptchaValidation(VALID_CAPTCHA_RESPONSE, INVALID_SECRET, '', false, ['invalid-input-secret']) 38 | } 39 | 40 | static void stubMissingResponseRecaptchaValidation() { 41 | stubRecaptchaValidation(null, VALID_SECRET, '', false, ['missing-input-response']) 42 | } 43 | 44 | static void stubInvalidResponseRecaptchaValidation() { 45 | stubRecaptchaValidation(INVALID_CAPTCHA_RESPONSE, VALID_SECRET, '', false, ['invalid-input-response']) 46 | } 47 | 48 | private static void stubRecaptchaValidation( 49 | String userResponse, String secretKey, String remoteIp, boolean success, List errors 50 | ) { 51 | def result = mapper.writeValueAsString(['success': success, 'error-codes': errors]) 52 | stubFor(post(urlEqualTo('/recaptcha/api/siteverify')) 53 | .withRequestBody(nullableContaining('response', userResponse)) 54 | .withRequestBody(nullableContaining('secret', secretKey)) 55 | .withRequestBody(nullableContaining('remoteip', remoteIp)) 56 | .willReturn( 57 | aResponse() 58 | .withStatus(OK.value()) 59 | .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) 60 | .withBody(result) 61 | )); 62 | } 63 | 64 | private static StringValuePattern nullableContaining(String param, String value) { 65 | value != null ? containing("$param=$value") : containing('') 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/test/java/com/github/mkopylec/recaptcha/Strings.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha; 2 | 3 | public final class Strings { 4 | 5 | public static final String REMOTE_IP_ADDRESS = "69.007.100.200"; 6 | public static final String VALID_CAPTCHA_RESPONSE = "valid-captcha"; 7 | public static final String INVALID_CAPTCHA_RESPONSE = "invalid-captcha"; 8 | public static final String VALID_SECRET = "valid-secret"; 9 | public static final String INVALID_SECRET = "invalid-secret"; 10 | public static final String RESPONSE_DATA_MESSAGE = "I am response"; 11 | 12 | private Strings() { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/github/mkopylec/recaptcha/TestApplication.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha; 2 | 3 | import org.apache.tomcat.util.http.LegacyCookieProcessor; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; 6 | import org.springframework.boot.web.server.WebServerFactoryCustomizer; 7 | import org.springframework.context.annotation.Bean; 8 | 9 | import static org.springframework.boot.SpringApplication.run; 10 | 11 | @SpringBootApplication 12 | public class TestApplication { 13 | 14 | public static void main(String[] args) { 15 | run(TestApplication.class, args); 16 | } 17 | 18 | @Bean 19 | public WebServerFactoryCustomizer cookieProcessorCustomizer() { 20 | return factory -> factory.addContextCustomizers(context -> context.setCookieProcessor(new LegacyCookieProcessor())); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/test/java/com/github/mkopylec/recaptcha/security/AccessConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.security; 2 | 3 | import com.github.mkopylec.recaptcha.security.login.FormLoginConfigurerEnhancer; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 6 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 7 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 8 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 9 | 10 | @Configuration 11 | @EnableWebSecurity 12 | public class AccessConfiguration extends WebSecurityConfigurerAdapter { 13 | 14 | private final FormLoginConfigurerEnhancer enhancer; 15 | 16 | public AccessConfiguration(FormLoginConfigurerEnhancer enhancer) { 17 | this.enhancer = enhancer; 18 | } 19 | 20 | @Override 21 | protected void configure(HttpSecurity http) throws Exception { 22 | enhancer.addRecaptchaSupport(http.formLogin()) 23 | .and() 24 | .csrf().disable() 25 | .authorizeRequests().antMatchers("/testSecurity/**").authenticated(); 26 | } 27 | 28 | @Override 29 | public void configure(WebSecurity web) { 30 | web.ignoring().antMatchers("/testValidation/**", "/testTesting/**"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/github/mkopylec/recaptcha/security/ResponseData.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.security; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | 6 | public class ResponseData { 7 | 8 | private final String message; 9 | 10 | @JsonCreator 11 | public ResponseData(@JsonProperty("message") String message) { 12 | this.message = message; 13 | } 14 | 15 | public String getMessage() { 16 | return message; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/com/github/mkopylec/recaptcha/security/SecurityController.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.security; 2 | 3 | import org.springframework.web.bind.annotation.RequestMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | import static com.github.mkopylec.recaptcha.Strings.RESPONSE_DATA_MESSAGE; 7 | import static org.springframework.web.bind.annotation.RequestMethod.POST; 8 | 9 | @RestController 10 | @RequestMapping(value = "testSecurity") 11 | public class SecurityController { 12 | 13 | @RequestMapping(value = "getResponse", method = POST) 14 | public ResponseData getResponseData() { 15 | return new ResponseData(RESPONSE_DATA_MESSAGE); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/test/java/com/github/mkopylec/recaptcha/testing/TestingController.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.testing; 2 | 3 | import com.github.mkopylec.recaptcha.validation.RecaptchaValidator; 4 | import com.github.mkopylec.recaptcha.validation.ValidationResult; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import javax.servlet.http.HttpServletRequest; 10 | 11 | import static org.springframework.web.bind.annotation.RequestMethod.POST; 12 | 13 | @RestController 14 | @RequestMapping(value = "testTesting") 15 | public class TestingController { 16 | 17 | @Autowired 18 | private RecaptchaValidator recaptchaValidator; 19 | 20 | @RequestMapping(value = "validate", method = POST) 21 | public ValidationResult validate(HttpServletRequest request) { 22 | return recaptchaValidator.validate(request); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/github/mkopylec/recaptcha/validation/ValidationController.java: -------------------------------------------------------------------------------- 1 | package com.github.mkopylec.recaptcha.validation; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | 9 | import static com.github.mkopylec.recaptcha.Strings.REMOTE_IP_ADDRESS; 10 | import static org.springframework.web.bind.annotation.RequestMethod.POST; 11 | 12 | @RestController 13 | @RequestMapping(value = "testValidation") 14 | public class ValidationController { 15 | 16 | @Autowired 17 | private RecaptchaValidator recaptchaValidator; 18 | 19 | @RequestMapping(value = "userResponse", method = POST) 20 | public ValidationResult validateUsingUserResponse(HttpServletRequest request) { 21 | return recaptchaValidator.validate(request); 22 | } 23 | 24 | @RequestMapping(value = "userResponseAndIp", method = POST) 25 | public ValidationResult validateUsingUserResponseAndIp(HttpServletRequest request) { 26 | return recaptchaValidator.validate(request, REMOTE_IP_ADDRESS); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/resources/application.yml: -------------------------------------------------------------------------------- 1 | recaptcha: 2 | validation: 3 | verification-url: http://localhost:8081/recaptcha/api/siteverify 4 | security: 5 | login-failures-threshold: 3 6 | 7 | spring: 8 | security: 9 | user: 10 | name: user 11 | password: password 12 | 13 | logging: 14 | level: 15 | com.github.mkopylec: debug 16 | 17 | --------------------------------------------------------------------------------