Skip to content

Commit

Permalink
awspringgh-1246: sample for AWS Cognito Integration
Browse files Browse the repository at this point in the history
  • Loading branch information
Forfend committed Nov 14, 2024
1 parent 53feeb3 commit 8de3eec
Show file tree
Hide file tree
Showing 5 changed files with 128 additions and 7 deletions.
3 changes: 2 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@
<module>spring-cloud-aws-test</module>
<module>spring-cloud-aws-modulith</module>
<module>docs</module>
</modules>
<module>spring-cloud-aws-samples/spring-cloud-aws-cognito-sample</module>
</modules>

<dependencyManagement>
<dependencies>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package io.awspring.cloud.cognito;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.util.Assert;
Expand Down Expand Up @@ -76,8 +77,12 @@ public AdminCreateUserResponse createUser(String username, List<AttributeType> a

@Override
public ForgotPasswordResponse resetPassword(String username) {
ForgotPasswordRequest forgotPasswordRequest = ForgotPasswordRequest.builder().clientId(clientId)
.username(username).build();
ForgotPasswordRequest.Builder forgotPasswordRequestBuilder = ForgotPasswordRequest.builder().clientId(clientId)
.username(username);
if (this.clientSecret != null) {
forgotPasswordRequestBuilder.secretHash(CognitoUtils.calculateSecretHash(clientId, clientSecret, username));
}
ForgotPasswordRequest forgotPasswordRequest = forgotPasswordRequestBuilder.build();

return cognitoIdentityProviderClient.forgotPassword(forgotPasswordRequest);
}
Expand All @@ -94,7 +99,7 @@ public ConfirmForgotPasswordResponse confirmResetPassword(String username, Strin
@Override
public RespondToAuthChallengeResponse setPermanentPassword(String session, String username, String password) {
RespondToAuthChallengeRequest respondToAuthChallengeRequest = RespondToAuthChallengeRequest.builder()
.clientId(clientId).challengeName(ChallengeNameType.NEW_PASSWORD_REQUIRED)
.clientId(clientId).challengeName(ChallengeNameType.NEW_PASSWORD_REQUIRED).session(session)
.challengeResponses(Map.of(CognitoParameters.USERNAME_PARAM_NAME, username,
CognitoParameters.NEW_PASSWORD_PARAM_NAME, password, CognitoParameters.SECRET_HASH_PARAM_NAME,
CognitoUtils.calculateSecretHash(clientId, clientSecret, username)))
Expand All @@ -103,8 +108,13 @@ public RespondToAuthChallengeResponse setPermanentPassword(String session, Strin
}

private Map<String, String> resolveAuthParameters(String username, String password) {
return Map.of(CognitoParameters.USERNAME_PARAM_NAME, username, CognitoParameters.PASSWORD_PARAM_NAME, password,
CognitoParameters.SECRET_HASH_PARAM_NAME,
CognitoUtils.calculateSecretHash(clientId, clientSecret, username));
Map<String, String> parametersMap = new HashMap<>();
parametersMap.put(CognitoParameters.USERNAME_PARAM_NAME, username);
parametersMap.put(CognitoParameters.PASSWORD_PARAM_NAME, password);
if (this.clientSecret != null) {
parametersMap.put(CognitoParameters.SECRET_HASH_PARAM_NAME,
CognitoUtils.calculateSecretHash(clientId, clientSecret, username));
}
return parametersMap;
}
}
34 changes: 34 additions & 0 deletions spring-cloud-aws-samples/spring-cloud-aws-cognito-sample/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-aws-samples</artifactId>
<groupId>io.awspring.cloud</groupId>
<version>3.3.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-aws-cognito-sample</artifactId>
<name>Spring Cloud AWS Cognito Sample</name>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-starter-cognito</artifactId>
<version>3.3.0-SNAPSHOT</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* Copyright 2013-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.awspring.cloud;

import io.awspring.cloud.cognito.CognitoTemplate;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminInitiateAuthResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AttributeType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AuthenticationResultType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ChallengeNameType;

@SpringBootApplication
public class SpringCloudAwsCognitoExample {

private static final Logger LOGGER = LoggerFactory.getLogger(SpringCloudAwsCognitoExample.class);
private static final String USERNAME = "[email protected]";

public static void main(String[] args) {
SpringApplication.run(SpringCloudAwsCognitoExample.class, args);
}

@Bean
ApplicationRunner applicationRunner(CognitoTemplate cognitoTemplate) {
return args -> {

cognitoTemplate.createUser(USERNAME, getAttributes());
LOGGER.info("User created, check your email");
AdminInitiateAuthResponse authResponse = cognitoTemplate.login(USERNAME, "password");
if (ChallengeNameType.NEW_PASSWORD_REQUIRED.equals(authResponse.challengeName())) {
String session = authResponse.session();
cognitoTemplate.setPermanentPassword(session, USERNAME, "superSecurePassword");
}
// your Access Token, Id Token and Refresh Token are stored here
AuthenticationResultType authenticationResultType = authResponse.authenticationResult();
LOGGER.info("Authentication result: {}", authenticationResultType);

cognitoTemplate.resetPassword(USERNAME);
LOGGER.info("Check your email for password reset instructions");
cognitoTemplate.confirmResetPassword(USERNAME, "confirmationCode", "newSuperSecurePassword");
};
}

private List<AttributeType> getAttributes() {
return List.of(AttributeType.builder().name("email").value(USERNAME).build()
// and all other attributes here
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# LocalStack configuration
spring.cloud.aws.endpoint=http://localhost:4566
spring.cloud.aws.region.static=us-east-1
spring.cloud.aws.credentials.access-key=noop
spring.cloud.aws.credentials.secret-key=noop

spring.cloud.aws.cognito.user-pool-id=eu-central-1_UserPoolId
spring.cloud.aws.cognito.client-id=client-id
spring.cloud.aws.cognito.client-secret=client-secret

0 comments on commit 8de3eec

Please sign in to comment.