Search in sources :

Example 16 with HttpWebResponse

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

the class Oauth2 method postMessage.

private AuthenticationResult postMessage(String requestMessage, Map<String, String> headers) throws IOException, AuthenticationException {
    final String methodName = ":postMessage";
    AuthenticationResult result = null;
    final HttpEvent httpEvent = startHttpEvent();
    final URL authority = StringExtensions.getUrl(getTokenEndpoint());
    if (authority == null) {
        stopHttpEvent(httpEvent);
        throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_URL);
    }
    httpEvent.setHttpPath(authority);
    try {
        mWebRequestHandler.setRequestCorrelationId(mRequest.getCorrelationId());
        mWebRequestHandler.setClientVersion(AuthenticationContext.getVersionName());
        ClientMetrics.INSTANCE.beginClientMetricsRecord(authority, mRequest.getCorrelationId(), headers);
        HttpWebResponse response = mWebRequestHandler.sendPost(authority, headers, requestMessage.getBytes(AuthenticationConstants.ENCODING_UTF8), "application/x-www-form-urlencoded");
        httpEvent.setResponseCode(response.getStatusCode());
        httpEvent.setCorrelationId(mRequest.getCorrelationId().toString());
        stopHttpEvent(httpEvent);
        if (response.getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            if (response.getResponseHeaders() != null && response.getResponseHeaders().containsKey(AuthenticationConstants.Broker.CHALLENGE_REQUEST_HEADER)) {
                // Device certificate challenge will send challenge request
                // in 401 header.
                String challengeHeader = response.getResponseHeaders().get(AuthenticationConstants.Broker.CHALLENGE_REQUEST_HEADER).get(0);
                Logger.i(TAG + methodName, "Device certificate challenge request. ", "Challenge header: " + challengeHeader);
                if (!StringExtensions.isNullOrBlank(challengeHeader)) {
                    // Handle each specific challenge header
                    if (StringExtensions.hasPrefixInHeader(challengeHeader, AuthenticationConstants.Broker.CHALLENGE_RESPONSE_TYPE)) {
                        final HttpEvent challengeHttpEvent = startHttpEvent();
                        challengeHttpEvent.setHttpPath(authority);
                        Logger.v(TAG + methodName, "Received pkeyAuth device challenge.");
                        ChallengeResponseBuilder certHandler = new ChallengeResponseBuilder(mJWSBuilder);
                        Logger.v(TAG + methodName, "Processing device challenge.");
                        final ChallengeResponse challengeResponse = certHandler.getChallengeResponseFromHeader(challengeHeader, authority.toString());
                        headers.put(AuthenticationConstants.Broker.CHALLENGE_RESPONSE_HEADER, challengeResponse.getAuthorizationHeaderValue());
                        Logger.v(TAG + methodName, "Sending request with challenge response.");
                        response = mWebRequestHandler.sendPost(authority, headers, requestMessage.getBytes(AuthenticationConstants.ENCODING_UTF8), "application/x-www-form-urlencoded");
                        challengeHttpEvent.setResponseCode(response.getStatusCode());
                        challengeHttpEvent.setCorrelationId(mRequest.getCorrelationId().toString());
                        stopHttpEvent(challengeHttpEvent);
                    }
                } else {
                    throw new AuthenticationException(ADALError.DEVICE_CERTIFICATE_REQUEST_INVALID, "Challenge header is empty", response);
                }
            } else {
                // AAD server returns 401 response for wrong request
                // messages
                Logger.v(TAG + methodName, "401 http status code is returned without authorization header.");
            }
        }
        boolean isBodyEmpty = TextUtils.isEmpty(response.getBody());
        if (!isBodyEmpty) {
            // Protocol related errors will read the error stream and report
            // the error and error description
            Logger.v(TAG + methodName, "Token request does not have exception.");
            try {
                result = processTokenResponse(response, httpEvent);
            } catch (final ServerRespondingWithRetryableException e) {
                result = retry(requestMessage, headers);
                if (result != null) {
                    return result;
                }
                if (mRequest.getIsExtendedLifetimeEnabled()) {
                    Logger.v(TAG + methodName, "WebResponse is not a success due to: " + response.getStatusCode());
                    throw e;
                } else {
                    Logger.v(TAG + methodName, "WebResponse is not a success due to: " + response.getStatusCode());
                    throw new AuthenticationException(ADALError.SERVER_ERROR, "WebResponse is not a success due to: " + response.getStatusCode(), response);
                }
            }
            ClientMetrics.INSTANCE.setLastError(null);
        }
        if (result == null) {
            // non-protocol related error
            String errMessage = isBodyEmpty ? "Status code:" + response.getStatusCode() : response.getBody();
            Logger.e(TAG + methodName, ADALError.SERVER_ERROR.getDescription(), errMessage, ADALError.SERVER_ERROR);
            throw new AuthenticationException(ADALError.SERVER_ERROR, errMessage, response);
        } else {
            ClientMetrics.INSTANCE.setLastErrorCodes(result.getErrorCodes());
        }
    } catch (final UnsupportedEncodingException e) {
        ClientMetrics.INSTANCE.setLastError(null);
        Logger.e(TAG + methodName, ADALError.ENCODING_IS_NOT_SUPPORTED.getDescription(), e.getMessage(), ADALError.ENCODING_IS_NOT_SUPPORTED, e);
        throw e;
    } catch (final SocketTimeoutException e) {
        result = retry(requestMessage, headers);
        if (result != null) {
            return result;
        }
        ClientMetrics.INSTANCE.setLastError(null);
        if (mRequest.getIsExtendedLifetimeEnabled()) {
            Logger.e(TAG + methodName, ADALError.SERVER_ERROR.getDescription(), e.getMessage(), ADALError.SERVER_ERROR, e);
            throw new ServerRespondingWithRetryableException(e.getMessage(), e);
        } else {
            Logger.e(TAG + methodName, ADALError.SERVER_ERROR.getDescription(), e.getMessage(), ADALError.SERVER_ERROR, e);
            throw e;
        }
    } catch (final IOException e) {
        ClientMetrics.INSTANCE.setLastError(null);
        Logger.e(TAG + methodName, ADALError.SERVER_ERROR.getDescription(), e.getMessage(), ADALError.SERVER_ERROR, e);
        throw e;
    } finally {
        ClientMetrics.INSTANCE.endClientMetricsRecord(ClientMetricsEndpointType.TOKEN, mRequest.getCorrelationId());
    }
    return result;
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) URL(java.net.URL) HttpWebResponse(com.microsoft.identity.common.adal.internal.net.HttpWebResponse) ChallengeResponse(com.microsoft.aad.adal.ChallengeResponseBuilder.ChallengeResponse) SocketTimeoutException(java.net.SocketTimeoutException)

