Search in sources :

Example 11 with HttpWebResponse

use of com.microsoft.identity.common.adal.internal.net.HttpWebResponse in project azure-activedirectory-library-for-android by AzureAD.

the class WebRequestHandlerTests method testPostRequest.

@Test
public void testPostRequest() throws IOException {
    final TestMessage message = new TestMessage("messagetest", "12345");
    final String json = new Gson().toJson(message);
    final HttpURLConnection mockedConnection = Mockito.mock(HttpURLConnection.class);
    HttpUrlConnectionFactory.setMockedHttpUrlConnection(mockedConnection);
    Util.prepareMockedUrlConnection(mockedConnection);
    Mockito.when(mockedConnection.getOutputStream()).thenReturn(Mockito.mock(OutputStream.class));
    Mockito.when(mockedConnection.getInputStream()).thenReturn(Util.createInputStream(message.getAccessToken() + message.getUserName()));
    Mockito.when(mockedConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK);
    final WebRequestHandler request = new WebRequestHandler();
    final HttpWebResponse httpResponse = request.sendPost(getUrl(TEST_WEBAPI_URL), new HashMap<String, String>(), json.getBytes(StandardCharsets.UTF_8), "application/json");
    assertTrue("status is 200", httpResponse.getStatusCode() == HttpURLConnection.HTTP_OK);
    final String responseMsg = httpResponse.getBody();
    assertTrue("request body check", responseMsg.contains(message.getAccessToken() + message.getUserName()));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) OutputStream(java.io.OutputStream) Gson(com.google.gson.Gson) WebRequestHandler(com.microsoft.identity.common.adal.internal.net.WebRequestHandler) HttpWebResponse(com.microsoft.identity.common.adal.internal.net.HttpWebResponse) Test(org.junit.Test)

Example 12 with HttpWebResponse

use of com.microsoft.identity.common.adal.internal.net.HttpWebResponse in project azure-activedirectory-library-for-android by AzureAD.

the class OauthTests method testRefreshTokenWebResponseInvalidStatus.

@Test
public void testRefreshTokenWebResponseInvalidStatus() {
    MockWebRequestHandler webrequest = new MockWebRequestHandler();
    webrequest.setReturnResponse(new HttpWebResponse(HttpURLConnection.HTTP_UNAVAILABLE, "{\"error\":\"no_internet\"}", new HashMap<String, List<String>>()));
    // send request
    MockAuthenticationCallback testResult = refreshToken(getValidAuthenticationRequest(), webrequest, "test");
    // Verify that callback can receive this error
    assertNull("AuthenticationResult is null", testResult.getAuthenticationResult());
    assertNotNull("Exception is not null", testResult.getException());
    assertTrue(testResult.getException() instanceof AuthenticationException);
    assertEquals(((AuthenticationException) testResult.getException()).getServiceStatusCode(), HttpURLConnection.HTTP_UNAVAILABLE);
}
Also used : HashMap(java.util.HashMap) HttpWebResponse(com.microsoft.identity.common.adal.internal.net.HttpWebResponse) Test(org.junit.Test)

Example 13 with HttpWebResponse

use of com.microsoft.identity.common.adal.internal.net.HttpWebResponse in project azure-activedirectory-library-for-android by AzureAD.

the class AuthenticationParameters method createFromResourceUrl.

/**
 * ADAL will make the call to get authority and resource info.
 *
 * @param context     {@link Context}
 * @param resourceUrl Url for resource to query for 401 response.
 * @param callback    {@link AuthenticationParamCallback}
 */
public static void createFromResourceUrl(Context context, final URL resourceUrl, final AuthenticationParamCallback callback) {
    if (callback == null) {
        throw new IllegalArgumentException("callback");
    }
    Logger.v(TAG, "createFromResourceUrl");
    final Handler handler = new Handler(context.getMainLooper());
    sThreadExecutor.submit(new Runnable() {

        @Override
        public void run() {
            final Map<String, String> headers = new HashMap<>();
            headers.put(WebRequestHandler.HEADER_ACCEPT, WebRequestHandler.HEADER_ACCEPT_JSON);
            final HttpWebResponse webResponse;
            try {
                webResponse = sWebRequest.sendGet(resourceUrl, headers);
                try {
                    onCompleted(null, parseResponse(webResponse));
                } catch (ResourceAuthenticationChallengeException exc) {
                    onCompleted(exc, null);
                }
            } catch (IOException e) {
                onCompleted(e, null);
            }
        }

        void onCompleted(final Exception exception, final AuthenticationParameters param) {
            handler.post(new Runnable() {

                @Override
                public void run() {
                    callback.onCompleted(exception, param);
                }
            });
        }
    });
}
Also used : IWebRequestHandler(com.microsoft.identity.common.adal.internal.net.IWebRequestHandler) WebRequestHandler(com.microsoft.identity.common.adal.internal.net.WebRequestHandler) Handler(android.os.Handler) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) IOException(java.io.IOException) HttpWebResponse(com.microsoft.identity.common.adal.internal.net.HttpWebResponse)

Example 14 with HttpWebResponse

