tskippe
tskippe

Reputation: 165

Amazon Cognito log users in with username and password

Is this possible with AWS Cognito? Also i would like to add a "relationship" between users and entities in DynamoDB.

Anyone been in this scenario - or am i using the wrong services from AWS?

Upvotes: 2

Views: 2875

Answers (2)

Mark Woon
Mark Woon

Reputation: 2196

If anyone should need actual code for the Java SDK, here's an example of authenticating on the back-end:

Map<String, String> params = new HashMap<>();
params.put("USERNAME", userId);
params.put("SECRET_HASH", calculateSecretHash(userId));
params.put("PASSWORD", rawPassword);

AdminInitiateAuthRequest request = new AdminInitiateAuthRequest()
    .withUserPoolId("YOUR_USER_POOL_ID")
    .withClientId("YOUR_USER_POOL_APP_CLIENT_ID")
    .withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH)
    .withAuthParameters(params);

AWSCognitoIdentityProvider identityProvider = AWSCognitoIdentityProviderClientBuilder.standard()
        .withCredentials(credentialsProvider)
        .withRegion(Regions.US_WEST_2)
        .build();
AdminInitiateAuthResult result = identityProvider.adminInitiateAuth(request);

Helper function:

private String calculateSecretHash(@Nonnull String userName) {

  SecretKeySpec signingKey = new SecretKeySpec(m_clientSecret.getBytes(StandardCharsets.UTF_8), HmacAlgorithms.HMAC_SHA_256.toString());
  try {
    Mac mac = Mac.getInstance(HmacAlgorithms.HMAC_SHA_256.toString());
    mac.init(signingKey);
    mac.update(userName.getBytes(StandardCharsets.UTF_8));
    byte[] rawHmac = mac.doFinal(m_clientId.getBytes(StandardCharsets.UTF_8));
    return Base64.encodeBase64String(rawHmac);

  } catch (Exception ex) {
    throw new PgkbRuntimeException("Error calculating secret hash", ex);
  }
}

Upvotes: 6

Jeff Bailey
Jeff Bailey

Reputation: 5775

For anyone else who finds this question, this is now possible with Cognito User Pools. More information is available here.

Upvotes: 3

Related Questions