Search in sources :

Example 1 with JWSBuilder

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

the class ChallengeResponseBuilderTests method testGetChallengeResponseFromHeaderPositive.

@Test
public void testGetChallengeResponseFromHeaderPositive() 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 String thumbPrint = "thumbprint23432432";
    final X509Certificate mockCert = mock(X509Certificate.class);
    MockDeviceCertProxy.reset();
    MockDeviceCertProxy.setIsValidIssuer(true);
    MockDeviceCertProxy.setThumbPrint(thumbPrint);
    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
    "getChallengeResponseFromHeader", String.class, String.class);
    final String redirectURI = AuthenticationConstants.Broker.CHALLENGE_RESPONSE_TYPE + " Nonce=\"" + nonce + "\",CertThumbprint=\"ABC\",Version=\"1.0\",Context=\"" + context + "\"";
    // act
    final Object response = m.invoke(handler, redirectURI, submitUrl);
    // assert
    final String authHeaderValue = (String) ReflectionUtils.getFieldValue(response, "mAuthorizationHeaderValue");
    assertTrue(authHeaderValue.contains(String.format("%s AuthToken=\"%s\",Context=\"%s\"", AuthenticationConstants.Broker.CHALLENGE_RESPONSE_TYPE, "signedJwtHere", context)));
}
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 2 with JWSBuilder

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

the class ChallengeResponseBuilderTests method testGetChallengeResponseFromHeaderCertAuthorityPresent.

/**
 * Test for verifying cert authorities could be used to pick up right certificate.
 */
@Test
public void testGetChallengeResponseFromHeaderCertAuthorityPresent() 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
    "getChallengeResponseFromHeader", String.class, String.class);
    final String authorizationHeader = AuthenticationConstants.Broker.CHALLENGE_RESPONSE_TYPE + " Nonce=\"" + nonce + "\",CertAuthorities=\"ABC\",Version=\"1.0\",Context=\"" + context + "\"";
    final Object response = m.invoke(handler, authorizationHeader, submitUrl);
    final String authHeaderValue = (String) ReflectionUtils.getFieldValue(response, // field name
    "mAuthorizationHeaderValue");
    assertTrue(authHeaderValue.contains(String.format("%s AuthToken=\"%s\",Context=\"%s\"", AuthenticationConstants.Broker.CHALLENGE_RESPONSE_TYPE, "signedJwtHere", context)));
}
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 3 with JWSBuilder

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

the class AcquireTokenSilentHandler method acquireTokenWithAssertion.

/**
 * Send token request with grant_type as assertion to token endpoint for getting new access token.
 */
