Search in sources :

Example 6 with JWSBuilder

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);
}
Also used : KeyPair(java.security.KeyPair) RSAPublicKey(java.security.interfaces.RSAPublicKey) Method(java.lang.reflect.Method) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) X509Certificate(java.security.cert.X509Certificate) JWSBuilder(com.microsoft.identity.common.adal.internal.JWSBuilder) Test(org.junit.Test)

Example 7 with JWSBuilder

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());
}
Also used : KeyPair(java.security.KeyPair) RSAPublicKey(java.security.interfaces.RSAPublicKey) IWebRequestHandler(com.microsoft.identity.common.adal.internal.net.IWebRequestHandler) ArrayList(java.util.ArrayList) List(java.util.List) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) X509Certificate(java.security.cert.X509Certificate) URL(java.net.URL) JWSBuilder(com.microsoft.identity.common.adal.internal.JWSBuilder) HttpWebResponse(com.microsoft.identity.common.adal.internal.net.HttpWebResponse) Test(org.junit.Test)

Example 8 with JWSBuilder

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;
}
Also used : IOException(java.io.IOException) JWSBuilder(com.microsoft.identity.common.adal.internal.JWSBuilder)

Example 9 with JWSBuilder

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;
}
Also used : IDeviceCertificate(com.microsoft.identity.common.adal.internal.IDeviceCertificate) HashMap(java.util.HashMap) ClientException(com.microsoft.identity.common.exception.ClientException) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWSBuilder(com.microsoft.identity.common.adal.internal.JWSBuilder)

Aggregations

JWSBuilder (com.microsoft.identity.common.adal.internal.JWSBuilder)9 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)5 KeyPair (java.security.KeyPair)4 X509Certificate (java.security.cert.X509Certificate)4 RSAPublicKey (java.security.interfaces.RSAPublicKey)4 Test (org.junit.Test)4 Method (java.lang.reflect.Method)3 HashMap (java.util.HashMap)3 ChallengeResponse (com.microsoft.aad.adal.ChallengeResponseBuilder.ChallengeResponse)2 IOException (java.io.IOException)2 Intent (android.content.Intent)1 IDeviceCertificate (com.microsoft.identity.common.adal.internal.IDeviceCertificate)1 HttpWebResponse (com.microsoft.identity.common.adal.internal.net.HttpWebResponse)1 IWebRequestHandler (com.microsoft.identity.common.adal.internal.net.IWebRequestHandler)1 ClientException (com.microsoft.identity.common.exception.ClientException)1 URL (java.net.URL)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1