use of com.microsoft.identity.common.adal.internal.net.HttpWebResponse in project azure-activedirectory-library-for-android by AzureAD.

the class DRSMetadataRequestor method requestDrsDiscoveryInternal.

private DRSMetadata requestDrsDiscoveryInternal(final Type type, final String domain) throws AuthenticationException, UnknownHostException {
    final URL requestURL;
    try {
        // create the request URL
        requestURL = new URL(buildRequestUrlByType(type, domain));
    } catch (MalformedURLException e) {
        throw new AuthenticationException(ADALError.DRS_METADATA_URL_INVALID);
    }
    // init the headers to use in the request
    final Map<String, String> headers = new HashMap<>();
    headers.put(ACCEPT, APPLICATION_JSON);
    if (null != getCorrelationId()) {
        headers.put(AuthenticationConstants.AAD.CLIENT_REQUEST_ID, getCorrelationId().toString());
    }
    final DRSMetadata metadata;
    final HttpWebResponse webResponse;
    // make the request
    try {
        webResponse = getWebrequestHandler().sendGet(requestURL, headers);
        final int statusCode = webResponse.getStatusCode();
        if (HttpURLConnection.HTTP_OK == statusCode) {
            metadata = parseMetadata(webResponse);
        } else {
            // unexpected status code
            throw new AuthenticationException(ADALError.DRS_FAILED_SERVER_ERROR, "Unexpected error code: [" + statusCode + "]");
        }
    } catch (UnknownHostException e) {
        throw e;
    } catch (IOException e) {
        throw new AuthenticationException(ADALError.IO_EXCEPTION);
    }
    return metadata;
}
Also used : MalformedURLException(java.net.MalformedURLException) UnknownHostException(java.net.UnknownHostException) HashMap(java.util.HashMap) IOException(java.io.IOException) URL(java.net.URL) HttpWebResponse(com.microsoft.identity.common.adal.internal.net.HttpWebResponse)

Example 15 with HttpWebResponse

use of com.microsoft.identity.common.adal.internal.net.HttpWebResponse in project azure-activedirectory-library-for-android by AzureAD.

the class Discovery method sendRequest.

private Map<String, String> sendRequest(final URL queryUrl) throws IOException, JSONException, AuthenticationException {
    Logger.v(TAG, "Sending discovery request to query url. ", "queryUrl: " + queryUrl, null);
    final Map<String, String> headers = new HashMap<>();
    headers.put(WebRequestHandler.HEADER_ACCEPT, WebRequestHandler.HEADER_ACCEPT_JSON);
    // CorrelationId is used to track the request at the Azure services
    if (mCorrelationId != null) {
        headers.put(AuthenticationConstants.AAD.CLIENT_REQUEST_ID, mCorrelationId.toString());
        headers.put(AuthenticationConstants.AAD.RETURN_CLIENT_REQUEST_ID, "true");
    }
    final HttpWebResponse webResponse;
    try {
        ClientMetrics.INSTANCE.beginClientMetricsRecord(queryUrl, mCorrelationId, headers);
        webResponse = mWebrequestHandler.sendGet(queryUrl, headers);
        ClientMetrics.INSTANCE.setLastError(null);
        // parse discovery response to find tenant info
        final Map<String, String> discoveryResponse = parseResponse(webResponse);
        if (discoveryResponse.containsKey(AuthenticationConstants.OAuth2.ERROR_CODES)) {
            final String errorCodes = discoveryResponse.get(AuthenticationConstants.OAuth2.ERROR_CODES);
            ClientMetrics.INSTANCE.setLastError(errorCodes);
            throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_INSTANCE, "Fail to valid authority with errors: " + errorCodes);
        }
        return discoveryResponse;
    } finally {
        ClientMetrics.INSTANCE.endClientMetricsRecord(ClientMetricsEndpointType.INSTANCE_DISCOVERY, mCorrelationId);
    }
}
Also used : HashMap(java.util.HashMap) HttpWebResponse(com.microsoft.identity.common.adal.internal.net.HttpWebResponse)

Aggregations

HttpWebResponse (com.microsoft.identity.common.adal.internal.net.HttpWebResponse)35 Test (org.junit.Test)29 URL (java.net.URL)21 IWebRequestHandler (com.microsoft.identity.common.adal.internal.net.IWebRequestHandler)19 SmallTest (androidx.test.filters.SmallTest)16 HashMap (java.util.HashMap)6 WebRequestHandler (com.microsoft.identity.common.adal.internal.net.WebRequestHandler)5 HttpURLConnection (java.net.HttpURLConnection)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Handler (android.os.Handler)1 Gson (com.google.gson.Gson)1 ChallengeResponse (com.microsoft.aad.adal.ChallengeResponseBuilder.ChallengeResponse)1 JWSBuilder (com.microsoft.identity.common.adal.internal.JWSBuilder)1 OutputStream (java.io.OutputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 MalformedURLException (java.net.MalformedURLException)1 SocketTimeoutException (java.net.SocketTimeoutException)1 UnknownHostException (java.net.UnknownHostException)1