Example 17 with HttpWebResponse

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

the class WebFingerMetadataRequestor method requestMetadata.

@Override
WebFingerMetadata requestMetadata(final WebFingerMetadataRequestParameters webFingerMetadataRequestParameters) throws AuthenticationException {
    final URL domain = webFingerMetadataRequestParameters.getDomain();
    final DRSMetadata drsMetadata = webFingerMetadataRequestParameters.getDrsMetadata();
    Logger.i(TAG, "Validating authority for auth endpoint. ", "Auth endpoint: " + domain.toString());
    try {
        // create the URL
        URL webFingerUrl = buildWebFingerUrl(domain, drsMetadata);
        // make the request
        final HttpWebResponse webResponse = getWebrequestHandler().sendGet(webFingerUrl, new HashMap<String, String>());
        // get the status code
        final int statusCode = webResponse.getStatusCode();
        if (HttpURLConnection.HTTP_OK != statusCode) {
            // non-200 codes mean not valid/trusted
            throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_INSTANCE);
        }
        // parse the response
        return parseMetadata(webResponse);
    } catch (IOException e) {
        throw new AuthenticationException(ADALError.IO_EXCEPTION, "Unexpected error", e);
    }
}
Also used : IOException(java.io.IOException) URL(java.net.URL) HttpWebResponse(com.microsoft.identity.common.adal.internal.net.HttpWebResponse)

