use of com.amazonaws.mobileconnectors.cognitoauth.handlers.AuthHandler in project aws-sdk-android by aws-amplify.
the class OAuth2Utils method _showSignInHostedUI.
private Runnable _showSignInHostedUI(final Activity callingActivity, final SignInUIOptions signInUIOptions, final Callback<UserStateDetails> callback) {
return new Runnable() {
@Override
public void run() {
final HostedUIOptions hostedUIOptions = signInUIOptions.getHostedUIOptions();
// Reset settings to JSON
JSONObject hostedUIJSON = null;
try {
hostedUIJSON = new JSONObject(getHostedUIJSONFromJSON().toString());
} catch (JSONException e) {
callback.onError(new Exception("Could not create OAuth configuration object", e));
}
if (hostedUIOptions.getFederationEnabled() != null) {
mStore.set(FEDERATION_ENABLED_KEY, hostedUIOptions.getFederationEnabled() ? "true" : "false");
} else {
mStore.set(FEDERATION_ENABLED_KEY, "true");
}
if (hostedUIOptions.getSignOutQueryParameters() != null) {
try {
JSONObject signOutParams = new JSONObject();
for (Map.Entry<String, String> e : hostedUIOptions.getSignOutQueryParameters().entrySet()) {
signOutParams.put(e.getKey(), e.getValue());
}
hostedUIJSON.put("SignOutQueryParameters", signOutParams);
} catch (JSONException e1) {
callback.onError(new Exception("Failed to construct sign-out query parameters", e1));
return;
}
}
if (hostedUIOptions.getTokenQueryParameters() != null) {
try {
JSONObject tokenParams = new JSONObject();
for (Map.Entry<String, String> e : hostedUIOptions.getTokenQueryParameters().entrySet()) {
tokenParams.put(e.getKey(), e.getValue());
}
hostedUIJSON.put("TokenQueryParameters", tokenParams);
} catch (JSONException e1) {
callback.onError(new Exception("Failed to construct token query parameters", e1));
return;
}
}
mStore.set(HOSTED_UI_KEY, hostedUIJSON.toString());
final HashSet<String> scopes;
if (hostedUIOptions.getScopes() != null) {
scopes = new HashSet<String>();
Collections.addAll(scopes, hostedUIOptions.getScopes());
} else {
scopes = null;
}
final String identityProvider = hostedUIOptions.getIdentityProvider();
final String idpIdentifier = hostedUIOptions.getIdpIdentifier();
mStore.set(SIGN_IN_MODE, SignInMode.HOSTED_UI.toString());
Auth.Builder hostedUIBuilder = null;
try {
hostedUIBuilder = getHostedUI(hostedUIJSON);
} catch (JSONException e) {
throw new RuntimeException("Failed to construct HostedUI from awsconfiguration.json", e);
}
hostedUIBuilder.setPersistenceEnabled(mIsPersistenceEnabled).setAuthHandler(new AuthHandler() {
boolean hasSucceededOnce = false;
@Override
public void onSuccess(AuthUserSession session) {
Log.d(TAG, "onSuccess: HostedUI signed-in");
hasSucceededOnce = true;
if (isFederationEnabled()) {
federatedSignInWithoutAssigningState(userpoolsLoginKey, session.getIdToken().getJWTToken(), new Callback<UserStateDetails>() {
@Override
public void onResult(UserStateDetails result) {
Log.d(TAG, "onResult: Federation from the Hosted UI " + "succeeded");
}
@Override
public void onError(Exception e) {
Log.e(TAG, "onError: Federation from the Hosted UI " + "failed", e);
}
});
}
new Thread(new Runnable() {
@Override
public void run() {
final UserStateDetails userStateDetails = getUserStateDetails(false);
callback.onResult(userStateDetails);
setUserState(userStateDetails);
}
}).start();
}
@Override
public void onSignout() {
Log.d(TAG, "onSignout: HostedUI signed-out");
}
@Override
public void onFailure(final Exception e) {
if (hasSucceededOnce) {
Log.d(TAG, "onFailure: Ignoring failure because HostedUI " + "has signaled success at least once.");
return;
}
new Thread(new Runnable() {
@Override
public void run() {
callback.onError(e);
}
}).start();
}
});
if (scopes != null) {
hostedUIBuilder.setScopes(scopes);
}
if (identityProvider != null) {
hostedUIBuilder.setIdentityProvider(identityProvider);
}
if (idpIdentifier != null) {
hostedUIBuilder.setIdpIdentifier(idpIdentifier);
}
hostedUI = hostedUIBuilder.build();
if (signInUIOptions.getBrowserPackage() != null) {
hostedUI.setBrowserPackage(signInUIOptions.getBrowserPackage());
}
hostedUI.getSession(callingActivity);
}
};
}
use of com.amazonaws.mobileconnectors.cognitoauth.handlers.AuthHandler in project aws-sdk-android by aws-amplify.
the class AuthClient method getTokens.
/**
* Internal method to exchange code for tokens.
* <p>
* Checks if the Uri contains a <b>state</b> query parameter. The FQDN for Cognito UI
* Web-Page contains a state. This method considers Uri's without a state parameter as
* <b><logout</b> redirect.
* Checks if the value of the contained state variable is valid. This is necessary to ensure
* that the SDK is parsing response from a known source. The SDK reads cache for proof-key
* stored with the value of the state in the Uri. If a stored proof-key is found, the Uri
* contains response from a request it generated.
* Checks if the Uri contains an error query parameter. An error query parameter indicates
* that the last request failed. This method invokes
* {@link AuthHandler#onFailure(Exception)} callback to report failure.
* When the above tests succeed, this method makes an http call to Amazon Cognito token
* end-point to exchange code for tokens.
* </p>
* @param uri Required: The redirect uri from the service.
* @param callback Required: {@link AuthHandler}.
*/
private void getTokens(final Uri uri, final AuthHandler callback) {
new Thread(new Runnable() {
final Handler handler = new Handler(context.getMainLooper());
Runnable returnCallback = new Runnable() {
@Override
public void run() {
callback.onFailure(new InvalidParameterException());
}
};
@Override
public void run() {
final Uri fqdn = new Uri.Builder().scheme(ClientConstants.DOMAIN_SCHEME).authority(pool.getAppWebDomain()).appendPath(ClientConstants.DOMAIN_PATH_OAUTH2).appendPath(ClientConstants.DOMAIN_PATH_TOKEN_ENDPOINT).build();
String callbackState = uri.getQueryParameter(ClientConstants.DOMAIN_QUERY_PARAM_STATE);
if (callbackState != null) {
Set<String> tokenScopes = LocalDataManager.getCachedScopes(pool.awsKeyValueStore, context, callbackState);
String proofKeyPlain = LocalDataManager.getCachedProofKey(pool.awsKeyValueStore, context, callbackState);
if (proofKeyPlain == null) {
// The state value is unknown, exit.
return;
}
final String errorText = uri.getQueryParameter(ClientConstants.DOMAIN_QUERY_PARAM_ERROR);
if (errorText != null) {
returnCallback = new Runnable() {
@Override
public void run() {
callback.onFailure(new AuthServiceException(errorText));
}
};
} else {
// Make http POST call
final AuthHttpClient httpClient = new AuthHttpClient();
Map<String, String> httpHeaderParams = getHttpHeader();
Map<String, String> httpBodyParams = generateTokenExchangeRequest(uri, proofKeyPlain);
try {
String response = httpClient.httpPost(new URL(fqdn.toString()), httpHeaderParams, httpBodyParams);
final AuthUserSession session = AuthHttpResponseParser.parseHttpResponse(response);
userId = session.getUsername();
// Cache tokens if successful
LocalDataManager.cacheSession(pool.awsKeyValueStore, context, pool.getAppId(), userId, session, tokenScopes);
// Return tokens
returnCallback = new Runnable() {
@Override
public void run() {
callback.onSuccess(session);
}
};
} catch (final Exception e) {
returnCallback = new Runnable() {
@Override
public void run() {
callback.onFailure(e);
}
};
}
}
} else {
if (cookiesCleared != null) {
cookiesCleared.countDown();
Log.d(TAG, "Sign-out was successful.");
}
// User sign-out.
returnCallback = new Runnable() {
@Override
public void run() {
callback.onSignout();
}
};
}
handler.post(returnCallback);
}
}).start();
}
use of com.amazonaws.mobileconnectors.cognitoauth.handlers.AuthHandler in project aws-sdk-android by aws-amplify.
the class AuthClient method refreshSession.
/**
* Internal method to refresh tokens.
* <p>
* Makes an http call to Amazon Cognito token end-point to refresh token. On successful
* token refresh, the refresh tokens is retained.
* </p>
* @param session Required: The android application {@link Context}.
* @param redirectUri Required: The redirect Uri, which will be launched after authentication.
* @param tokenScopes Required: A {@link Set<String>} specifying all scopes for the tokens.
* @param callback Required: {@link AuthHandler}.
* @param showSignInIfExpired true if the web UI should launch when the refresh token is expired
* @param browserPackage String specifying the browser package to launch the specified url.
* @param activity The activity to launch the sign in experience from.
* This must not be null if showSignInIfExpired is true.
*/
private void refreshSession(final AuthUserSession session, final String redirectUri, final Set<String> tokenScopes, final AuthHandler callback, final boolean showSignInIfExpired, final String browserPackage, final Activity activity) {
new Thread(new Runnable() {
final Handler handler = new Handler(context.getMainLooper());
Runnable returnCallback;
@Override
public void run() {
final Uri fqdn = new Uri.Builder().scheme(ClientConstants.DOMAIN_SCHEME).authority(pool.getAppWebDomain()).appendPath(ClientConstants.DOMAIN_PATH_OAUTH2).appendPath(ClientConstants.DOMAIN_PATH_TOKEN_ENDPOINT).build();
// Make http POST call
final AuthHttpClient httpClient = new AuthHttpClient();
Map<String, String> httpHeaderParams = getHttpHeader();
Map<String, String> httpBodyParams = generateTokenRefreshRequest(redirectUri, session);
try {
String response = httpClient.httpPost(new URL(fqdn.toString()), httpHeaderParams, httpBodyParams);
AuthUserSession parsedSession = AuthHttpResponseParser.parseHttpResponse(response);
final AuthUserSession refreshedSession = new AuthUserSession(parsedSession.getIdToken(), parsedSession.getAccessToken(), session.getRefreshToken());
final String username = refreshedSession.getUsername();
// Cache session
LocalDataManager.cacheSession(pool.awsKeyValueStore, context, pool.getAppId(), username, refreshedSession, pool.getScopes());
// Return tokens
returnCallback = new Runnable() {
@Override
public void run() {
callback.onSuccess(refreshedSession);
}
};
} catch (final AuthInvalidGrantException invg) {
if (showSignInIfExpired) {
returnCallback = new Runnable() {
@Override
public void run() {
launchCognitoAuth(redirectUri, tokenScopes, activity, browserPackage);
}
};
} else {
returnCallback = new Runnable() {
@Override
public void run() {
userHandler.onFailure(invg);
}
};
}
} catch (final Exception e) {
returnCallback = new Runnable() {
@Override
public void run() {
callback.onFailure(e);
}
};
}
handler.post(returnCallback);
}
}).start();
}
use of com.amazonaws.mobileconnectors.cognitoauth.handlers.AuthHandler in project aws-sdk-android by aws-amplify.
the class OAuth2Utils method _getHostedUITokens.
private void _getHostedUITokens(final Callback<Tokens> callback) {
hostedUI = hostedUI.getCurrentUser();
hostedUI.setAuthHandler(new AuthHandler() {
@Override
public void onSuccess(AuthUserSession session) {
callback.onResult(new Tokens(session.getAccessToken().getJWTToken(), session.getIdToken().getJWTToken(), session.getRefreshToken().getToken()));
}
@Override
public void onSignout() {
callback.onError(new Exception("No cached session."));
}
@Override
public void onFailure(Exception e) {
callback.onError(new Exception("No cached session.", e));
}
});
hostedUI.getSessionWithoutWebUI();
}
use of com.amazonaws.mobileconnectors.cognitoauth.handlers.AuthHandler in project aws-sdk-android by aws-amplify.
the class OAuth2Utils method _initializeHostedUI.
private void _initializeHostedUI(JSONObject hostedUIJSON) throws JSONException {
Log.d(TAG, "initialize: Cognito HostedUI client detected");
final JSONArray scopesJSONArray = hostedUIJSON.getJSONArray("Scopes");
final Set<String> scopes = new HashSet<String>();
for (int i = 0; i < scopesJSONArray.length(); i++) {
scopes.add(scopesJSONArray.getString(i));
}
if (mUserPoolPoolId == null) {
throw new IllegalStateException("User pool Id must be available through user pool setting");
}
hostedUI = getHostedUI(hostedUIJSON).setPersistenceEnabled(mIsPersistenceEnabled).setAuthHandler(new AuthHandler() {
@Override
public void onSuccess(AuthUserSession session) {
// Ignored because this is used to pre-warm the session
}
@Override
public void onSignout() {
// Ignored because this is used to pre-warm the session
}
@Override
public void onFailure(Exception e) {
// Ignored because this is used to pre-warm the session
}
}).build();
}
Aggregations