Search in sources :

Example 1 with WebRequestHandler

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

the class AcquireTokenInteractiveRequest method acquireTokenWithAuthCode.

/**
 * @param url Url containing the auth code.
 * @return {@link AuthenticationResult} for acquire token request with grant_type as code.
 * @throws AuthenticationException
 */
AuthenticationResult acquireTokenWithAuthCode(final String url) throws AuthenticationException {
    final String methodName = ":acquireTokenWithAuthCode";
    Logger.v(TAG + methodName, "Start token acquisition with auth code.", mAuthRequest.getLogInfo(), null);
    final Oauth2 oauthRequest = new Oauth2(mAuthRequest, new WebRequestHandler());
    final AuthenticationResult result;
    try {
        result = oauthRequest.getToken(url);
        Logger.v(TAG + methodName, "OnActivityResult processed the result.");
    } catch (final IOException | AuthenticationException exc) {
        final String msg = "Error in processing code to get token. " + getCorrelationInfo();
        throw new AuthenticationException(ADALError.AUTHORIZATION_CODE_NOT_EXCHANGED_FOR_TOKEN, msg, exc);
    }
    if (result == null) {
        Logger.e(TAG + methodName, "Returned result with exchanging auth code for token is null" + getCorrelationInfo(), "", ADALError.AUTHORIZATION_CODE_NOT_EXCHANGED_FOR_TOKEN);
        throw new AuthenticationException(ADALError.AUTHORIZATION_CODE_NOT_EXCHANGED_FOR_TOKEN, getCorrelationInfo());
    }
    if (!StringExtensions.isNullOrBlank(result.getErrorCode())) {
        Logger.e(TAG + methodName, " ErrorCode:" + result.getErrorCode(), " ErrorDescription:" + result.getErrorDescription(), ADALError.AUTH_FAILED);
        throw new AuthenticationException(ADALError.AUTH_FAILED, " ErrorCode:" + result.getErrorCode());
    }
    if (!StringExtensions.isNullOrBlank(result.getAccessToken()) && mTokenCacheAccessor != null) {
        // Developer may pass null for the acquireToken flow.
        try {
            mTokenCacheAccessor.updateTokenCache(mAuthRequest, result);
        } catch (MalformedURLException e) {
            throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_URL, e.getMessage(), e);
        }
    }
    return result;
}
Also used : MalformedURLException(java.net.MalformedURLException) WebRequestHandler(com.microsoft.identity.common.adal.internal.net.WebRequestHandler) IOException(java.io.IOException)

Example 2 with WebRequestHandler

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

the class WebRequestHandlerTests method testNonExistentUrl.

