use of com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession 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.AuthUserSession in project aws-sdk-android by aws-amplify.
the class LocalDataManager method getCachedSession.
/**
* Returns cached tokens for a user as a {@link AuthUserSession}.
* @param context Required: The host application {@link Context}.
* @param clientId Required: Cognito App/Client Id.
* @param username Required: The username.
* @return {@link AuthUserSession}.
*/
public static AuthUserSession getCachedSession(final Context context, final String clientId, final String username, final Set<String> scopes) {
AuthUserSession session = new AuthUserSession(null, null, null);
if (username != null) {
if (context == null || clientId == null || clientId.isEmpty()) {
throw new InvalidParameterException("Application context, and application domain cannot be null");
}
String cachedIdTokenKey = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_TYPE_ID);
String cachedAccessTokenKey = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_TYPE_ACCESS);
String cachedRefreshTokenKey = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_TYPE_REFRESH);
String cachedTokenScopes = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_KEY_SCOPES);
try {
SharedPreferences localCache = context.getSharedPreferences(ClientConstants.APP_LOCAL_CACHE, Context.MODE_PRIVATE);
Set<String> cachedScopes = localCache.getStringSet(cachedTokenScopes, new HashSet<String>());
// Check if the requested scopes match scopes of the cached tokens.
if (!cachedScopes.equals(scopes)) {
return session;
}
// Scopes match, return the cached tokens
IdToken idToken = new IdToken(localCache.getString(cachedIdTokenKey, null));
AccessToken accessToken = new AccessToken(localCache.getString(cachedAccessTokenKey, null));
RefreshToken refreshToken = new RefreshToken(localCache.getString(cachedRefreshTokenKey, null));
session = new AuthUserSession(idToken, accessToken, refreshToken);
} catch (Exception e) {
Log.e(TAG, "Failed to read from SharedPreferences", e);
}
}
return session;
}
use of com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession in project aws-sdk-android by aws-amplify.
the class LocalDataManager method getCachedSession.
/**
* Returns cached tokens for a user as a {@link AuthUserSession}.
* @param context Required: The host application {@link Context}.
* @param clientId Required: Cognito App/Client Id.
* @param username Required: The username.
* @return {@link AuthUserSession}.
*/
public static AuthUserSession getCachedSession(final AWSKeyValueStore awsKeyValueStore, final Context context, final String clientId, final String username, final Set<String> scopes) {
AuthUserSession session = new AuthUserSession(null, null, null);
if (username != null) {
if (context == null || clientId == null || clientId.isEmpty()) {
throw new InvalidParameterException("Application context, and application domain cannot be null");
}
String cachedIdTokenKey = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_TYPE_ID);
String cachedAccessTokenKey = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_TYPE_ACCESS);
String cachedRefreshTokenKey = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_TYPE_REFRESH);
String cachedTokenScopes = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_KEY_SCOPES);
try {
String cachedSetString = awsKeyValueStore.get(cachedTokenScopes);
Set<String> cachedScopes = setFromString(cachedSetString);
// Check if the requested scopes match scopes of the cached tokens.
if (!cachedScopes.equals(scopes)) {
return session;
}
// Scopes match, return the cached tokens
IdToken idToken = new IdToken(awsKeyValueStore.get(cachedIdTokenKey));
AccessToken accessToken = new AccessToken(awsKeyValueStore.get(cachedAccessTokenKey));
RefreshToken refreshToken = new RefreshToken(awsKeyValueStore.get(cachedRefreshTokenKey));
session = new AuthUserSession(idToken, accessToken, refreshToken);
} catch (Exception e) {
Log.e(TAG, "Failed to read from SharedPreferences", e);
}
}
return session;
}
use of com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession in project aws-sdk-android by aws-amplify.
the class AuthHttpResponseParser method parseHttpResponse.
/**
* Parses the http response from Cognito service and extracts tokens.
* <p>
* Throws {@link AuthInvalidGrantException when }
* </p>
* @param responseStr Required: Response from Cognito Service Token-Endpoint.
* @return {@link AuthUserSession}.
*/
public static final AuthUserSession parseHttpResponse(String responseStr) {
if (responseStr == null || responseStr.isEmpty()) {
throw new AuthInvalidParameterException("Invalid (null) response from Amazon Cognito Auth endpoint");
}
AccessToken accessToken = new AccessToken(null);
IdToken idToken = new IdToken(null);
RefreshToken refreshToken = new RefreshToken(null);
JSONObject responseJson;
try {
responseJson = new JSONObject(responseStr);
if (responseJson.has(ClientConstants.DOMAIN_QUERY_PARAM_ERROR)) {
String errorText = responseJson.getString(ClientConstants.DOMAIN_QUERY_PARAM_ERROR);
if (ClientConstants.HTTP_RESPONSE_INVALID_GRANT.equals(errorText)) {
throw new AuthInvalidGrantException(errorText);
} else {
throw new AuthServiceException(errorText);
}
}
if (responseJson.has(ClientConstants.HTTP_RESPONSE_ACCESS_TOKEN)) {
accessToken = new AccessToken(responseJson.getString(ClientConstants.HTTP_RESPONSE_ACCESS_TOKEN));
}
if (responseJson.has(ClientConstants.HTTP_RESPONSE_ID_TOKEN)) {
idToken = new IdToken(responseJson.getString(ClientConstants.HTTP_RESPONSE_ID_TOKEN));
}
if (responseJson.has(ClientConstants.HTTP_RESPONSE_REFRESH_TOKEN)) {
refreshToken = new RefreshToken(responseJson.getString(ClientConstants.HTTP_RESPONSE_REFRESH_TOKEN));
}
} catch (AuthInvalidGrantException invg) {
throw invg;
} catch (AuthServiceException seve) {
throw seve;
} catch (Exception e) {
throw new AuthClientException(e.getMessage(), e);
}
return new AuthUserSession(idToken, accessToken, refreshToken);
}
use of com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession 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();
}
Aggregations