use of com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler 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.handlers.AuthenticationHandler in project aws-sdk-android by aws-amplify.
the class AWSMobileClientTest method testRevokeTokenWithSignedOutUser.
@Test
public void testRevokeTokenWithSignedOutUser() throws Exception {
auth.signIn(username, PASSWORD, null);
assertTrue("isSignedIn is true", auth.isSignedIn());
final CountDownLatch revokeTokenLatch = new CountDownLatch(1);
final CognitoUser user = userPool.getCurrentUser();
user.getSession(new AuthenticationHandler() {
@Override
public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
revokeTokenLatch.countDown();
}
@Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
}
@Override
public void getMFACode(MultiFactorAuthenticationContinuation continuation) {
}
@Override
public void authenticationChallenge(ChallengeContinuation continuation) {
}
@Override
public void onFailure(Exception exception) {
exception.printStackTrace();
fail("Sign in failed.");
}
});
revokeTokenLatch.await(5, TimeUnit.SECONDS);
auth.signOut();
assertFalse("isSignedIn is false", auth.isSignedIn());
try {
user.revokeTokens();
} catch (Exception e) {
assertTrue(e instanceof InvalidParameterException);
}
}
use of com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler in project aws-sdk-android by aws-amplify.
the class AWSMobileClientAuthFlowSettingTest method setupMockUserPool.
private CognitoUserPool setupMockUserPool(AuthenticationContinuation mockContinuation) {
CognitoUserPool mockUserPool = mock(CognitoUserPool.class);
CognitoUser mockUser = mock(CognitoUser.class);
doAnswer(invocation -> {
int indexOfHandler = 1;
AuthenticationHandler handler = invocation.getArgument(indexOfHandler, AuthenticationHandler.class);
handler.getAuthenticationDetails(mockContinuation, "FAKE_USER_ID");
return null;
}).when(mockUser).getSession(any(), any());
when(mockUserPool.getUser(anyString())).thenReturn(mockUser);
return mockUserPool;
}
use of com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler in project aws-sdk-android by aws-amplify.
the class CognitoUser method getSessionInBackground.
/**
* getSession orchestrates the SignIn flow with Amazon Cognito UserPools.
*
* <p>
* This method is asynchronous and performs network operations
* on a background thread.
* </p>
*
* <p>
* 1) Read the tokens (Id, Access and Refresh) that are cached on the device.
* 1.1) If the Id and Access tokens are present and they are valid, the
* {@link AuthenticationHandler#onSuccess(CognitoUserSession, CognitoDevice)}.
* will be called with a {@link CognitoUserSession} that has references to the valid tokens.
* This means that the user is signed-in.
* 1.2) If the Id and Access tokens are expired, and if there is a valid refresh token,
* a network call is made to get new Id and Access tokens.
* If valid Id and Access tokens are retrieved, they are cached on the device
* and {@link AuthenticationHandler#onSuccess(CognitoUserSession, CognitoDevice)}
* will be called with a {@link CognitoUserSession} that has references to the valid
* tokens. This means that the user is signed-in.
*
* 2) If there are no valid tokens cached on the device, the callback method
* {@link AuthenticationHandler#getAuthenticationDetails(AuthenticationContinuation, String)}
* will be called where the {@link AuthenticationDetails} will need to be supplied
* to continue the SignIn operation. See
* {@link com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.CognitoIdentityProviderContinuation}
* for details on continuation objects.
*
* 3) In all other error scenarios, {@link AuthenticationHandler#onFailure(Exception)} will
* be called with the type and message of the exception and it is the responsibility of
* the caller to handle the exceptions appropriately.
* </p>
*
* @param callback REQUIRED: {@link AuthenticationHandler} callback
*/
public void getSessionInBackground(final AuthenticationHandler callback) {
if (callback == null) {
throw new CognitoParameterInvalidException("callback is null");
}
final CognitoUser cognitoUser = this;
new Thread(new Runnable() {
@Override
public void run() {
final Handler handler = new Handler(context.getMainLooper());
Runnable returnCallback;
try {
getCachedSession();
returnCallback = new Runnable() {
@Override
public void run() {
callback.onSuccess(cipSession, null);
}
};
} catch (final CognitoNotAuthorizedException e) {
returnCallback = new Runnable() {
@Override
public void run() {
final AuthenticationContinuation authenticationContinuation = new AuthenticationContinuation(cognitoUser, context, AuthenticationContinuation.RUN_IN_BACKGROUND, callback);
callback.getAuthenticationDetails(authenticationContinuation, cognitoUser.getUserId());
}
};
} catch (final Exception e) {
returnCallback = new Runnable() {
@Override
public void run() {
callback.onFailure(e);
}
};
}
handler.post(returnCallback);
}
}).start();
}
use of com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler in project aws-sdk-android by aws-amplify.
the class CognitoUser method initiateUserAuthentication.
/**
* Note: Please use {@link #getSession(Map, AuthenticationHandler)} or
* {@link #getSessionInBackground(AuthenticationHandler)} instead.
*
* Initiates user authentication through the generic auth flow (also called
* as Enhanced or Custom authentication). This is the first step in user
* authentication. The response to this step from the service will contain
* information about the next step in the authentication process.
*
* @param clientMetadata A map of custom key-value pairs that is passed to the lambda function for
* custom workflow.
* @param authenticationDetails REQUIRED: Contains details about the user
* authentication.
* @param runInBackground flag indicating if the operation has to run in
* background
* @param callback REQUIRED: {@link AuthenticationHandler} callback.
* @return {@link Runnable} for the next step in user authentication.
*/
public Runnable initiateUserAuthentication(final Map<String, String> clientMetadata, final AuthenticationDetails authenticationDetails, final AuthenticationHandler callback, final boolean runInBackground) {
final AuthenticationHandler internalCallback = new AuthenticationHandler() {
@Override
public void onSuccess(final CognitoUserSession userSession, final CognitoDevice newDevice) {
if (runInBackground) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
callback.onSuccess(userSession, newDevice);
}
});
} else {
callback.onSuccess(userSession, newDevice);
}
}
@Override
public void getAuthenticationDetails(final AuthenticationContinuation authenticationContinuation, final String userId) {
if (runInBackground) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
callback.getAuthenticationDetails(authenticationContinuation, userId);
}
});
} else {
callback.getAuthenticationDetails(authenticationContinuation, userId);
}
}
@Override
public void getMFACode(final MultiFactorAuthenticationContinuation continuation) {
if (runInBackground) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
callback.getMFACode(continuation);
}
});
} else {
callback.getMFACode(continuation);
}
}
@Override
public void authenticationChallenge(final ChallengeContinuation continuation) {
if (runInBackground) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
callback.authenticationChallenge(continuation);
}
});
} else {
callback.authenticationChallenge(continuation);
}
}
@Override
public void onFailure(final Exception exception) {
if (runInBackground) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
callback.onFailure(exception);
}
});
} else {
callback.onFailure(exception);
}
}
};
final Runnable task = _initiateUserAuthentication(clientMetadata, authenticationDetails, internalCallback, runInBackground);
if (runInBackground) {
return new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
task.run();
}
}).start();
}
};
} else {
return task;
}
}
Aggregations