use of com.microsoft.identity.common.adal.internal.JWSBuilder in project azure-activedirectory-library-for-android by AzureAD.
the class ChallengeResponseBuilderTests method testGetChallengeResponsePositive.
@Test
public void testGetChallengeResponsePositive() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException, NoSuchAlgorithmException, ClientException {
final KeyPair keyPair = getKeyPair();
final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
final RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
final String submitUrl = "http://fs.contoso.com/adfs/services/trust";
final String nonce = "123123-123213-123";
final String context = "ABcdeded";
final X509Certificate mockCert = mock(X509Certificate.class);
MockDeviceCertProxy.reset();
MockDeviceCertProxy.setIsValidIssuer(true);
MockDeviceCertProxy.setPrivateKey(privateKey);
MockDeviceCertProxy.setPublicKey(publicKey);
MockDeviceCertProxy.setCertificate(mockCert);
final JWSBuilder mockJwsBuilder = mock(JWSBuilder.class);
when(mockJwsBuilder.generateSignedJWT(nonce, submitUrl, privateKey, publicKey, mockCert)).thenReturn("signedJwtHere");
final Object handler = getInstance(mockJwsBuilder);
final Method m = ReflectionUtils.getTestMethod(handler, // method name
"getChallengeResponseFromUri", String.class);
final String redirectURI = CERT_REDIRECT + "?Nonce=" + nonce + "&CertAuthorities=ABC&Version=1.0&SubmitUrl=" + submitUrl + "&Context=" + context;
final Object response = m.invoke(handler, redirectURI);
verifyChallengeResponse(response, "signedJwtHere", context, submitUrl);
}
use of com.microsoft.identity.common.adal.internal.JWSBuilder 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.JWSBuilder in project azure-activedirectory-library-for-android by AzureAD.
the class AcquireTokenSilentHandler method acquireTokenWithRefreshToken.
/**
* Send token request with grant_type as refresh_token to token endpoint for getting new access token.
*/
AuthenticationResult acquireTokenWithRefreshToken(final String refreshToken) throws AuthenticationException {
final String methodName = ":acquireTokenWithRefreshToken";
Logger.v(TAG + methodName, "Try to get new access token with the found refresh token.", mAuthRequest.getLogInfo(), null);
// Check if network is available, if not throw exception.
HttpUtil.throwIfNetworkNotAvailable(mContext);
final AuthenticationResult result;
try {
final JWSBuilder jwsBuilder = new JWSBuilder();
final Oauth2 oauthRequest = new Oauth2(mAuthRequest, mWebRequestHandler, jwsBuilder);
result = oauthRequest.refreshToken(refreshToken);
if (result != null && StringExtensions.isNullOrBlank(result.getRefreshToken())) {
Logger.w(TAG + methodName, "Refresh token is not returned or empty");
result.setRefreshToken(refreshToken);
}
} catch (final ServerRespondingWithRetryableException exc) {
Logger.i(TAG + methodName, "The server is not responding after the retry with error code: " + exc.getCode(), "");
final TokenCacheItem accessTokenItem = mTokenCacheAccessor.getStaleToken(mAuthRequest);
if (accessTokenItem != null) {
final AuthenticationResult retryResult = AuthenticationResult.createExtendedLifeTimeResult(accessTokenItem);
Logger.i(TAG + methodName, "The result with stale access token is returned.", "");
return retryResult;
}
Logger.e(TAG + methodName, "Error in refresh token for request. ", "Request: " + mAuthRequest.getLogInfo() + " " + ExceptionExtensions.getExceptionMessage(exc) + " " + Log.getStackTraceString(exc), ADALError.AUTH_FAILED_NO_TOKEN, null);
throw new AuthenticationException(ADALError.AUTH_FAILED_NO_TOKEN, ExceptionExtensions.getExceptionMessage(exc), new AuthenticationException(ADALError.SERVER_ERROR, exc.getMessage(), exc));
} catch (final IOException | AuthenticationException exc) {
// Server side error or similar
Logger.e(TAG + methodName, "Error in refresh token for request.", "Request: " + mAuthRequest.getLogInfo() + " " + ExceptionExtensions.getExceptionMessage(exc) + " " + Log.getStackTraceString(exc), ADALError.AUTH_FAILED_NO_TOKEN, null);
throw new AuthenticationException(ADALError.AUTH_FAILED_NO_TOKEN, ExceptionExtensions.getExceptionMessage(exc), new AuthenticationException(ADALError.SERVER_ERROR, exc.getMessage(), exc));
}
return result;
}
use of com.microsoft.identity.common.adal.internal.JWSBuilder in project microsoft-authentication-library-common-for-android by AzureAD.
the class PKeyAuthChallengeHandler method getChallengeHeader.
public static Map<String, String> getChallengeHeader(final PKeyAuthChallenge pKeyAuthChallenge) throws ClientException {
String authorizationHeaderValue = String.format("%s Context=\"%s\",Version=\"%s\"", AuthenticationConstants.Broker.CHALLENGE_RESPONSE_TYPE, pKeyAuthChallenge.getContext(), pKeyAuthChallenge.getVersion());
// If not device cert exists, alias or private key will not exist on the device
// Suppressing unchecked warnings due to the generic type not provided in the object returned from method getDeviceCertificateProxy
@SuppressWarnings(WarningType.unchecked_warning) Class<IDeviceCertificate> certClazz = (Class<IDeviceCertificate>) AuthenticationSettings.INSTANCE.getDeviceCertificateProxy();
if (certClazz != null) {
IDeviceCertificate deviceCertProxy = getWPJAPIInstance(certClazz);
if (deviceCertProxy.isValidIssuer(pKeyAuthChallenge.getCertAuthorities()) || StringUtil.equalsIgnoreCase(deviceCertProxy.getThumbPrint(), pKeyAuthChallenge.getThumbprint())) {
RSAPrivateKey privateKey = deviceCertProxy.getRSAPrivateKey();
if (privateKey == null) {
throw new ClientException(ErrorStrings.KEY_CHAIN_PRIVATE_KEY_EXCEPTION);
}
final String jwt = (new JWSBuilder()).generateSignedJWT(pKeyAuthChallenge.getNonce(), pKeyAuthChallenge.getSubmitUrl(), privateKey, deviceCertProxy.getRSAPublicKey(), deviceCertProxy.getCertificate());
authorizationHeaderValue = String.format("%s AuthToken=\"%s\",Context=\"%s\",Version=\"%s\"", AuthenticationConstants.Broker.CHALLENGE_RESPONSE_TYPE, jwt, pKeyAuthChallenge.getContext(), pKeyAuthChallenge.getVersion());
Logger.info(TAG, "Receive challenge response. ");
}
}
final Map<String, String> headers = new HashMap<>();
headers.put(AuthenticationConstants.Broker.CHALLENGE_RESPONSE_HEADER, authorizationHeaderValue);
return headers;
}
Aggregations