AuthenticationResult acquireTokenWithAssertion() throws AuthenticationException {
    final String methodName = ":acquireTokenWithAssertion";
    Logger.v(TAG + methodName, "Try to get new access token with the provided assertion.", mAuthRequest.getLogInfo(), null);
    // Check if network is available, if not throw exception.
    HttpUtil.throwIfNetworkNotAvailable(mContext);
    final AuthenticationResult result;
    final String samlAssertion = mAuthRequest.getSamlAssertion();
    final String assertionType = mAuthRequest.getAssertionType();
    try {
        final JWSBuilder jwsBuilder = new JWSBuilder();
        final Oauth2 oauthRequest = new Oauth2(mAuthRequest, mWebRequestHandler, jwsBuilder);
        result = oauthRequest.refreshTokenUsingAssertion(samlAssertion, assertionType);
        if (result != null && StringExtensions.isNullOrBlank(result.getRefreshToken())) {
            Logger.w(TAG + methodName, "Refresh token is not returned or empty");
        // we have reached this point because we couldnt find the refresh token/use it
        // so we cant set the refresh token
        }
    } catch (final IOException | AuthenticationException exc) {
        // Server side error or similar
        Logger.e(TAG + methodName, "Error in assertion 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 4 with JWSBuilder

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

the class WebviewHelper method getPreKeyAuthInfo.

/**
 * @param challengeUrl URL from which challenge response is received
 * @return PreKeyAuth class filled in
 * @throws UnsupportedEncodingException on malformed exception
 * @throws AuthenticationException      on parameter validation failure
 */
public PreKeyAuthInfo getPreKeyAuthInfo(String challengeUrl) throws UnsupportedEncodingException, AuthenticationException {
    JWSBuilder jwsBuilder = new JWSBuilder();
    ChallengeResponseBuilder certHandler = new ChallengeResponseBuilder(jwsBuilder);
    final ChallengeResponse challengeResponse = certHandler.getChallengeResponseFromUri(challengeUrl);
    final HashMap<String, String> headers = new HashMap<String, String>();
    headers.put(AuthenticationConstants.Broker.CHALLENGE_RESPONSE_HEADER, challengeResponse.getAuthorizationHeaderValue());
    String loadUrl = challengeResponse.getSubmitUrl();
    HashMap<String, String> parameters = StringExtensions.getUrlParameters(challengeResponse.getSubmitUrl());
    Logger.i(TAG, "Get submit url. ", "SubmitUrl:" + challengeResponse.getSubmitUrl());
    if (!parameters.containsKey(AuthenticationConstants.OAuth2.CLIENT_ID)) {
        loadUrl = loadUrl + "?" + mOauth.getAuthorizationEndpointQueryParameters();
    }
    return new PreKeyAuthInfo(headers, loadUrl);
}
Also used : HashMap(java.util.HashMap) JWSBuilder(com.microsoft.identity.common.adal.internal.JWSBuilder) ChallengeResponse(com.microsoft.aad.adal.ChallengeResponseBuilder.ChallengeResponse)

Example 5 with JWSBuilder

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

the class BasicWebViewClient method shouldOverrideUrlLoading.

@Override
public // loaded in the current WebView.
boolean shouldOverrideUrlLoading(final WebView view, final String url) {
    final String methodName = ":shouldOverrideUrlLoading";
    com.microsoft.identity.common.internal.logging.Logger.verbose(TAG + methodName, "Navigation is detected.");
    if (url.startsWith(PKEYAUTH_REDIRECT)) {
        com.microsoft.identity.common.internal.logging.Logger.verbose(TAG + methodName, "Webview detected request for pkeyauth challenge.");
        view.stopLoading();
        setPKeyAuthStatus(true);
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    final ChallengeResponseBuilder certHandler = new ChallengeResponseBuilder(new JWSBuilder());
                    final ChallengeResponse challengeResponse = certHandler.getChallengeResponseFromUri(url);
                    final Map<String, String> headers = new HashMap<>();
                    headers.put(CHALLENGE_RESPONSE_HEADER, challengeResponse.getAuthorizationHeaderValue());
                    postRunnable(new Runnable() {

                        @Override
                        public void run() {
                            String loadUrl = challengeResponse.getSubmitUrl();
                            com.microsoft.identity.common.internal.logging.Logger.verbose(TAG + methodName, "Respond to pkeyAuth challenge.");
                            com.microsoft.identity.common.internal.logging.Logger.verbosePII(TAG + methodName, "Challenge submit url:" + challengeResponse.getSubmitUrl());
                            view.loadUrl(loadUrl, headers);
                        }
                    });
                } catch (final AuthenticationServerProtocolException e) {
                    com.microsoft.identity.common.internal.logging.Logger.errorPII(TAG + methodName, "Argument exception", e);
                    // It should return error code and finish the
                    // activity, so that onActivityResult implementation
                    // returns errors to callback.
                    final Intent resultIntent = new Intent();
                    resultIntent.putExtra(RESPONSE_AUTHENTICATION_EXCEPTION, e);
                    if (mRequest != null) {
                        resultIntent.putExtra(RESPONSE_REQUEST_INFO, mRequest);
                    }
                    sendResponse(BROWSER_CODE_AUTHENTICATION_EXCEPTION, resultIntent);
                } catch (final AuthenticationException e) {
                    com.microsoft.identity.common.internal.logging.Logger.error(TAG + methodName, "Failed to create device certificate response", null);
                    com.microsoft.identity.common.internal.logging.Logger.errorPII(TAG + methodName, "Error", e);
                    // It should return error code and finish the
                    // activity, so that onActivityResult implementation
                    // returns errors to callback.
                    final Intent resultIntent = new Intent();
                    resultIntent.putExtra(RESPONSE_AUTHENTICATION_EXCEPTION, e);
                    if (mRequest != null) {
                        resultIntent.putExtra(RESPONSE_REQUEST_INFO, mRequest);
                    }
                    sendResponse(BROWSER_CODE_AUTHENTICATION_EXCEPTION, resultIntent);
                }
            }
        }).start();
        return true;
    } else if (url.toLowerCase(Locale.US).startsWith(mRedirect.toLowerCase(Locale.US))) {
        com.microsoft.identity.common.internal.logging.Logger.verbose(TAG + methodName, "Navigation starts with the redirect uri.");
        Intent errorIntent = parseError(url);
        if (errorIntent != null) {
            // Catch WEB-UI cancel request
            com.microsoft.identity.common.internal.logging.Logger.info(TAG + methodName, "Sending intent to cancel authentication activity");
            view.stopLoading();
            cancelWebViewRequest(errorIntent);
            return true;
        }
        processRedirectUrl(view, url);
        return true;
    } else if (url.startsWith(BROWSER_EXT_PREFIX)) {
        com.microsoft.identity.common.internal.logging.Logger.verbose(TAG + methodName, "It is an external website request");
        view.stopLoading();
        if (url.contains(AuthenticationConstants.Broker.BROWSER_DEVICE_CA_URL_QUERY_STRING_PARAMETER)) {
            Logger.warn(TAG + methodName, "Failed to launch Company Portal, falling back to browser.");
            openLinkInBrowser(url);
            sendResponse(AuthenticationConstants.UIResponse.BROWSER_CODE_MDM, new Intent());
        } else {
            openLinkInBrowser(url);
            cancelWebViewRequest(null);
        }
        return true;
    } else if (url.startsWith(BROWSER_EXT_INSTALL_PREFIX)) {
        com.microsoft.identity.common.internal.logging.Logger.verbose(TAG + methodName, "It is an install request");
        final HashMap<String, String> parameters = StringExtensions.getUrlParameters(url);
        prepareForBrokerResumeRequest();
        // Having thread sleep for 1 second for calling activity to receive the result from
        // prepareForBrokerResumeRequest, thus the receiver for listening broker result return
        // can be registered. openLinkInBrowser will launch activity for going to
        // playstore and broker app download page which brought the calling activity down
        // in the activity stack.
        final int threadSleepForCallingActivity = 1000;
        try {
            Thread.sleep(threadSleepForCallingActivity);
        } catch (InterruptedException e) {
            com.microsoft.identity.common.internal.logging.Logger.warn(TAG + methodName, "Error occurred when having thread sleeping for 1 second.");
        }
        openLinkInBrowser(parameters.get(INSTALL_URL_KEY));
        view.stopLoading();
        return true;
    }
    return processInvalidUrl(view, url);
}
Also used : HashMap(java.util.HashMap) Intent(android.content.Intent) JWSBuilder(com.microsoft.identity.common.adal.internal.JWSBuilder) ChallengeResponse(com.microsoft.aad.adal.ChallengeResponseBuilder.ChallengeResponse)

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