use of com.amazonaws.mobileconnectors.cognitoauth.exceptions.AuthServiceException 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.exceptions.AuthServiceException in project aws-sdk-android by aws-amplify.
the class AuthHttpClient method httpPost.
public String httpPost(final URL uri, final Map<String, String> headerParams, final Map<String, String> bodyParams) throws Exception {
if (uri == null || bodyParams == null || bodyParams.size() < 1) {
throw new AuthClientException("Invalid http request parameters");
}
final HttpsURLConnection httpsURLConnection = (HttpsURLConnection) uri.openConnection();
DataOutputStream httpOutputStream = null;
BufferedReader br = null;
try {
// Request header
httpsURLConnection.setRequestMethod(ClientConstants.HTTP_REQUEST_TYPE_POST);
httpsURLConnection.setDoOutput(true);
for (Map.Entry<String, String> param : headerParams.entrySet()) {
httpsURLConnection.addRequestProperty(param.getKey(), param.getValue());
}
// Request body
StringBuilder reqBuilder = new StringBuilder();
int index = bodyParams.size();
for (Map.Entry<String, String> param : bodyParams.entrySet()) {
reqBuilder.append(URLEncoder.encode(param.getKey(), "UTF-8")).append('=').append(URLEncoder.encode(param.getValue(), "UTF-8"));
if (index-- > 1) {
reqBuilder.append('&');
}
}
String requestBody = reqBuilder.toString();
httpOutputStream = new DataOutputStream(httpsURLConnection.getOutputStream());
httpOutputStream.writeBytes(requestBody);
httpOutputStream.flush();
// Parse response
Map<String, List<String>> respHeaders = httpsURLConnection.getHeaderFields();
int responseCode = httpsURLConnection.getResponseCode();
if (responseCode >= HttpURLConnection.HTTP_OK && responseCode < HttpURLConnection.HTTP_INTERNAL_ERROR) {
// Return response from the http call
InputStream httpDataStream;
if (responseCode < HttpURLConnection.HTTP_BAD_REQUEST) {
httpDataStream = httpsURLConnection.getInputStream();
} else {
httpDataStream = httpsURLConnection.getErrorStream();
}
br = new BufferedReader(new InputStreamReader(httpDataStream));
String line = "";
StringBuilder responseOutput = new StringBuilder();
while ((line = br.readLine()) != null) {
responseOutput.append(line);
}
return responseOutput.toString();
} else {
// Throw a Cognito Client Exception
throw new AuthServiceException(httpsURLConnection.getResponseMessage());
}
} catch (final Exception e) {
throw e;
} finally {
if (httpOutputStream != null) {
httpOutputStream.close();
}
if (br != null) {
br.close();
}
}
}
use of com.amazonaws.mobileconnectors.cognitoauth.exceptions.AuthServiceException in project aws-sdk-android by aws-amplify.
the class AuthClient method endSession.
/**
* Ends current browser session.
* @param browserPackage browser package to launch sign-out endpoint from.
* @throws AuthClientException if sign-out redirect fails to resolve.
*/
private void endSession(final String browserPackage) throws AuthClientException {
boolean redirectReceived;
try {
cookiesCleared = new CountDownLatch(1);
launchSignOut(pool.getSignOutRedirectUri(), browserPackage);
if (!isRedirectActivityDeclared()) {
cookiesCleared.countDown();
}
redirectReceived = cookiesCleared.await(REDIRECT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new AuthNavigationException("User cancelled sign-out.");
}
if (!redirectReceived) {
throw new AuthServiceException("Timed out while waiting for sign-out redirect response.");
}
}
use of com.amazonaws.mobileconnectors.cognitoauth.exceptions.AuthServiceException 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.exceptions.AuthServiceException in project aws-sdk-android by aws-amplify.
the class OAuth2Constants method httpPost.
public static String httpPost(final URL uri, final Map<String, String> headerParams, final Map<String, String> bodyParams, final String userAgentOverride) throws Exception {
if (uri == null || bodyParams == null || bodyParams.size() < 1) {
throw new AuthClientException("Invalid http request parameters");
}
final HttpsURLConnection httpsURLConnection = (HttpsURLConnection) uri.openConnection();
DataOutputStream httpOutputStream = null;
BufferedReader br = null;
try {
// Request header
httpsURLConnection.setRequestMethod(ClientConstants.HTTP_REQUEST_TYPE_POST);
httpsURLConnection.setDoOutput(true);
for (Map.Entry<String, String> param : headerParams.entrySet()) {
httpsURLConnection.addRequestProperty(param.getKey(), param.getValue());
}
httpsURLConnection.addRequestProperty("x-amz-user-agent", userAgentOverride != null ? userAgentOverride : AWSMobileClient.DEFAULT_USER_AGENT);
httpsURLConnection.setRequestProperty("User-Agent", userAgentOverride != null ? userAgentOverride : httpsURLConnection.getRequestProperty("User-Agent") + " " + AWSMobileClient.DEFAULT_USER_AGENT);
// Request body
StringBuilder reqBuilder = new StringBuilder();
int index = bodyParams.size();
for (Map.Entry<String, String> param : bodyParams.entrySet()) {
reqBuilder.append(URLEncoder.encode(param.getKey(), "UTF-8")).append('=').append(URLEncoder.encode(param.getValue(), "UTF-8"));
if (index-- > 1) {
reqBuilder.append('&');
}
}
String requestBody = reqBuilder.toString();
httpOutputStream = new DataOutputStream(httpsURLConnection.getOutputStream());
httpOutputStream.writeBytes(requestBody);
httpOutputStream.flush();
// Parse response
Map<String, List<String>> respHeaders = httpsURLConnection.getHeaderFields();
int responseCode = httpsURLConnection.getResponseCode();
if (responseCode >= HttpURLConnection.HTTP_OK && responseCode < HttpURLConnection.HTTP_INTERNAL_ERROR) {
// Return response from the http call
InputStream httpDataStream;
if (responseCode < HttpURLConnection.HTTP_BAD_REQUEST) {
httpDataStream = httpsURLConnection.getInputStream();
} else {
httpDataStream = httpsURLConnection.getErrorStream();
}
br = new BufferedReader(new InputStreamReader(httpDataStream));
String line;
StringBuilder responseOutput = new StringBuilder();
while ((line = br.readLine()) != null) {
responseOutput.append(line);
}
return responseOutput.toString();
} else {
// Throw a Cognito Client Exception
throw new AuthServiceException(httpsURLConnection.getResponseMessage());
}
} catch (final Exception e) {
throw e;
} finally {
if (httpOutputStream != null) {
httpOutputStream.close();
}
if (br != null) {
br.close();
}
}
}
Aggregations