Example 18 with HttpWebResponse

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

the class AuthenticationActivityUnitTest method setMockWebResponse.

private MockWebRequestHandler setMockWebResponse() throws NoSuchFieldException, IllegalAccessException {
    MockWebRequestHandler webrequest = new MockWebRequestHandler();
    String idToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiJlNzBiMTE1ZS1hYzBhLTQ4MjMtODVkYS04ZjRiN2I0ZjAwZTYiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC8zMGJhYTY2Ni04ZGY4LTQ4ZTctOTdlNi03N2NmZDA5OTU5NjMvIiwibmJmIjoxMzc2NDI4MzEwLCJleHAiOjEzNzY0NTcxMTAsInZlciI6IjEuMCIsInRpZCI6IjMwYmFhNjY2LThkZjgtNDhlNy05N2U2LTc3Y2ZkMDk5NTk2MyIsIm9pZCI6IjRmODU5OTg5LWEyZmYtNDExZS05MDQ4LWMzMjIyNDdhYzYyYyIsInVwbiI6ImFkbWluQGFhbHRlc3RzLm9ubWljcm9zb2Z0LmNvbSIsInVuaXF1ZV9uYW1lIjoiYWRtaW5AYWFsdGVzdHMub25taWNyb3NvZnQuY29tIiwic3ViIjoiVDU0V2hGR1RnbEJMN1VWYWtlODc5UkdhZEVOaUh5LXNjenNYTmFxRF9jNCIsImZhbWlseV9uYW1lIjoiU2VwZWhyaSIsImdpdmVuX25hbWUiOiJBZnNoaW4ifQ.";
    String json = "{\"id_token\":" + idToken + ",\"access_token\":\"TokentestBroker\",\"token_type\":\"Bearer\",\"expires_in\":\"28799\",\"expires_on\":\"1368768616\",\"refresh_token\":\"refresh112\",\"scope\":\"*\"}";
    ReflectionUtils.setFieldValue(mActivityRule.getActivity(), "mWebRequestHandler", webrequest);
    webrequest.setReturnResponse(new HttpWebResponse(HttpURLConnection.HTTP_OK, json, null));
    return webrequest;
}
Also used : HttpWebResponse(com.microsoft.identity.common.adal.internal.net.HttpWebResponse)

Example 19 with HttpWebResponse

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

the class DRSMetadataRequestorTests method testParseMetadata.

@Test
public void testParseMetadata() throws AuthenticationException {
    HttpWebResponse mockWebResponse = Mockito.mock(HttpWebResponse.class);
    Mockito.when(mockWebResponse.getBody()).thenReturn(RESPONSE);
    DRSMetadata metadata = new DRSMetadataRequestor().parseMetadata(mockWebResponse);
    assertEquals(TEST_ADFS, metadata.getIdentityProviderService().getPassiveAuthEndpoint());
}
Also used : HttpWebResponse(com.microsoft.identity.common.adal.internal.net.HttpWebResponse) Test(org.junit.Test)

Example 20 with HttpWebResponse

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

the class AcquireTokenSilentHandlerTest method testTokenPresentForPassedInAuthorityAndOtherAliasedHost.

/**
 * If a token is not present for preferred_cache, but available for the developer specified authority, as well as other alias,
 * the developer specified authority token is used.
 */
