use of com.amazonaws.mobileconnectors.cognitoauth.tokens.AccessToken in project aws-sdk-android by aws-amplify.
the class AWSMobileClientPersistenceWithRestartabilityTest method signInAndVerifySignIn.
private void signInAndVerifySignIn() {
try {
final CountDownLatch stateNotificationLatch = new CountDownLatch(1);
final AtomicReference<UserStateDetails> userState = new AtomicReference<UserStateDetails>();
listener = new UserStateListener() {
@Override
public void onUserStateChanged(UserStateDetails details) {
userState.set(details);
auth.removeUserStateListener(listener);
stateNotificationLatch.countDown();
}
};
auth.addUserStateListener(listener);
final SignInResult signInResult = auth.signIn(username, PASSWORD, null);
assertEquals("Cannot support MFA in tests", SignInState.DONE, signInResult.getSignInState());
assertTrue("isSignedIn is true", auth.isSignedIn());
assertEquals(username, auth.getUsername());
// Check credentials are available
final AWSCredentials credentials = auth.getCredentials();
assertNotNull("Credentials are null", credentials);
assertNotNull("Access key is null", credentials.getAWSAccessKeyId());
assertNotNull("Secret key is null", credentials.getAWSSecretKey());
Tokens tokens = auth.getTokens();
assertNotNull(tokens);
Token accessToken = tokens.getAccessToken();
assertNotNull(accessToken);
assertTrue("Access token should not be expired", accessToken.getExpiration().after(new Date()));
Token idToken = tokens.getIdToken();
assertNotNull(idToken);
assertTrue("Id token should not be expired", idToken.getExpiration().after(new Date()));
Token refreshToken = tokens.getRefreshToken();
assertNotNull(refreshToken);
// Check one attribute
final Map<String, String> userAttributes = auth.getUserAttributes();
assertEquals(getPackageConfigure().getString("email"), userAttributes.get("email"));
stateNotificationLatch.await(5, TimeUnit.SECONDS);
UserStateDetails userStateDetails = userState.get();
assertEquals(userStateDetails.getUserState(), UserState.SIGNED_IN);
Map<String, String> details = userStateDetails.getDetails();
assertNotEquals(getPackageConfigure().getString("identity_id"), details.toString());
} catch (Exception ex) {
fail(ex.getMessage());
}
}
use of com.amazonaws.mobileconnectors.cognitoauth.tokens.AccessToken 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.tokens.AccessToken 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.tokens.AccessToken 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.tokens.AccessToken in project aws-sdk-android by aws-amplify.
the class AWSMobileClientPersistenceWithRestartabilityTest method mockHostedUISignIn.
// Note that most tests create valid JWT tokens with expiry dates in the past. However, because
// we want to assert that HostedUI can get tokens, without making a network call to refresh a
// session, we're going to mock up valid session data, and ensure we call `getTokens` with
// `waitForSignIn = false`.
private void mockHostedUISignIn() throws JSONException {
AuthUserSession authUserSession = new AuthUserSession(new IdToken(getValidJWT(3600L)), new AccessToken(getValidJWT(3600L)), new RefreshToken(getValidJWT(360000L)));
Context targetContext = ApplicationProvider.getApplicationContext();
AWSKeyValueStore storeForHostedUI = new AWSKeyValueStore(targetContext, "CognitoIdentityProviderCache", true);
final Set<String> scopes = new HashSet<String>(Arrays.asList("aws.cognito.signin.user.admin", "phone", "openid", "profile", "email"));
LocalDataManager.cacheSession(storeForHostedUI, targetContext, getPackageConfigure().getString("app_client_id"), getPackageConfigure().getString("username"), authUserSession, scopes);
// Set the AWSMobileClient metadata that is specific to HostedUI
auth.mStore.set(FEDERATION_ENABLED_KEY, "true");
auth.mStore.set(HOSTED_UI_KEY, "dummyJson");
auth.mStore.set(SIGN_IN_MODE, SignInMode.HOSTED_UI.toString());
auth.mStore.set(PROVIDER_KEY, auth.getLoginKey());
auth.mStore.set(TOKEN_KEY, getValidJWT(3600L));
}
Aggregations