@Test
@Ignore
public // Depending on the operating environment, DNS assistance (ISP supplied) breaks this test
void testNonExistentUrl() {
    WebRequestHandler request = new WebRequestHandler();
    try {
        request.sendGet(getUrl("http://www.somethingabcddnotexists.com"), new HashMap<String, String>());
        fail("Unreachable host, should throw IOException");
    } catch (final IOException e) {
        assertTrue(e instanceof UnknownHostException);
        assertTrue(e.getMessage().toLowerCase(Locale.US).contains("unable to resolve host"));
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) WebRequestHandler(com.microsoft.identity.common.adal.internal.net.WebRequestHandler) IOException(java.io.IOException) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 3 with WebRequestHandler

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

the class WebRequestHandlerTests method testGetWithIdRequest.

@Test
public void testGetWithIdRequest() throws IOException {
    final HttpURLConnection mockedConnection = Mockito.mock(HttpURLConnection.class);
    HttpUrlConnectionFactory.setMockedHttpUrlConnection(mockedConnection);
    Util.prepareMockedUrlConnection(mockedConnection);
    Mockito.when(mockedConnection.getInputStream()).thenReturn(Util.createInputStream("test get with id"));
    Mockito.when(mockedConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK);
    final WebRequestHandler request = new WebRequestHandler();
    HttpWebResponse httpResponse = request.sendGet(getUrl(TEST_WEBAPI_URL + "/1"), new HashMap<String, String>());
    assertTrue("status is 200", httpResponse.getStatusCode() == HttpURLConnection.HTTP_OK);
    final String responseMsg = httpResponse.getBody();
    assertTrue("request body check", responseMsg.contains("test get with id"));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) WebRequestHandler(com.microsoft.identity.common.adal.internal.net.WebRequestHandler) HttpWebResponse(com.microsoft.identity.common.adal.internal.net.HttpWebResponse) Test(org.junit.Test)

Example 4 with WebRequestHandler

use of com.microsoft.identity.common.adal.internal.net.WebRequestHandler 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 5 with WebRequestHandler

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

the class OauthTests method testProcessTokenResponseWrongCorrelationId.

@Test
public void testProcessTokenResponseWrongCorrelationId() throws IOException {
    final AuthenticationRequest request = createAuthenticationRequest(TEST_AUTHORITY, "resource", "client", "redirect", "loginhint", null, null, UUID.randomUUID(), false);
    final Oauth2 oauth2 = createOAuthInstance(request, new WebRequestHandler());
    final String jsonResponse = "{\"access_token\":\"sometokenhere2343=\",\"token_type\":" + "\"Bearer\",\"expires_in\":\"28799\",\"expires_on\":\"1368768616\"," + "\"refresh_token\":\"refreshfasdfsdf435=\",\"scope\":\"*\"}";
    // mock token request response
    final HttpURLConnection mockedConnection = mock(HttpURLConnection.class);
    HttpUrlConnectionFactory.setMockedHttpUrlConnection(mockedConnection);
    Util.prepareMockedUrlConnection(mockedConnection);
    when(mockedConnection.getOutputStream()).thenReturn(mock(OutputStream.class));
    when(mockedConnection.getInputStream()).thenReturn(Util.createInputStream(jsonResponse), Util.createInputStream(jsonResponse));
    when(mockedConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK);
    // mock conncetion header
    final List<String> listOfHeaders = new ArrayList<>();
    listOfHeaders.add(UUID.randomUUID().toString());
    final Map<String, List<String>> headers = new HashMap<>();
    headers.put(AuthenticationConstants.AAD.CLIENT_REQUEST_ID, listOfHeaders);
    when(mockedConnection.getHeaderFields()).thenReturn(headers);
    Logger.getInstance().setLogLevel(Logger.LogLevel.Debug);
    final TestLogResponse logResponse = new TestLogResponse();
    logResponse.listenForLogMessage("CorrelationId is not matching", null);
    try {
        final AuthenticationResult result = oauth2.refreshToken("fakeRefreshToken");
        Thread.sleep(1000);
        // verify same token
        assertEquals("Same token in parsed result", "sometokenhere2343=", result.getAccessToken());
        assertTrue("Log response has message", ADALError.CORRELATION_ID_NOT_MATCHING_REQUEST_RESPONSE.equals(logResponse.getErrorCode()));
    } catch (final AuthenticationException e) {
        fail("unexpected exception");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    final List<String> invalidHeaders = new ArrayList<>();
    invalidHeaders.add("invalid-UUID");
    headers.put(AuthenticationConstants.AAD.CLIENT_REQUEST_ID, invalidHeaders);
    when(mockedConnection.getHeaderFields()).thenReturn(headers);
    TestLogResponse logResponse2 = new TestLogResponse();
    logResponse2.listenLogForMessageSegments("Wrong format of the correlation ID:");
    try {
        oauth2.refreshToken("fakeRefreshToken");
        Thread.sleep(1000);
        assertTrue("Log response has message", logResponse2.getErrorCode().equals(ADALError.CORRELATION_ID_FORMAT));
    } catch (final AuthenticationException e) {
        fail("Unexpected exception");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
Also used : HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) HttpURLConnection(java.net.HttpURLConnection) IWebRequestHandler(com.microsoft.identity.common.adal.internal.net.IWebRequestHandler) WebRequestHandler(com.microsoft.identity.common.adal.internal.net.WebRequestHandler) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.Test)

Aggregations

WebRequestHandler (com.microsoft.identity.common.adal.internal.net.WebRequestHandler)10 Test (org.junit.Test)8 HttpURLConnection (java.net.HttpURLConnection)7 HttpWebResponse (com.microsoft.identity.common.adal.internal.net.HttpWebResponse)4 OutputStream (java.io.OutputStream)4 IWebRequestHandler (com.microsoft.identity.common.adal.internal.net.IWebRequestHandler)3 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 Gson (com.google.gson.Gson)1 MalformedURLException (java.net.MalformedURLException)1 UnknownHostException (java.net.UnknownHostException)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 JSONException (org.json.JSONException)1 Ignore (org.junit.Ignore)1