use of com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationDetails in project aws-sdk-android by aws-amplify.
the class OAuth2Utils method _signIn.
private Runnable _signIn(final String username, final String password, final Map<String, String> validationData, final Map<String, String> clientMetadata, final AuthFlowType authFlowType, final Callback<SignInResult> callback) {
this.signInCallback = callback;
signInState = null;
mStore.set(SIGN_IN_MODE, SignInMode.SIGN_IN.toString());
return new Runnable() {
@Override
public void run() {
try {
userpool.getUser(username).getSession(clientMetadata, new AuthenticationHandler() {
@Override
public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
try {
mCognitoUserSession = userSession;
signInState = SignInState.DONE;
} catch (Exception e) {
signInCallback.onError(e);
signInCallback = null;
}
try {
if (isFederationEnabled()) {
federatedSignInWithoutAssigningState(userpoolsLoginKey, mCognitoUserSession.getIdToken().getJWTToken());
}
releaseSignInWait();
} catch (Exception e) {
Log.w(TAG, "Failed to federate tokens during sign-in", e);
} finally {
setUserState(new UserStateDetails(UserState.SIGNED_IN, getSignInDetailsMap()));
}
signInCallback.onResult(SignInResult.DONE);
}
@Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
Log.d(TAG, "Sending password.");
final HashMap<String, String> authParameters = new HashMap<>();
// Check if the auth flow type setting is in the configuration.
boolean authFlowTypeInConfig = awsConfiguration.optJsonObject(AUTH_KEY) != null && awsConfiguration.optJsonObject(AUTH_KEY).has("authenticationFlowType");
try {
String resolvedAuthFlowType = authFlowType != null ? authFlowType.name() : null;
if (resolvedAuthFlowType == null && authFlowTypeInConfig) {
resolvedAuthFlowType = awsConfiguration.optJsonObject(AUTH_KEY).getString("authenticationFlowType");
}
if (resolvedAuthFlowType != null && AUTH_TYPE_INIT_CUSTOM_AUTH.equals(resolvedAuthFlowType)) {
// use one of the below constructors depending on what's passed in.
if (password != null) {
authenticationContinuation.setAuthenticationDetails(new AuthenticationDetails(username, password, authParameters, validationData));
} else {
authenticationContinuation.setAuthenticationDetails(new AuthenticationDetails(username, authParameters, validationData));
}
} else if (resolvedAuthFlowType != null && AUTH_TYPE_INIT_USER_PASSWORD.equals(resolvedAuthFlowType)) {
// If there's a value in the config and it's USER_PASSWORD_AUTH, set the auth type (challenge name)
// to be USER_PASSWORD.
AuthenticationDetails authenticationDetails = new AuthenticationDetails(username, password, validationData);
authenticationDetails.setAuthenticationType(CHLG_TYPE_USER_PASSWORD);
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
} else {
// Otherwise, auth flow is USER_SRP_AUTH and the auth type (challenge name)
// will default to PASSWORD_VERIFIER.
Log.d(TAG, "Using USER_SRP_AUTH for flow type.");
authenticationContinuation.setAuthenticationDetails(new AuthenticationDetails(username, password, validationData));
}
} catch (JSONException exception) {
Log.w(TAG, "Exception while attempting to read authenticationFlowType from config.", exception);
}
authenticationContinuation.continueTask();
}
@Override
public void getMFACode(MultiFactorAuthenticationContinuation continuation) {
signInMfaContinuation = continuation;
CognitoUserCodeDeliveryDetails parameters = continuation.getParameters();
signInState = SignInState.SMS_MFA;
signInCallback.onResult(new SignInResult(SignInState.SMS_MFA, new UserCodeDeliveryDetails(parameters.getDestination(), parameters.getDeliveryMedium(), parameters.getAttributeName())));
}
@Override
public void authenticationChallenge(ChallengeContinuation continuation) {
try {
signInState = SignInState.valueOf(continuation.getChallengeName());
signInChallengeContinuation = continuation;
signInCallback.onResult(new SignInResult(signInState, continuation.getParameters()));
} catch (IllegalArgumentException e) {
signInCallback.onError(e);
}
}
@Override
public void onFailure(Exception exception) {
signInCallback.onError(exception);
}
});
} catch (Exception e) {
callback.onError(e);
}
}
};
}
use of com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationDetails in project aws-sdk-android by aws-amplify.
the class AWSMobileClientAuthFlowSettingTest method verifyScenario.
/**
* Verify that the correct auth type (aka challenge name) is passed in based on the
* auth flow type from the config file.
* @param configAuthFlowType The auth flow type from the config.
* @param expectedAuthType The auth type expected.
* @param overridenAuthFlowType The authType passed to the API
* @throws JSONException Not expected.
* @throws InterruptedException Not expected.
*/
private void verifyScenario(String configAuthFlowType, String overridenAuthFlowType, String expectedAuthType) throws JSONException, InterruptedException {
AuthenticationContinuation mockContinuation = setupMockContinuation();
CognitoUserPool mockUserPool = setupMockUserPool(mockContinuation);
initMobileClientAndWait(configAuthFlowType, mockUserPool);
signinAndWait(overridenAuthFlowType);
ArgumentCaptor<AuthenticationDetails> argumentCaptor = ArgumentCaptor.forClass(AuthenticationDetails.class);
verify(mockContinuation).setAuthenticationDetails(argumentCaptor.capture());
AuthenticationDetails actualAuthDetails = argumentCaptor.getValue();
assertEquals(expectedAuthType, actualAuthDetails.getAuthenticationType());
}
use of com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationDetails in project aws-sdk-android by aws-amplify.
the class CognitoUserIntegrationTest method testCustomAuth.
@Test
public void testCustomAuth() {
final CountDownLatch signInLatch = new CountDownLatch(1);
final ArrayList<CognitoUserSession> userSessions = new ArrayList();
AuthenticationHandler authenticationHandler = new AuthenticationHandler() {
@Override
public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
userSessions.add(userSession);
signInLatch.countDown();
}
@Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
final HashMap<String, String> authParameters = new HashMap<>();
// This is a passwordless flow, hance passing a dummy password.
AuthenticationDetails authenticationDetails = new AuthenticationDetails(customAuthUsername, "", authParameters, null);
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
authenticationContinuation.continueTask();
}
@Override
public void getMFACode(MultiFactorAuthenticationContinuation continuation) {
fail("Tests are not configured to work with MFA. " + "Either create a CognitoUserPool without MFA or update the test.");
signInLatch.countDown();
}
@Override
public void authenticationChallenge(ChallengeContinuation continuation) {
Log.d(TAG, "Yo, Authentication Chanllenge is called Passwordless");
continuation.setChallengeResponse(CognitoServiceConstants.CHLG_RESP_ANSWER, "1133");
continuation.continueTask();
}
@Override
public void onFailure(Exception exception) {
fail("Error while signing-in. " + exception.getLocalizedMessage());
signInLatch.countDown();
}
};
cognitoUserPool.getUser(customAuthUsername).getSessionInBackground(authenticationHandler);
try {
signInLatch.await(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
assertEquals(1, userSessions.size());
// Verify that the sign-in was successful
verifyCognitoUserSessionForSignedInUser(userSessions.get(0));
}
use of com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationDetails in project aws-sdk-android by aws-amplify.
the class CognitoIdentityProviderSignInUserTest method getSessionInCurrentThreadNoCachedTokensNoMFA.
// Authenticate user with user password verifier in current thread
@Ignore
@Test
public void getSessionInCurrentThreadNoCachedTokensNoMFA() throws Exception {
assertNotNull(testUser.getUserId());
// Test with a user cached in shared preferences, with no cached tokens
awsKeyValueStorageUtility.put("CognitoIdentityProvider." + TEST_CLIENT_ID + ".LastAuthUser", TEST_USER_NAME);
// Set mock returns for Authentication API Calls
// API call to start forgot-password flow
doReturn(TEST_VALID_INITIATE_USER_SRP_AUTH_RESPONSE).when(mockCSIClient).initiateAuth(any(InitiateAuthRequest.class));
// Tracker to validate the callback sequence -> callback.getAuthenticationDetails() -> onSuccess()
final FlowTracker tracker = new FlowTracker("getAuthenticationDetails");
System.out.println("Get session");
testUser.getSession(new AuthenticationHandler() {
@Override
public void onSuccess(CognitoUserSession session, CognitoDevice device) {
// Check if this method was called out of sequence
assertTrue(tracker.check("onSuccess"));
// Extract the arguments passed to the initiateAuth API call
ArgumentCaptor<InitiateAuthRequest> argumentCaptor = ArgumentCaptor.forClass(InitiateAuthRequest.class);
verify(mockCSIClient).initiateAuth(argumentCaptor.capture());
InitiateAuthRequest requestSent = argumentCaptor.getValue();
// Verify the arguments passed in the API call
assertNotNull(requestSent);
assertEquals(TEST_CLIENT_ID, requestSent.getClientId());
assertEquals("USER_SRP_AUTH", requestSent.getAuthFlow());
// Check authentication parameters
assertNotNull(requestSent.getAuthParameters());
assertNotNull(requestSent.getAuthParameters().get("SRP_A"));
assertNotNull(requestSent.getAuthParameters().get("SECRET_HASH"));
assertNotNull(requestSent.getAuthParameters().get("USERNAME"));
assertNotNull(requestSent.getAuthParameters().get("SRP_A"));
// Check Validation parameters, input to Lambda Triggers
assertNotNull(requestSent.getClientMetadata());
assertEquals(2, requestSent.getClientMetadata().size());
// Extract the arguments passed to the RespondToAuthChallenge API call
ArgumentCaptor<RespondToAuthChallengeRequest> argumentCaptorA = ArgumentCaptor.forClass(RespondToAuthChallengeRequest.class);
verify(mockCSIClient).respondToAuthChallenge(argumentCaptorA.capture());
RespondToAuthChallengeRequest requestSentA = argumentCaptorA.getValue();
// Verify the arguments passed in the API call
assertNotNull(requestSentA);
assertEquals(TEST_CLIENT_ID, requestSentA.getClientId());
assertEquals("PASSWORD_VERIFIER", requestSentA.getChallengeName());
assertNotNull(requestSentA.getSession());
assertNotNull(requestSentA.getChallengeResponses());
// Verify if we have a valid session
assertNotNull(session);
assertTrue(session.isValid());
// Verify that the device is null
assertNull(device);
tracker.setNext("end");
}
@Override
public void getAuthenticationDetails(AuthenticationContinuation continuation, String username) {
// Check if this method was called out of sequence
assertTrue(tracker.check("getAuthenticationDetails"));
// Check parameters
assertNotNull(continuation);
assertNotNull(continuation.getParameters());
// Continue with authentication details
Map<String, String> TEST_IN_VALIDATION_DATA = new HashMap<String, String>();
TEST_IN_VALIDATION_DATA.put("DummyAttribute_1", "Value4DummyAttribute_1");
TEST_IN_VALIDATION_DATA.put("DummyAttribute_2", "Value4DummyAttribute_2");
AuthenticationDetails authDetails = new AuthenticationDetails(TEST_USER_NAME, TEST_USER_PASSWORD, TEST_IN_VALIDATION_DATA);
tracker.setNext("onSuccess");
continuation.setAuthenticationDetails(authDetails);
// Set challenge response for valid
doReturn(TEST_VALID_INITIATE_USER_SRP_AUTH_RESPONSE).when(mockCSIClient).initiateAuth(any(InitiateAuthRequest.class));
doReturn(TEST_VALID_SUCCESSFUL_AUTH_RESPONSE).when(mockCSIClient).respondToAuthChallenge(any(RespondToAuthChallengeRequest.class));
continuation.continueTask();
}
@Override
public void getMFACode(MultiFactorAuthenticationContinuation continuation) {
// Check if this method was called out of sequence
assertTrue(tracker.check("getMFACode"));
}
@Override
public void onFailure(Exception exception) {
// Check if this method was called out of sequence
assertTrue(tracker.check("onFailure"));
}
@Override
public void authenticationChallenge(ChallengeContinuation continuation) {
// Check if this method was called out of sequence
assertTrue(tracker.check("authenticationChallenge"));
}
});
}
use of com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationDetails in project aws-sdk-android by aws-amplify.
the class CognitoIdentityProviderSignInUserTest method getSessionInBackgroundThreadNoCachedTokensNoMFA.
// Authenticate user with user password verifier in background thread
// Failing due to Mockito error
@Ignore
@Test
public void getSessionInBackgroundThreadNoCachedTokensNoMFA() throws Exception {
assertNotNull(testUser.getUserId());
// Test with a user cached in shared preferences, with no cached tokens
awsKeyValueStorageUtility.put("CognitoIdentityProvider." + TEST_CLIENT_ID + ".LastAuthUser", TEST_USER_NAME);
// Set mock returns for Authentication API Calls
// API call to start forgot-password flow
doReturn(TEST_VALID_INITIATE_USER_SRP_AUTH_RESPONSE).when(mockCSIClient).initiateAuth(any(InitiateAuthRequest.class));
// Tracker to validate the callback sequence -> callback.getAuthenticationDetails() -> onSuccess()
final FlowTracker tracker = new FlowTracker("getAuthenticationDetails");
System.out.println("Get session");
testUser.getSessionInBackground(new AuthenticationHandler() {
@Override
public void onSuccess(CognitoUserSession session, CognitoDevice device) {
// Check if this method was called out of sequence
assertTrue(tracker.check("onSuccess"));
// Extract the arguments passed to the initiateAuth API call
ArgumentCaptor<InitiateAuthRequest> argumentCaptor = ArgumentCaptor.forClass(InitiateAuthRequest.class);
verify(mockCSIClient).initiateAuth(argumentCaptor.capture());
InitiateAuthRequest requestSent = argumentCaptor.getValue();
// Verify the arguments passed in the API call
assertNotNull(requestSent);
assertEquals(TEST_CLIENT_ID, requestSent.getClientId());
assertEquals("USER_SRP_AUTH", requestSent.getAuthFlow());
// Check authentication parameters
assertNotNull(requestSent.getAuthParameters());
assertNotNull(requestSent.getAuthParameters().get("SRP_A"));
assertNotNull(requestSent.getAuthParameters().get("SECRET_HASH"));
assertNotNull(requestSent.getAuthParameters().get("USERNAME"));
assertNotNull(requestSent.getAuthParameters().get("SRP_A"));
// Check Validation parameters, input to Lambda Triggers
assertNotNull(requestSent.getClientMetadata());
assertEquals(2, requestSent.getClientMetadata().size());
// Extract the arguments passed to the RespondToAuthChallenge API call
ArgumentCaptor<RespondToAuthChallengeRequest> argumentCaptorA = ArgumentCaptor.forClass(RespondToAuthChallengeRequest.class);
verify(mockCSIClient).respondToAuthChallenge(argumentCaptorA.capture());
RespondToAuthChallengeRequest requestSentA = argumentCaptorA.getValue();
// Verify the arguments passed in the API call
assertNotNull(requestSentA);
assertEquals(TEST_CLIENT_ID, requestSentA.getClientId());
assertEquals("PASSWORD_VERIFIER", requestSentA.getChallengeName());
assertNotNull(requestSentA.getSession());
assertNotNull(requestSentA.getChallengeResponses());
// Verify if we have a valid session
assertNotNull(session);
assertTrue(session.isValid());
// Verify that the device is null
assertNull(device);
tracker.setNext("end");
}
@Override
public void getAuthenticationDetails(AuthenticationContinuation continuation, String username) {
// Check if this method was called out of sequence
assertTrue(tracker.check("getAuthenticationDetails"));
// Check parameters
assertNotNull(continuation);
assertNotNull(continuation.getParameters());
// Continue with authentication details
Map<String, String> TEST_IN_VALIDATION_DATA = new HashMap<String, String>();
TEST_IN_VALIDATION_DATA.put("DummyAttribute_1", "Value4DummyAttribute_1");
TEST_IN_VALIDATION_DATA.put("DummyAttribute_2", "Value4DummyAttribute_2");
AuthenticationDetails authDetails = new AuthenticationDetails(TEST_USER_NAME, TEST_USER_PASSWORD, TEST_IN_VALIDATION_DATA);
tracker.setNext("onSuccess");
continuation.setAuthenticationDetails(authDetails);
// Set challenge response for valid
doReturn(TEST_VALID_INITIATE_USER_SRP_AUTH_RESPONSE).when(mockCSIClient).initiateAuth(any(InitiateAuthRequest.class));
doReturn(TEST_VALID_SUCCESSFUL_AUTH_RESPONSE).when(mockCSIClient).respondToAuthChallenge(any(RespondToAuthChallengeRequest.class));
continuation.continueTask();
}
@Override
public void getMFACode(MultiFactorAuthenticationContinuation continuation) {
// Check if this method was called out of sequence
assertTrue(tracker.check("getMFACode"));
}
@Override
public void onFailure(Exception exception) {
// Check if this method was called out of sequence
assertTrue(tracker.check("onFailure"));
}
@Override
public void authenticationChallenge(ChallengeContinuation continuation) {
// Check if this method was called out of sequence
assertTrue(tracker.check("authenticationChallenge"));
}
});
}
Aggregations