├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── kdgregory │ │ └── example │ │ └── cognito │ │ ├── servlets │ │ ├── AbstractCognitoServlet.java │ │ ├── ConfirmSignUp.java │ │ ├── Constants.java │ │ ├── SignIn.java │ │ ├── SignUp.java │ │ └── ValidatedAction.java │ │ └── util │ │ └── CredentialsCache.java ├── resources │ └── log4j.properties └── webapp │ ├── WEB-INF │ └── web.xml │ ├── confirm-signup.html │ ├── css │ └── common.css │ ├── signin.html │ └── validated-page.html ├── scripts └── cognito-create-userpool.sh └── test └── java └── com └── kdgregory └── example └── cognito └── util └── TestCredentialsCache.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # This project has been archived 2 | 3 | It has been two years since I've worked with Cognito. At the time, this was the best approach that I could come up with, 4 | but I've been told that it's no longer appropriate. 5 | 6 | You are welcome to fork this project, modify it, do whatever you want within the constraints of the Apache 2 License. 7 | But I'm no longer maintaining it, and don't have the knowledge to answer your questions. 8 | 9 | ---- 10 | 11 | > This is the example code for a [blog post](http://blog.kdgregory.com/2016/12/server-side-authentication-with-amazon.html). 12 | Please read that post before downloading and building this project, as it explains a lot of the decisions that I made. 13 | Some of those decisions I would make again, some I wouldn't. 14 | 15 | Cognito is marketed as a client-side technology. It also happens to be by far the worst-documented Amazon service that I've ever used. However, its feature set is compelling: you can manage users, provide validation of both email and mobile phone, and support multi-factor authentication. But, as I said, it's the worst-documented Amazon service that I've ever used. 16 | 17 | Based on the documentation, reading the Android source code, and a bunch of experimentation, I've worked out how to use it from the server side. I've wrapped the basic operations in Java servlets, with some simple front-end pages to invoke them. Currently it supports the following features: 18 | 19 | * Users identified via email address. 20 | * Signup uses a temporary password, generated by Cognito. 21 | * Authentication using Cognito-generated tokens (with caching so we don't hit a call limit). 22 | 23 | If you believe that I'm using Cognito incorrectly, feel free to open an issue. However, please do not use issues 24 | to ask debugging questions; [Stack Overflow](https://stackoverflow.com/questions/tagged/amazon-web-services) is 25 | a much better resource. 26 | 27 | 28 | ## Building and Running 29 | 30 | Start by creating the user pool. You can do this manually, or by running the provided script: 31 | 32 | > src/scripts/cognito-create-userpool.sh Example Example 33 | User Pool ID: us-east-1_rCQ6gAd1Q 34 | Client ID: 5co5s8e43krcdps2lrp4fo301i 35 | 36 | Update `src/main/webapp/WEB-INF/web.xml`, setting the initialization parameters `cognito_pool_id` and `cognito_client_id` to the values output in the previous step. 37 | 38 | You can build with Maven and deploy to your favorite app-server, import into your favorite IDE, or run with the [Jetty plugin](https://www.eclipse.org/jetty/documentation/9.4.x/jetty-maven-plugin.html): 39 | 40 | mvn jetty:run 41 | 42 | The web-app entry-point is [http://localhost:8080/cognito-webapp/](http://localhost:8080/cognito-webapp/). 43 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.kdgregory.example 6 | cognito-webapp 7 | 1.0-SNAPSHOT 8 | war 9 | 10 | Cognito Service Example 11 | 12 | 13 | Demonstrates the use of AWS Cognito to provide simple authentication for a webapp. 14 | 15 | 16 | 17 | 18 | 19 | UTF-8 20 | UTF-8 21 | 22 | 1.11.458 23 | 4.10 24 | 1.0.14 25 | 1.2.12 26 | 2.5 27 | 1.7.13 28 | 29 | 30 | 31 | 32 | 33 | com.amazonaws 34 | aws-java-sdk-cognitoidp 35 | ${aws-sdk.version} 36 | 37 | 38 | log4j 39 | log4j 40 | ${log4j.version} 41 | 42 | 43 | net.sf.kdgcommons 44 | kdgcommons 45 | ${kdgcommons.version} 46 | 47 | 48 | org.slf4j 49 | slf4j-api 50 | ${slf4j.version} 51 | 52 | 53 | org.slf4j 54 | slf4j-log4j12 55 | ${slf4j.version} 56 | 57 | 58 | 59 | javax.servlet 60 | servlet-api 61 | ${servlet.version} 62 | provided 63 | 64 | 65 | 66 | junit 67 | junit 68 | ${junit.version} 69 | test 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | org.apache.maven.plugins 78 | maven-compiler-plugin 79 | 80 | 1.7 81 | 1.7 82 | true 83 | 84 | 85 | 86 | org.mortbay.jetty 87 | maven-jetty-plugin 88 | 89 | 10 90 | 91 | 92 | 8080 93 | 60000 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /src/main/java/com/kdgregory/example/cognito/servlets/AbstractCognitoServlet.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) Keith D Gregory 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package com.kdgregory.example.cognito.servlets; 16 | 17 | import java.io.IOException; 18 | import java.io.PrintWriter; 19 | 20 | import javax.servlet.ServletException; 21 | import javax.servlet.http.Cookie; 22 | import javax.servlet.http.HttpServlet; 23 | import javax.servlet.http.HttpServletResponse; 24 | 25 | import org.slf4j.Logger; 26 | import org.slf4j.LoggerFactory; 27 | 28 | import com.amazonaws.services.cognitoidp.AWSCognitoIdentityProvider; 29 | import com.amazonaws.services.cognitoidp.AWSCognitoIdentityProviderClientBuilder; 30 | import com.amazonaws.services.cognitoidp.model.AuthenticationResultType; 31 | 32 | import com.kdgregory.example.cognito.util.CredentialsCache; 33 | 34 | import net.sf.kdgcommons.lang.StringUtil; 35 | 36 | 37 | /** 38 | * Base class for all servlets; provides common functionality. 39 | */ 40 | public abstract class AbstractCognitoServlet 41 | extends HttpServlet 42 | { 43 | private static final long serialVersionUID = 1L; 44 | 45 | protected Logger logger = LoggerFactory.getLogger(getClass()); 46 | protected AWSCognitoIdentityProvider cognitoClient = AWSCognitoIdentityProviderClientBuilder.defaultClient(); 47 | 48 | // credentials cache is static so that all validating servlets can check it 49 | protected static CredentialsCache tokenCache = new CredentialsCache(10000); 50 | 51 | 52 | /** 53 | * Returns the Cognito pool ID, defined in the servlet context. 54 | */ 55 | protected String cognitoPoolId() 56 | { 57 | return getServletContext().getInitParameter("cognito_pool_id"); 58 | } 59 | 60 | 61 | /** 62 | * Returns the Cognito client ID, defined in the servlet context. 63 | */ 64 | protected String cognitoClientId() 65 | { 66 | return getServletContext().getInitParameter("cognito_client_id"); 67 | } 68 | 69 | 70 | /** 71 | * Updates the access and refresh tokens, stored in cookies in the response. 72 | * Note that refresh token is optional -- on a refresh, we just get a new 73 | * access token. 74 | *