@Test
public void testTokenPresentForPassedInAuthorityAndOtherAliasedHost() throws IOException, JSONException {
    final FileMockContext mockContext = new FileMockContext(getContext());
    final ITokenCacheStore mockedCache = new DefaultTokenCacheStore(getContext());
    clearCache(mockedCache);
    updateAuthorityMetadataCache();
    // insert token with authority as other aliased host
    final String resource = "resource";
    final String clientId = "clientId";
    // Add regular RT item without RT in the cache
    final String aliasedAuthority = "https://test.alias/test.onmicrosoft.com";
    final String rtForAliashedHost = "rt with aliased authority";
    final TokenCacheItem rtTokenCacheItem = Util.getTokenCacheItem(aliasedAuthority, resource, clientId, TEST_IDTOKEN_USERID, TEST_IDTOKEN_UPN);
    rtTokenCacheItem.setRefreshToken(rtForAliashedHost);
    rtTokenCacheItem.setIsMultiResourceRefreshToken(false);
    saveTokenIntoCache(mockedCache, rtTokenCacheItem);
    // insert token with authority as aliased host
    final String testHostAuthority = "https://test.host/test.onmicrosoft.com";
    final String rtForTestHost = "rt for test host";
    final TokenCacheItem itemWithTestHost = Util.getTokenCacheItem(testHostAuthority, resource, clientId, TEST_IDTOKEN_USERID, TEST_IDTOKEN_UPN);
    itemWithTestHost.setRefreshToken(rtForTestHost);
    saveTokenIntoCache(mockedCache, itemWithTestHost);
    final AuthenticationRequest authenticationRequest = getAuthenticationRequest(testHostAuthority, resource, clientId, false);
    authenticationRequest.setUserIdentifierType(UserIdentifierType.UniqueId);
    authenticationRequest.setUserId(TEST_IDTOKEN_USERID);
    final AcquireTokenSilentHandler acquireTokenSilentHandler = getAcquireTokenHandler(mockContext, authenticationRequest, mockedCache);
    // inject mocked web request handler
    final IWebRequestHandler mockedWebRequestHandler = Mockito.mock(WebRequestHandler.class);
    // MRRT request fails with invalid_grant
    Mockito.when(mockedWebRequestHandler.sendPost(Mockito.any(URL.class), Mockito.<String, String>anyMap(), AdditionalMatchers.aryEq(Util.getPostMessage(rtForTestHost, clientId, resource)), Mockito.anyString())).thenReturn(new HttpWebResponse(HttpURLConnection.HTTP_OK, Util.getSuccessTokenResponse(false, false), null));
    acquireTokenSilentHandler.setWebRequestHandler(mockedWebRequestHandler);
    try {
        final AuthenticationResult result = acquireTokenSilentHandler.getAccessToken();
        assertNotNull(result);
        assertNotNull(result.getAccessToken());
    } catch (final AuthenticationException e) {
        fail();
    }
    Mockito.verify(mockedWebRequestHandler, Mockito.times(1)).sendPost(Mockito.any(URL.class), Mockito.<String, String>anyMap(), AdditionalMatchers.aryEq(Util.getPostMessage(rtForTestHost, clientId, resource)), Mockito.anyString());
    // verify token items
    final String preferredCacheLocation = "https://preferred.cache/test.onmicrosoft.com";
    assertNotNull(mockedCache.getItem(CacheKey.createCacheKeyForRTEntry(preferredCacheLocation, resource, clientId, TEST_IDTOKEN_USERID)));
    assertNotNull(mockedCache.getItem(CacheKey.createCacheKeyForRTEntry(preferredCacheLocation, resource, clientId, TEST_IDTOKEN_UPN)));
    clearCache(mockedCache);
}
Also used : IWebRequestHandler(com.microsoft.identity.common.adal.internal.net.IWebRequestHandler) URL(java.net.URL) HttpWebResponse(com.microsoft.identity.common.adal.internal.net.HttpWebResponse) SmallTest(androidx.test.filters.SmallTest) Test(org.junit.Test)

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