use of com.microsoft.identity.common.adal.internal.net.HttpWebResponse in project azure-activedirectory-library-for-android by AzureAD.
the class AcquireTokenSilentHandlerTest method testMRRTRequestFailsTryFRT.
/**
* Test if MRRT is not marked as FRT, if the MRRT request fails, we will try with FRT.
*/
@Test
public void testMRRTRequestFailsTryFRT() throws JSONException, IOException {
FileMockContext mockContext = new FileMockContext(getContext());
final ITokenCacheStore mockCache = new DefaultTokenCacheStore(getContext());
mockCache.removeAll();
final String clientId = "clientId";
final String resource = "resource";
// MRRT token Cache Item without FoCI flag
final String mrrtToken = "MRRT Refresh Token";
final TokenCacheItem mrrtTokenCacheItem = Util.getTokenCacheItem(VALID_AUTHORITY, null, clientId, TEST_IDTOKEN_USERID, TEST_IDTOKEN_UPN);
mrrtTokenCacheItem.setRefreshToken(mrrtToken);
mrrtTokenCacheItem.setIsMultiResourceRefreshToken(true);
saveTokenIntoCache(mockCache, mrrtTokenCacheItem);
// FRT token cache item
final TokenCacheItem frtTokenCacheItem = Util.getTokenCacheItem(VALID_AUTHORITY, null, null, TEST_IDTOKEN_USERID, TEST_IDTOKEN_UPN);
final String frtToken = "FRT Refresh Token";
frtTokenCacheItem.setRefreshToken(frtToken);
frtTokenCacheItem.setIsMultiResourceRefreshToken(true);
frtTokenCacheItem.setFamilyClientId(AuthenticationConstants.MS_FAMILY_ID);
saveTokenIntoCache(mockCache, frtTokenCacheItem);
final AuthenticationRequest authenticationRequest = getAuthenticationRequest(VALID_AUTHORITY, resource, clientId, false);
authenticationRequest.setUserIdentifierType(UserIdentifierType.UniqueId);
authenticationRequest.setUserId(TEST_IDTOKEN_USERID);
final AcquireTokenSilentHandler acquireTokenSilentHandler = getAcquireTokenHandler(mockContext, authenticationRequest, mockCache);
// 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(mrrtToken, clientId, resource)), Mockito.anyString())).thenReturn(new HttpWebResponse(HttpURLConnection.HTTP_BAD_REQUEST, Util.getErrorResponseBody("invalid_grant"), null));
// FRT request succeed
Mockito.when(mockedWebRequestHandler.sendPost(Mockito.any(URL.class), Mockito.<String, String>anyMap(), AdditionalMatchers.aryEq(Util.getPostMessage(frtToken, clientId, resource)), Mockito.anyString())).thenReturn(new HttpWebResponse(HttpURLConnection.HTTP_OK, Util.getSuccessTokenResponse(true, true), null));
acquireTokenSilentHandler.setWebRequestHandler(mockedWebRequestHandler);
try {
final AuthenticationResult authResult = acquireTokenSilentHandler.getAccessToken();
assertNotNull(authResult);
assertNull(authResult.getErrorCode());
assertNotNull(authResult.getAccessToken());
assertNotNull(authResult.getRefreshToken());
} catch (final AuthenticationException e) {
fail("Unexpected exception");
}
// Verify post request with MRRT token is executed first, followed by post request with FRT.
Mockito.verify(mockedWebRequestHandler, Mockito.times(1)).sendPost(Mockito.any(URL.class), Mockito.<String, String>anyMap(), AdditionalMatchers.aryEq(Util.getPostMessage(mrrtToken, clientId, resource)), Mockito.anyString());
Mockito.verify(mockedWebRequestHandler, Mockito.times(1)).sendPost(Mockito.any(URL.class), Mockito.<String, String>anyMap(), AdditionalMatchers.aryEq(Util.getPostMessage(frtToken, clientId, resource)), Mockito.anyString());
// Verify cache entry, FRT return token back, should store entries with user in cache.
// FRT token entry
assertNotNull(mockCache.getItem(CacheKey.createCacheKeyForFRT(VALID_AUTHORITY, "familyClientId", TEST_IDTOKEN_USERID)));
assertNotNull(mockCache.getItem(CacheKey.createCacheKeyForFRT(VALID_AUTHORITY, "familyClientId", TEST_IDTOKEN_UPN)));
// MRRT token entry
assertNotNull(mockCache.getItem(CacheKey.createCacheKeyForMRRT(VALID_AUTHORITY, clientId, TEST_IDTOKEN_USERID)));
assertNotNull(mockCache.getItem(CacheKey.createCacheKeyForMRRT(VALID_AUTHORITY, clientId, TEST_IDTOKEN_UPN)));
// RT entry
assertNotNull(mockCache.getItem(CacheKey.createCacheKeyForRTEntry(VALID_AUTHORITY, resource, clientId, TEST_IDTOKEN_USERID)));
assertNotNull(mockCache.getItem(CacheKey.createCacheKeyForRTEntry(VALID_AUTHORITY, resource, clientId, TEST_IDTOKEN_UPN)));
clearCache(mockCache);
}
use of com.microsoft.identity.common.adal.internal.net.HttpWebResponse in project azure-activedirectory-library-for-android by AzureAD.
the class AcquireTokenSilentHandlerTest method testFRTSuccess.
/**
* Make sure if we acquire token for a client id, and if we already have a family token item in cache, we use that
* refresh token.
*/
@Test
public void testFRTSuccess() throws IOException, JSONException {
FileMockContext mockContext = new FileMockContext(getContext());
final ITokenCacheStore mockCache = new DefaultTokenCacheStore(mockContext);
// note: if only FRT exists, cache key will be hard-coded to 1
final TokenCacheItem frTokenCacheItem = getTokenCacheItemWithFoCI(TEST_IDTOKEN_USERID, TEST_IDTOKEN_UPN, AuthenticationConstants.MS_FAMILY_ID);
saveTokenIntoCache(mockCache, frTokenCacheItem);
addAzureADCloudForValidAuthority();
final String resource = "resource";
final String clientId = "clientId";
final AuthenticationRequest authenticationRequest = getAuthenticationRequest(VALID_AUTHORITY, resource, clientId, false);
authenticationRequest.setUserIdentifierType(UserIdentifierType.UniqueId);
authenticationRequest.setUserId(TEST_IDTOKEN_USERID);
final AcquireTokenSilentHandler acquireTokenSilentHandler = getAcquireTokenHandler(mockContext, authenticationRequest, mockCache);
// inject mocked web request handler
final IWebRequestHandler mockedWebRequestHandler = Mockito.mock(WebRequestHandler.class);
Mockito.when(mockedWebRequestHandler.sendPost(Mockito.any(URL.class), Mockito.<String, String>anyMap(), Mockito.any(byte[].class), Mockito.anyString())).thenReturn(new HttpWebResponse(HttpURLConnection.HTTP_OK, Util.getSuccessTokenResponse(true, true), null));
acquireTokenSilentHandler.setWebRequestHandler(mockedWebRequestHandler);
try {
final AuthenticationResult authResult = acquireTokenSilentHandler.getAccessToken();
assertNotNull(authResult);
assertEquals("Returned assess token is not as expected.", "I am a new access token", authResult.getAccessToken());
assertEquals("Returned refresh token is not as expected", "I am a new refresh token", authResult.getRefreshToken());
assertEquals("Returned id token is not as expected.", TEST_IDTOKEN, authResult.getIdToken());
} catch (AuthenticationException e) {
fail("Unexpected exception");
}
assertNotNull(mockCache.getItem(CacheKey.createCacheKeyForFRT(VALID_AUTHORITY, "familyClientId", TEST_IDTOKEN_USERID)));
assertNotNull(mockCache.getItem(CacheKey.createCacheKeyForFRT(VALID_AUTHORITY, "familyClientId", TEST_IDTOKEN_UPN)));
// MRRT token entry
assertNotNull(mockCache.getItem(CacheKey.createCacheKeyForMRRT(VALID_AUTHORITY, clientId, TEST_IDTOKEN_USERID)));
assertNotNull(mockCache.getItem(CacheKey.createCacheKeyForMRRT(VALID_AUTHORITY, clientId, TEST_IDTOKEN_UPN)));
// RT entry
assertNotNull(mockCache.getItem(CacheKey.createCacheKeyForRTEntry(VALID_AUTHORITY, resource, clientId, TEST_IDTOKEN_USERID)));
assertNotNull(mockCache.getItem(CacheKey.createCacheKeyForRTEntry(VALID_AUTHORITY, resource, clientId, TEST_IDTOKEN_UPN)));
clearCache(mockCache);
}
use of com.microsoft.identity.common.adal.internal.net.HttpWebResponse in project azure-activedirectory-library-for-android by AzureAD.
the class OauthTests method testRefreshTokenWebResponseDeviceChallengePositive.
@Test
public void testRefreshTokenWebResponseDeviceChallengePositive() throws IOException, ClientException, NoSuchAlgorithmException {
final IWebRequestHandler mockWebRequest = mock(IWebRequestHandler.class);
final KeyPair keyPair = getKeyPair();
final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
final RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
final String nonce = UUID.randomUUID().toString();
final String context = "CookieConABcdeded";
final X509Certificate mockCert = mock(X509Certificate.class);
final String thumbPrint = "thumbPrinttest";
AuthenticationSettings.INSTANCE.setDeviceCertificateProxyClass(MockDeviceCertProxy.class);
MockDeviceCertProxy.reset();
MockDeviceCertProxy.setIsValidIssuer(true);
MockDeviceCertProxy.setThumbPrint(thumbPrint);
MockDeviceCertProxy.setPrivateKey(privateKey);
MockDeviceCertProxy.setPublicKey(publicKey);
final JWSBuilder mockJwsBuilder = mock(JWSBuilder.class);
when(mockJwsBuilder.generateSignedJWT(eq(nonce), any(String.class), eq(privateKey), eq(publicKey), eq(mockCert))).thenReturn("signedJwtHere");
final String challengeHeaderValue = AuthenticationConstants.Broker.CHALLENGE_RESPONSE_TYPE + " Nonce=\"" + nonce + "\", Version=\"1.0\", CertThumbprint=\"" + thumbPrint + "\", Context=\"" + context + "\"";
final String tokenPositiveResponse = "{\"access_token\":\"accessTokenHere\",\"token_type\":\"Bearer\",\"expires_in\":\"28799\",\"expires_on\":\"1368768616\",\"refresh_token\":\"refreshWithDeviceChallenge\",\"scope\":\"*\"}";
final Map<String, List<String>> headers = getHeader(AuthenticationConstants.Broker.CHALLENGE_REQUEST_HEADER, challengeHeaderValue);
final HttpWebResponse responeChallenge = new HttpWebResponse(HttpURLConnection.HTTP_UNAUTHORIZED, null, headers);
final HttpWebResponse responseValid = new HttpWebResponse(HttpURLConnection.HTTP_OK, tokenPositiveResponse, null);
// first call returns 401 and second call returns token
when(mockWebRequest.sendPost(eq(new URL(TEST_AUTHORITY + "/oauth2/token")), Mockito.<String, String>anyMap(), any(byte[].class), eq("application/x-www-form-urlencoded"))).thenReturn(responeChallenge).thenReturn(responseValid);
// send request
final MockAuthenticationCallback testResult = refreshToken(getValidAuthenticationRequest(), mockWebRequest, mockJwsBuilder, "testRefreshToken");
// Verify that callback can receive this error
assertNull("callback does not have error", testResult.getException());
assertNotNull("Result is not null", testResult.getAuthenticationResult());
assertEquals("Same access token", "accessTokenHere", testResult.getAuthenticationResult().getAccessToken());
assertEquals("Same refresh token", "refreshWithDeviceChallenge", testResult.getAuthenticationResult().getRefreshToken());
}
use of com.microsoft.identity.common.adal.internal.net.HttpWebResponse in project azure-activedirectory-library-for-android by AzureAD.
the class OauthTests method testRefreshTokenWebResponseHeader.
@Test
public void testRefreshTokenWebResponseHeader() {
Map<String, List<String>> headers = getHeader("Retry-After", "120");
MockWebRequestHandler mockWebRequest = new MockWebRequestHandler();
mockWebRequest.setReturnResponse(new HttpWebResponse(RETRY_AFTER, "{\"body\":\"not_null\"}", headers));
// send request
MockAuthenticationCallback testResult = refreshToken(getValidAuthenticationRequest(), mockWebRequest, "testRefreshToken");
// Verify that callback can receive this error
assertNotNull("Callback has error", testResult.getException());
assertNotNull(testResult.getException());
assertTrue(testResult.getException() instanceof AuthenticationException);
assertEquals(((AuthenticationException) testResult.getException()).getServiceStatusCode(), RETRY_AFTER);
assertTrue(((AuthenticationException) testResult.getException()).getHttpResponseHeaders().containsKey("Retry-After"));
}
use of com.microsoft.identity.common.adal.internal.net.HttpWebResponse in project azure-activedirectory-library-for-android by AzureAD.
the class OauthTests method testRefreshTokenWebResponsePositive.
@Test
public void testRefreshTokenWebResponsePositive() {
MockWebRequestHandler webrequest = new MockWebRequestHandler();
String json = "{\"access_token\":\"sometokenhere\",\"token_type\":\"Bearer\"," + "\"expires_in\":\"28799\",\"expires_on\":\"1368768616\",\"refresh_token\":" + "\"refreshfasdfsdf435\",\"scope\":\"*\"}";
webrequest.setReturnResponse(new HttpWebResponse(HttpURLConnection.HTTP_OK, json, null));
// send request
MockAuthenticationCallback testResult = refreshToken(getValidAuthenticationRequest(), webrequest, "test");
// Verify that callback can receive this error
assertNull("callback does not have error", testResult.getException());
assertNotNull("Result is not null", testResult.getAuthenticationResult());
assertEquals("Same access token", "sometokenhere", testResult.getAuthenticationResult().getAccessToken());
assertEquals("Same refresh token", "refreshfasdfsdf435", testResult.getAuthenticationResult().getRefreshToken());
}
Aggregations