75 | * Note: also updates the token cache. 76 | */ 77 | protected void updateCredentialCookies(HttpServletResponse response, AuthenticationResultType authResult) 78 | { 79 | tokenCache.addToken(authResult.getAccessToken()); 80 | 81 | Cookie accessTokenCookie = new Cookie(Constants.CookieNames.ACCESS_TOKEN, authResult.getAccessToken()); 82 | response.addCookie(accessTokenCookie); 83 | 84 | if (!StringUtil.isBlank(authResult.getRefreshToken())) 85 | { 86 | Cookie refreshTokenCookie = new Cookie(Constants.CookieNames.REFRESH_TOKEN, authResult.getRefreshToken()); 87 | response.addCookie(refreshTokenCookie); 88 | } 89 | } 90 | 91 | 92 | /** 93 | * Writes the response message. All responses use status code 200; the client must 94 | * look at the message to determine its action. 95 | */ 96 | protected void reportResult(HttpServletResponse response, String responseMessage) 97 | throws ServletException, IOException 98 | { 99 | response.setStatus(HttpServletResponse.SC_OK); 100 | response.setContentType("text/plain"); 101 | try (PrintWriter out = response.getWriter()) 102 | { 103 | out.print(responseMessage); 104 | } 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/com/kdgregory/example/cognito/servlets/ConfirmSignUp.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) Keith D Gregory 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package com.kdgregory.example.cognito.servlets; 16 | 17 | import java.io.IOException; 18 | import java.util.HashMap; 19 | import java.util.Map; 20 | 21 | import javax.servlet.ServletException; 22 | import javax.servlet.http.HttpServletRequest; 23 | import javax.servlet.http.HttpServletResponse; 24 | 25 | import com.amazonaws.services.cognitoidp.model.*; 26 | 27 | import net.sf.kdgcommons.lang.StringUtil; 28 | import net.sf.kdgcommons.lang.ThreadUtil; 29 | 30 | 31 | /** 32 | * This servlet finishes the signup process for a new user, changing the temporary 33 | * password to a final password. 34 | */ 35 | public class ConfirmSignUp extends AbstractCognitoServlet 36 | { 37 | private static final long serialVersionUID = 1L; 38 | 39 | 40 | @Override 41 | protected void doPost(HttpServletRequest request, HttpServletResponse response) 42 | throws ServletException, IOException 43 | { 44 | String emailAddress = request.getParameter(Constants.RequestParameters.EMAIL); 45 | String tempPassword = request.getParameter(Constants.RequestParameters.TEMPORARY_PASSWORD); 46 | String finalPassword = request.getParameter(Constants.RequestParameters.PASSWORD); 47 | if (StringUtil.isBlank(emailAddress) || StringUtil.isBlank(tempPassword) || StringUtil.isBlank(finalPassword)) 48 | { 49 | reportResult(response, Constants.ResponseMessages.INVALID_REQUEST); 50 | return; 51 | } 52 | 53 | logger.debug("confirming signup of user {}", emailAddress); 54 | 55 | try 56 | { 57 | // must attempt signin with temporary password in order to establish session for password change 58 | // (even though it's documented as not required) 59 | 60 | Map initialParams = new HashMap(); 61 | initialParams.put("USERNAME", emailAddress); 62 | initialParams.put("PASSWORD", tempPassword); 63 | 64 | AdminInitiateAuthRequest initialRequest = new AdminInitiateAuthRequest() 65 | .withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH) 66 | .withAuthParameters(initialParams) 67 | .withClientId(cognitoClientId()) 68 | .withUserPoolId(cognitoPoolId()); 69 | 70 | AdminInitiateAuthResult initialResponse = cognitoClient.adminInitiateAuth(initialRequest); 71 | if (! ChallengeNameType.NEW_PASSWORD_REQUIRED.name().equals(initialResponse.getChallengeName())) 72 | { 73 | throw new RuntimeException("unexpected challenge: " + initialResponse.getChallengeName()); 74 | } 75 | 76 | Map challengeResponses = new HashMap(); 77 | challengeResponses.put("USERNAME", emailAddress); 78 | challengeResponses.put("PASSWORD", tempPassword); 79 | challengeResponses.put("NEW_PASSWORD", finalPassword); 80 | 81 | AdminRespondToAuthChallengeRequest finalRequest = new AdminRespondToAuthChallengeRequest() 82 | .withChallengeName(ChallengeNameType.NEW_PASSWORD_REQUIRED) 83 | .withChallengeResponses(challengeResponses) 84 | .withClientId(cognitoClientId()) 85 | .withUserPoolId(cognitoPoolId()) 86 | .withSession(initialResponse.getSession()); 87 | 88 | AdminRespondToAuthChallengeResult challengeResponse = cognitoClient.adminRespondToAuthChallenge(finalRequest); 89 | if (StringUtil.isBlank(challengeResponse.getChallengeName())) 90 | { 91 | updateCredentialCookies(response, challengeResponse.getAuthenticationResult()); 92 | reportResult(response, Constants.ResponseMessages.LOGGED_IN); 93 | } 94 | else 95 | { 96 | throw new RuntimeException("unexpected challenge: " + challengeResponse.getChallengeName()); 97 | } 98 | } 99 | catch (InvalidPasswordException ex) 100 | { 101 | logger.debug("{} submitted invalid password", emailAddress); 102 | reportResult(response, Constants.ResponseMessages.INVALID_PASSWORD); 103 | } 104 | catch (UserNotFoundException ex) 105 | { 106 | logger.debug("not found: {}", emailAddress); 107 | reportResult(response, Constants.ResponseMessages.NO_SUCH_USER); 108 | } 109 | catch (NotAuthorizedException ex) 110 | { 111 | logger.debug("invalid credentials: {}", emailAddress); 112 | reportResult(response, Constants.ResponseMessages.NO_SUCH_USER); 113 | } 114 | catch (TooManyRequestsException ex) 115 | { 116 | logger.warn("caught TooManyRequestsException, delaying then retrying"); 117 | ThreadUtil.sleepQuietly(250); 118 | doPost(request, response); 119 | } 120 | } 121 | 122 | 123 | @Override 124 | public String getServletInfo() 125 | { 126 | return "Handles second stage of user signup, replacing temporary password by final"; 127 | } 128 | 129 | } 130 | -------------------------------------------------------------------------------- /src/main/java/com/kdgregory/example/cognito/servlets/Constants.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) Keith D Gregory 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package com.kdgregory.example.cognito.servlets; 16 | 17 | /** 18 | * Holds constants that cross servlets. These are categorized using static nested classes. 19 | */ 20 | public abstract class Constants 21 | { 22 | /** 23 | * Parameter names. Should be self-explanatory. 24 | */ 25 | public abstract class RequestParameters 26 | { 27 | public final static String EMAIL = "EMAIL"; 28 | public final static String PASSWORD = "PASSWORD"; 29 | public final static String TEMPORARY_PASSWORD = "TEMPORARY_PASSWORD"; 30 | } 31 | 32 | 33 | /** 34 | * Standard response messages. These strings will constitute the entirety of the response body. 35 | */ 36 | public abstract class ResponseMessages 37 | { 38 | /** 39 | * User is not logged in -- client should redirect to sign-in page. 40 | */ 41 | public final static String NOT_LOGGED_IN = "NOT_LOGGED_IN"; 42 | 43 | /** 44 | * User is logged in (returned after successful sign-in/sign-up, or from an auth check). 45 | */ 46 | public final static String LOGGED_IN = "LOGGED_IN"; 47 | 48 | /** 49 | * Request was mising required parameters 50 | */ 51 | public final static String INVALID_REQUEST = "INVALID_REQUEST"; 52 | 53 | /** 54 | * The supplied username and/or password were incorrect. 55 | * We do not differentiate between the two cases as a security measure. 56 | */ 57 | public final static String NO_SUCH_USER = "NO_SUCH_USER"; 58 | 59 | /** 60 | * Returned by signup when a user with the given email already exists. 61 | */ 62 | public final static String USER_ALREADY_EXISTS = "USER_ALREADY_EXISTS"; 63 | 64 | /** 65 | * User was created, must log in and change password. 66 | */ 67 | public final static String USER_CREATED = "USER_CREATED"; 68 | 69 | /** 70 | * New user attempted to login via normal signin page, needs to go to signup-confirm page. 71 | */ 72 | public final static String FORCE_PASSWORD_CHANGE = "FORCE_PASSWORD_CHANGE"; 73 | 74 | /** 75 | * Returned when user submits a permanent password that doesn't meet criteria. 76 | */ 77 | public final static String INVALID_PASSWORD = "INVALID_PASSWORD"; 78 | } 79 | 80 | 81 | /** 82 | * Names of the cookies used to store credentials. 83 | */ 84 | public abstract class CookieNames 85 | { 86 | public final static String ACCESS_TOKEN = "ACCESS_TOKEN"; 87 | public final static String REFRESH_TOKEN = "REFRESH_TOKEN"; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/kdgregory/example/cognito/servlets/SignIn.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) Keith D Gregory 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package com.kdgregory.example.cognito.servlets; 16 | 17 | import java.io.IOException; 18 | import java.util.HashMap; 19 | import java.util.Map; 20 | 21 | import javax.servlet.ServletException; 22 | import javax.servlet.http.HttpServletRequest; 23 | import javax.servlet.http.HttpServletResponse; 24 | 25 | import com.amazonaws.services.cognitoidp.model.*; 26 | 27 | import net.sf.kdgcommons.lang.StringUtil; 28 | import net.sf.kdgcommons.lang.ThreadUtil; 29 | 30 | 31 | /** 32 | * This servlet handles normal user sign-in, based on username and password. 33 | */ 34 | public class SignIn extends AbstractCognitoServlet 35 | { 36 | private static final long serialVersionUID = 1L; 37 | 38 | 39 | @Override 40 | protected void doPost(HttpServletRequest request, HttpServletResponse response) 41 | throws ServletException, IOException 42 | { 43 | String emailAddress = request.getParameter(Constants.RequestParameters.EMAIL); 44 | String password = request.getParameter(Constants.RequestParameters.PASSWORD); 45 | if (StringUtil.isBlank(emailAddress) || StringUtil.isBlank(password)) 46 | { 47 | reportResult(response, Constants.ResponseMessages.INVALID_REQUEST); 48 | return; 49 | } 50 | 51 | logger.debug("authenticating {}", emailAddress); 52 | 53 | try 54 | { 55 | Map authParams = new HashMap(); 56 | authParams.put("USERNAME", emailAddress); 57 | authParams.put("PASSWORD", password); 58 | 59 | AdminInitiateAuthRequest authRequest = new AdminInitiateAuthRequest() 60 | .withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH) 61 | .withAuthParameters(authParams) 62 | .withClientId(cognitoClientId()) 63 | .withUserPoolId(cognitoPoolId()); 64 | 65 | AdminInitiateAuthResult authResponse = cognitoClient.adminInitiateAuth(authRequest); 66 | if (StringUtil.isBlank(authResponse.getChallengeName())) 67 | { 68 | updateCredentialCookies(response, authResponse.getAuthenticationResult()); 69 | reportResult(response, Constants.ResponseMessages.LOGGED_IN); 70 | return; 71 | } 72 | else if (ChallengeNameType.NEW_PASSWORD_REQUIRED.name().equals(authResponse.getChallengeName())) 73 | { 74 | logger.debug("{} attempted to sign in with temporary password", emailAddress); 75 | reportResult(response, Constants.ResponseMessages.FORCE_PASSWORD_CHANGE); 76 | } 77 | else 78 | { 79 | throw new RuntimeException("unexpected challenge on signin: " + authResponse.getChallengeName()); 80 | } 81 | } 82 | catch (UserNotFoundException ex) 83 | { 84 | logger.debug("not found: {}", emailAddress); 85 | reportResult(response, Constants.ResponseMessages.NO_SUCH_USER); 86 | } 87 | catch (NotAuthorizedException ex) 88 | { 89 | logger.debug("invalid credentials: {}", emailAddress); 90 | reportResult(response, Constants.ResponseMessages.NO_SUCH_USER); 91 | } 92 | catch (TooManyRequestsException ex) 93 | { 94 | logger.warn("caught TooManyRequestsException, delaying then retrying"); 95 | ThreadUtil.sleepQuietly(250); 96 | doPost(request, response); 97 | } 98 | } 99 | 100 | 101 | @Override 102 | public String getServletInfo() 103 | { 104 | return "Handles user signin"; 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/com/kdgregory/example/cognito/servlets/SignUp.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) Keith D Gregory 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package com.kdgregory.example.cognito.servlets; 16 | 17 | import java.io.IOException; 18 | 19 | import javax.servlet.ServletException; 20 | import javax.servlet.http.HttpServletRequest; 21 | import javax.servlet.http.HttpServletResponse; 22 | 23 | import com.amazonaws.services.cognitoidp.model.*; 24 | 25 | import net.sf.kdgcommons.lang.StringUtil; 26 | import net.sf.kdgcommons.lang.ThreadUtil; 27 | 28 | 29 | /** 30 | * This servlet initiates the signup process for a new user. 31 | */ 32 | public class SignUp extends AbstractCognitoServlet 33 | { 34 | private static final long serialVersionUID = 1L; 35 | 36 | 37 | @Override 38 | protected void doPost(HttpServletRequest request, HttpServletResponse response) 39 | throws ServletException, IOException 40 | { 41 | String emailAddress = request.getParameter(Constants.RequestParameters.EMAIL); 42 | if (StringUtil.isBlank(emailAddress)) 43 | { 44 | reportResult(response, Constants.ResponseMessages.INVALID_REQUEST); 45 | return; 46 | } 47 | 48 | logger.debug("creating user {}", emailAddress); 49 | 50 | try 51 | { 52 | AdminCreateUserRequest cognitoRequest = new AdminCreateUserRequest() 53 | .withUserPoolId(cognitoPoolId()) 54 | .withUsername(emailAddress) 55 | .withUserAttributes( 56 | new AttributeType() 57 | .withName("email") 58 | .withValue(emailAddress), 59 | new AttributeType() 60 | .withName("email_verified") 61 | .withValue("true")) 62 | .withDesiredDeliveryMediums(DeliveryMediumType.EMAIL) 63 | .withForceAliasCreation(Boolean.FALSE); 64 | 65 | cognitoClient.adminCreateUser(cognitoRequest); 66 | reportResult(response, Constants.ResponseMessages.USER_CREATED); 67 | } 68 | catch (UsernameExistsException ex) 69 | { 70 | logger.debug("user already exists: {}", emailAddress); 71 | reportResult(response, Constants.ResponseMessages.USER_ALREADY_EXISTS); 72 | } 73 | catch (TooManyRequestsException ex) 74 | { 75 | logger.warn("caught TooManyRequestsException, delaying then retrying"); 76 | ThreadUtil.sleepQuietly(250); 77 | doPost(request, response); 78 | } 79 | } 80 | 81 | 82 | @Override 83 | public String getServletInfo() 84 | { 85 | return "Handles the first stage of user signup, creating the user entry"; 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/com/kdgregory/example/cognito/servlets/ValidatedAction.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) Keith D Gregory 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package com.kdgregory.example.cognito.servlets; 16 | 17 | import java.io.IOException; 18 | import java.util.HashMap; 19 | import java.util.Map; 20 | 21 | import javax.servlet.ServletException; 22 | import javax.servlet.http.Cookie; 23 | import javax.servlet.http.HttpServletRequest; 24 | import javax.servlet.http.HttpServletResponse; 25 | 26 | import com.amazonaws.services.cognitoidp.model.*; 27 | 28 | import net.sf.kdgcommons.lang.StringUtil; 29 | import net.sf.kdgcommons.lang.ThreadUtil; 30 | 31 | 32 | /** 33 | * This servlet takes the place of some action that requires a valid user. It simply 34 | * returns text indicating whether or not the user is authenticated. 35 | *

36 | * In a real application, this validation logic (and associated cache) should be pushed 37 | * into the abstract servlet. 38 | */ 39 | public class ValidatedAction extends AbstractCognitoServlet 40 | { 41 | private static final long serialVersionUID = 1L; 42 | 43 | 44 | 45 | @Override 46 | protected void doGet(HttpServletRequest request, HttpServletResponse response) 47 | throws ServletException, IOException 48 | { 49 | String accessToken = null; 50 | String refreshToken = null; 51 | 52 | logger.debug("attempting validation"); 53 | 54 | Cookie[] cookies = request.getCookies(); 55 | if (cookies == null) 56 | { 57 | logger.warn("request from {} did not have cookies", request.getRemoteAddr()); 58 | reportResult(response, Constants.ResponseMessages.NOT_LOGGED_IN); 59 | return; 60 | } 61 | 62 | for (Cookie cookie : cookies) 63 | { 64 | if (cookie.getName().equals(Constants.CookieNames.ACCESS_TOKEN)) 65 | accessToken = cookie.getValue(); 66 | if (cookie.getName().equals(Constants.CookieNames.REFRESH_TOKEN)) 67 | refreshToken = cookie.getValue(); 68 | } 69 | 70 | if (tokenCache.checkToken(accessToken)) 71 | { 72 | logger.debug("token was found in cache, not going to AWS"); 73 | reportResult(response, Constants.ResponseMessages.LOGGED_IN); 74 | return; 75 | } 76 | 77 | try 78 | { 79 | GetUserRequest authRequest = new GetUserRequest().withAccessToken(accessToken); 80 | GetUserResult authResponse = cognitoClient.getUser(authRequest); 81 | 82 | logger.debug("successful validation for {}", authResponse.getUsername()); 83 | tokenCache.addToken(accessToken); 84 | reportResult(response, Constants.ResponseMessages.LOGGED_IN); 85 | } 86 | catch (NotAuthorizedException ex) 87 | { 88 | if (ex.getErrorMessage().equals("Access Token has expired")) 89 | { 90 | attemptRefresh(refreshToken, response); 91 | } 92 | else 93 | { 94 | logger.warn("exception during validation: {}", ex.getMessage()); 95 | reportResult(response, Constants.ResponseMessages.NOT_LOGGED_IN); 96 | } 97 | } 98 | catch (TooManyRequestsException ex) 99 | { 100 | logger.warn("caught TooManyRequestsException, delaying then retrying"); 101 | ThreadUtil.sleepQuietly(250); 102 | doPost(request, response); 103 | } 104 | } 105 | 106 | 107 | /** 108 | * Attempts to create a new access token based on the provided refresh token. 109 | */ 110 | private void attemptRefresh(String refreshToken, HttpServletResponse response) 111 | throws ServletException, IOException 112 | { 113 | try 114 | { 115 | Map authParams = new HashMap(); 116 | authParams.put("REFRESH_TOKEN", refreshToken); 117 | 118 | AdminInitiateAuthRequest refreshRequest = new AdminInitiateAuthRequest() 119 | .withAuthFlow(AuthFlowType.REFRESH_TOKEN) 120 | .withAuthParameters(authParams) 121 | .withClientId(cognitoClientId()) 122 | .withUserPoolId(cognitoPoolId()); 123 | 124 | AdminInitiateAuthResult refreshResponse = cognitoClient.adminInitiateAuth(refreshRequest); 125 | if (StringUtil.isBlank(refreshResponse.getChallengeName())) 126 | { 127 | logger.debug("successfully refreshed token"); 128 | updateCredentialCookies(response, refreshResponse.getAuthenticationResult()); 129 | reportResult(response, Constants.ResponseMessages.LOGGED_IN); 130 | } 131 | else 132 | { 133 | logger.warn("unexpected challenge when refreshing token: {}", refreshResponse.getChallengeName()); 134 | reportResult(response, Constants.ResponseMessages.NOT_LOGGED_IN); 135 | } 136 | } 137 | catch (TooManyRequestsException ex) 138 | { 139 | logger.warn("caught TooManyRequestsException, delaying then retrying"); 140 | ThreadUtil.sleepQuietly(250); 141 | attemptRefresh(refreshToken, response); 142 | } 143 | catch (AWSCognitoIdentityProviderException ex) 144 | { 145 | logger.debug("exception during token refresh: {}", ex.getMessage()); 146 | reportResult(response, Constants.ResponseMessages.NOT_LOGGED_IN); 147 | } 148 | } 149 | 150 | 151 | @Override 152 | public String getServletInfo() 153 | { 154 | return "Checks authorization based on tokens stored in cookies"; 155 | } 156 | 157 | } 158 | -------------------------------------------------------------------------------- /src/main/java/com/kdgregory/example/cognito/util/CredentialsCache.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) Keith D Gregory 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package com.kdgregory.example.cognito.util; 16 | 17 | import java.io.Serializable; 18 | import java.util.Collections; 19 | import java.util.Date; 20 | import java.util.LinkedHashMap; 21 | import java.util.Map; 22 | import java.util.Map.Entry; 23 | 24 | /** 25 | * Holds access tokens with an associated validity timestamp. The intention is to 26 | * minimize the number of calls to Cognito. Tokens should be added to the cache 27 | * on successful authentication or refresh. They will time out after 15 minutes, 28 | * at which point the servlet must authenticate again. 29 | *

30 | * To further minimize calls, a single cache should be injected into all servlets. 31 | *

32 | * Implementation notes: 33 | *

49 | */ 50 | public class CredentialsCache 51 | implements Serializable 52 | { 53 | private static final long serialVersionUID = 1L; 54 | 55 | private static final long DEFAULT_TIMEOUT = 15 * 60 * 1000L; 56 | 57 | private Map cache; 58 | 59 | 60 | /** 61 | * Creates a new cache, holding up to maxEntries entries. 62 | */ 63 | public CredentialsCache(final int maxEntries) 64 | { 65 | cache = Collections.synchronizedMap(new LinkedHashMap() 66 | { 67 | private static final long serialVersionUID = 1L; 68 | 69 | @Override 70 | protected boolean removeEldestEntry(Entry eldest) 71 | { 72 | return size() > maxEntries; 73 | } 74 | }); 75 | } 76 | 77 | 78 | /** 79 | * Adds an access token to the cache, with default (1 hour) timeout. 80 | */ 81 | public void addToken(String accessToken) 82 | { 83 | addToken(accessToken, DEFAULT_TIMEOUT); 84 | } 85 | 86 | 87 | /** 88 | * Adds an access token to the cache with specified timeout (in millis). 89 | * This should be called when an uncached token has been validated (which 90 | * would happen when the app restarts). 91 | */ 92 | public void addToken(String accessToken, long timeoutMillis) 93 | { 94 | cache.put(accessToken, new Date(System.currentTimeMillis() + timeoutMillis)); 95 | } 96 | 97 | /** 98 | * Checks the cache for the given access token, returning true if the token 99 | * exists and has not yet timed out. 100 | */ 101 | public boolean checkToken(String accessToken) 102 | { 103 | Date expirationDate = cache.get(accessToken); 104 | if (expirationDate == null) 105 | { 106 | return false; 107 | } 108 | else if (System.currentTimeMillis() > expirationDate.getTime()) 109 | { 110 | cache.remove(accessToken); 111 | return false; 112 | } 113 | else 114 | { 115 | return true; 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=DEBUG, default 2 | 3 | log4j.logger.org.apache=WARN 4 | log4j.logger.com.amazonaws=WARN 5 | log4j.logger.httpclient.wire.header=OFF 6 | log4j.logger.httpclient.wire.content=OFF 7 | 8 | log4j.appender.default=org.apache.log4j.ConsoleAppender 9 | log4j.appender.default.layout=org.apache.log4j.PatternLayout 10 | log4j.appender.default.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n 11 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | User Management with AWS Cognito 5 | 6 | 7 | cognito_pool_id 8 | us-east-1_rCQ6gAd1Q 9 | 10 | 11 | 12 | cognito_client_id 13 | 5co5s8e43krcdps2lrp4fo301i 14 | 15 | 16 | 17 | SignIn 18 | com.kdgregory.example.cognito.servlets.SignIn 19 | 20 | 21 | SignIn 22 | /signin 23 | 24 | 25 | 26 | SignUp 27 | com.kdgregory.example.cognito.servlets.SignUp 28 | 29 | 30 | SignUp 31 | /signup 32 | 33 | 34 | 35 | ConfirmSignUp 36 | com.kdgregory.example.cognito.servlets.ConfirmSignUp 37 | 38 | 39 | ConfirmSignUp 40 | /confirmsignup 41 | 42 | 43 | 44 | ValidatedAction 45 | com.kdgregory.example.cognito.servlets.ValidatedAction 46 | 47 | 48 | ValidatedAction 49 | /validatedaction 50 | 51 | 52 | 53 | signin.html 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/main/webapp/confirm-signup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Confirm Signup 5 | 6 | 7 | 8 |
9 | 10 |

11 | Please enter your email address, the temporary password that you received in the email, 12 | and a permanent password (twice). Then click Confirm. 13 |

14 | 15 | 16 | 18 | 20 | 22 | 24 | 25 | 26 |
27 |
28 | 29 | 30 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /src/main/webapp/css/common.css: -------------------------------------------------------------------------------- 1 | BODY { 2 | margin: 0; 3 | border: 0; 4 | padding: 0; 5 | font-family: Calibri, "Times New Roman", Times, serif; 6 | font-size: 14pt; 7 | color: #002564; background-color: #F8FFFF; 8 | } 9 | 10 | DIV.container { 11 | position: relative; 12 | width: 40%; 13 | left: 25%; 14 | padding: 1em; 15 | } 16 | 17 | TABLE.login TH { 18 | padding: 0.25em; 19 | text-align: left; 20 | } 21 | 22 | TABLE.login TD { 23 | padding: 0.25em; 24 | } 25 | 26 | P.actionDesc { 27 | margin-top: 4em; 28 | } 29 | 30 | INPUT { 31 | padding: 0.5em; 32 | } 33 | 34 | BUTTON { 35 | padding: 0.5em 4em 0.5em 4em; 36 | border-radius: 8px; 37 | font-size: large; 38 | font-weight: bold; 39 | } 40 | 41 | BUTTON.preferredButton { 42 | background-color: #60C060; 43 | } 44 | 45 | BUTTON.secondaryButton { 46 | background-color: #90A0D0; 47 | } 48 | -------------------------------------------------------------------------------- /src/main/webapp/signin.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Sign In 5 | 6 | 7 | 8 |
9 | 10 |

11 | If you already have an active account, enter your email address and 12 | password to sign in. 13 |

14 | 15 | 16 | 18 | 20 | 21 | 22 |
23 | 24 |

25 | If you don't already have an account, enter your email address here. You will 26 | receive an email with a temporary password within a few moments. 27 |

28 | 29 | 30 | 32 | 33 | 34 |
35 | 36 |
37 | 38 | 39 | 107 | 108 | 109 | -------------------------------------------------------------------------------- /src/main/webapp/validated-page.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Validated Page 5 | 6 | 7 | 8 | 9 |
10 | Checking your validation ... 11 |
12 | 13 | 14 | 15 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /src/scripts/cognito-create-userpool.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Creates a new user pool and client with minimal policies and attributes 4 | # (ie, use for authentication only, no authorization or profile tracking). 5 | # 6 | # cognite-create-userpool.sh POOL_NAME CLIENT_NAME 7 | # 8 | 9 | cat > /tmp/$$-pooldef.json < /tmp/$$-clientdef.json < /tmp/$$-pooldef-output.json 61 | 62 | USER_POOL_ID=`jq ".UserPool.Id" < /tmp/$$-pooldef-output.json | sed -e 's/"//g'` 63 | echo "User Pool ID: " $USER_POOL_ID 64 | 65 | aws cognito-idp create-user-pool-client --user-pool-id $USER_POOL_ID --client-name $2 --cli-input-json file:///tmp/$$-clientdef.json > /tmp/$$-clientdef-output.json 66 | 67 | echo "Client ID: " `jq ".UserPoolClient.ClientId" < /tmp/$$-clientdef-output.json | sed -e 's/"//g'` 68 | -------------------------------------------------------------------------------- /src/test/java/com/kdgregory/example/cognito/util/TestCredentialsCache.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) Keith D Gregory 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package com.kdgregory.example.cognito.util; 16 | 17 | import org.junit.Test; 18 | import static org.junit.Assert.*; 19 | 20 | public class TestCredentialsCache 21 | { 22 | @Test 23 | public void testBasicOperation() throws Exception 24 | { 25 | CredentialsCache cache = new CredentialsCache(10); 26 | cache.addToken("foo"); 27 | 28 | assertTrue("cached token was found", cache.checkToken("foo")); 29 | assertFalse("bogus token was not found", cache.checkToken("bar")); 30 | } 31 | 32 | 33 | @Test 34 | public void testLRU() throws Exception 35 | { 36 | CredentialsCache cache = new CredentialsCache(3); 37 | cache.addToken("foo"); 38 | cache.addToken("bar"); 39 | cache.addToken("baz"); 40 | cache.addToken("biff"); 41 | 42 | assertFalse("earliest token no loger in cache", cache.checkToken("foo")); 43 | assertTrue("later token (bar) is in cache", cache.checkToken("bar")); 44 | assertTrue("later token (baz) is in cache", cache.checkToken("baz")); 45 | assertTrue("later token (biff) is in cache", cache.checkToken("biff")); 46 | } 47 | 48 | 49 | @Test 50 | public void testTimeout() throws Exception 51 | { 52 | CredentialsCache cache = new CredentialsCache(3); 53 | cache.addToken("foo", -1); 54 | 55 | assertFalse("token no loger in cache", cache.checkToken("foo")); 56 | } 57 | } 58 | --------------------------------------------------------------------------------