8

I've created a Cognito User Pool. I can list the users and add the users using the AWSCognitoIdentityProviderClient from the Java AWS SDK.

However, I have a custom login page and I wish to take the entered username and password and authenticate against my User Pool. I don't see anywhere in the Java AWS SDK where I can pass credentials and get an authentication result from.

Edit: I can't get past this error:

NotAuthorizedException: Missing credentials in config

Relevant code:

    AWS.config.region = 'us-east-1';
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: 'us-east-1:087a3210-64f8-4dae-9e3c...' // your identity pool id here
    });

    AWSCognito.config.region = 'us-east-1';
    AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: 'us-east-1:087a3210-64f8-4dae-9e3c...' // your identity pool id here
    });

    var poolData = {
        UserPoolId: 'us-east-1_39RP...',
        ClientId: 'ttsj9j5...',
        ClientSecret: 'bkvkj9r8kl2ujrlu41c7krsb6r7nub2kb260gj3mgi...'
    };
    var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);

    var authenticationData = {
        Username: '[email protected]',
        Password: 'foobarfoo',
    };
    var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
    var userData = {
        Username: '[email protected]',
        Pool: userPool
    };
    var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function (result) {
            console.log('access token + ' + result.getAccessToken().getJwtToken());
        },

        onFailure: function (err) {
            alert(err);
        },

    });
1
  • 1
    looks like you're using javascript - this is not java.
    – ecoe
    Mar 3, 2018 at 16:19

3 Answers 3

14

The AWS Java SDK includes APIs to authenticate users in a User Pool. You can authenticate a user using either the InitiateAuth api or AdminInitiateAuth api of the AWSCognitoIdentityProviderClient class. The difference between these two API is explained in the documentation. In short, for InitiateAuth, you need to perform SRP calculations and then pass it to the API, while in AdminInitiateAuth you can directly pass the username and password. You can read about the security implications in both cases and decide which one to use.

Documentation : https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html

API reference: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html

https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html

My working sample(Groovy):

def login() {
    AWSCognitoIdentityProviderClient client = new AWSCognitoIdentityProviderClient()
    println("Provider client: " + client)
    client.setRegion(Region.getRegion(Regions.AP_NORTHEAST_1))

    HashMap authParams = new HashMap<>()
    authParams.put("USERNAME", "User1")
    authParams.put("PASSWORD", "a*123")
    AdminInitiateAuthRequest adminInitiateAuthRequest = new AdminInitiateAuthRequest()
            .withClientId(<YOUR_CLIENT_ID>)
            .withUserPoolId(<YOUR_USER_POOL_ID>)
            .withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH )
            .withAuthParameters(authParams)
    AdminInitiateAuthResult result = client.adminInitiateAuth(adminInitiateAuthRequest);
    if (result != null) {
        System.out.println("AdminInitiateAuthResult:");
        System.out.println(result.toString());
    } else {
        System.out.println("No result available");
        return;
    }
}
3
  • This was helpful, how do you then get the user data once you have the AdminInitiateAuthResult ?
    – gremwell
    May 10, 2017 at 7:31
  • Ah, worked it out, GetUserRequest getUserRequest = new GetUserRequest().withAccessToken(initiateAuthResult.getAuthenticationResult().getAccessToken()); GetUserResult getUserResult = client.getUser(getUserRequest);
    – gremwell
    May 10, 2017 at 7:42
  • 2
    however, adminInitiateAuth requires AWS credentials, so this approach would only work for users that have that privileged information.
    – ecoe
    Mar 3, 2018 at 17:20
3

Authentication is only supported via JavaScript, iOS and Android at this time. The necessary apis to authenticate are not part of the server SDKs (java, python et. all) during the beta. Using the JavaScript SDK is the recommended way of authenticating from your login page.

4
  • I must be so close, followed all the instructions for JavaScript, and now I'm stuck at: "ConfigError: Missing credentials in config", following Use case 4: Apr 25, 2016 at 21:35
  • This is an artifact of how the JavaScript SDK is generated. Our JavaScript SDK assumes that all AWS services require credentials, but some have unauthenticated apis and don't require them. If you put some arbitrary values, like ACCESS_KEY and SECRET_KEY for your credentials it should work.
    – perpil
    Apr 26, 2016 at 17:30
  • Got it working, I finally re-read the instructions and created an app without checking the generate client secret box Apr 29, 2016 at 20:36
  • 1
    The JavaScript SDK seems to be impossible to use from AWS Lambda. Not only that, but while the OP might have said "Java SDK," they are clearly using the JavaScript SDK already.
    – TiggerToo
    May 23, 2016 at 18:01
2

check here https://github.com/aws/amazon-cognito-identity-js

there is a missing line of code

This page http://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-javascript-examples.html is not updated

// Need to provide placeholder keys unless unauthorised user access is enabled for user pool
AWSCognito.config.update({accessKeyId: 'anything', secretAccessKey: 'anything'})

After including this I stopped having this error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.