· 4 years ago · Nov 30, 2020, 12:56 PM
1private static void signup(String username, String password, String email) {
2 SignUpRequest signup = new SignUpRequest();
3 signup.setClientId("CLIENT_ID");
4 signup.setSecretHash(getSecretHash(username, "CLIENT_ID", "SECRET_HASH"));
5
6 signup.setUsername(username);
7 signup.setPassword(password);
8
9 List<AttributeType> attributeTypeList = new ArrayList<>();
10 attributeTypeList.add(new AttributeType().withName("email").withValue(email));
11 signup.setUserAttributes(attributeTypeList);
12
13 AWSCognitoIdentityProvider provider = AWSCognitoIdentityProviderClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
14 SignUpResult signUpResult = provider.signUp(signup);
15 System.out.println(signUpResult.toString());
16 }
17
18 public static void login(String username, String password) {
19 AdminInitiateAuthRequest authRequest = new AdminInitiateAuthRequest();
20 authRequest.setAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH);
21 authRequest.setClientId("CLIENT_ID");
22 authRequest.setUserPoolId("us-east-1_SvY58FCOV");
23
24 Map<String, String> authParamMap = new HashMap<>();
25 authParamMap.put("USERNAME", username);
26 authParamMap.put("PASSWORD", password);
27 authParamMap.put("SECRET_HASH", getSecretHash(username, "CLIENT_ID", "SECRET_HASH"));
28
29 BasicAWSCredentials awsCreds = new BasicAWSCredentials("ACCESS_KEY", "SECRET_KEY");
30 AWSCognitoIdentityProvider provider = AWSCognitoIdentityProviderClientBuilder.standard()
31 .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
32 .withRegion(Regions.US_EAST_1).build();
33 AdminInitiateAuthResult adminInitiateAuthResult = provider.adminInitiateAuth(authRequest);
34 }
35
36 public static String getSecretHash(String userId, String clientId, String clientSecret) {
37
38 if (userId == null) {
39 throw new IllegalArgumentException("User ID cannot be null.");
40 }
41
42 if (clientId == null) {
43 throw new IllegalArgumentException("Client ID cannot be null.");
44 }
45
46 if (clientSecret == null) {
47 return null;
48 }
49
50 SecretKeySpec signingKey = new SecretKeySpec(clientSecret.getBytes(StringUtils.UTF8), "HmacSHA256");
51
52 try {
53 Mac mac = Mac.getInstance("HmacSHA256");
54 mac.init(signingKey);
55 mac.update(userId.getBytes(StringUtils.UTF8));
56 byte[] rawHmac = mac.doFinal(clientId.getBytes(StringUtils.UTF8));
57 return new String(Base64.encode(rawHmac));
58 } catch (Exception e) {
59 throw new RuntimeException("Errors in HMAC calculation.");
60 }
61 }
62
63