Search in sources :

Example 1 with StorageHelper

use of com.microsoft.identity.common.adal.internal.cache.StorageHelper in project microsoft-authentication-library-common-for-android by AzureAD.

the class TestUtils method getEncryptedSharedPreferences.

/**
 * Return a SharedPreferences instance that works with stores containing encrypted values.
 *
 * @param sharedPrefName the name of the shared preferences file.
 * @return A SharedPreferences that decrypts and encrypts the values.
 */
public static SharedPreferencesFileManager getEncryptedSharedPreferences(final String sharedPrefName) {
    final Context context = ApplicationProvider.getApplicationContext();
    final StorageHelper storageHelper = new StorageHelper(context);
    final SharedPreferencesFileManager barePreferences = SharedPreferencesFileManager.getSharedPreferences(context, sharedPrefName, storageHelper);
    return barePreferences;
}
Also used : Context(android.content.Context) SharedPreferencesFileManager(com.microsoft.identity.common.internal.cache.SharedPreferencesFileManager) StorageHelper(com.microsoft.identity.common.adal.internal.cache.StorageHelper)

Example 2 with StorageHelper

use of com.microsoft.identity.common.adal.internal.cache.StorageHelper in project microsoft-authentication-library-common-for-android by AzureAD.

the class BrokerOAuth2TokenCache method initializeProcessUidCache.

private MsalOAuth2TokenCache initializeProcessUidCache(@NonNull final Context context, final int bindingProcessUid) {
    final String methodName = ":initializeProcessUidCache";
    Logger.verbose(TAG + methodName, "Initializing uid cache.");
    if (null != mDelegate) {
        Logger.warn(TAG + methodName, "Using swapped delegate cache.");
        return mDelegate.getTokenCache(context, bindingProcessUid);
    }
    final IStorageHelper storageHelper = new StorageHelper(context);
    final ISharedPreferencesFileManager sharedPreferencesFileManager = SharedPreferencesFileManager.getSharedPreferences(context, SharedPreferencesAccountCredentialCache.getBrokerUidSequesteredFilename(bindingProcessUid), storageHelper);
    return getTokenCache(context, sharedPreferencesFileManager, false);
}
Also used : IStorageHelper(com.microsoft.identity.common.adal.internal.cache.IStorageHelper) StorageHelper(com.microsoft.identity.common.adal.internal.cache.StorageHelper) IStorageHelper(com.microsoft.identity.common.adal.internal.cache.IStorageHelper)

Example 3 with StorageHelper

use of com.microsoft.identity.common.adal.internal.cache.StorageHelper in project microsoft-authentication-library-common-for-android by AzureAD.

the class MsalOAuth2TokenCache method create.

/**
 * Factory method for creating an instance of MsalOAuth2TokenCache
 * <p>
 * NOTE: Currently this is configured for AAD v2 as the only IDP
 *
 * @param context The Application Context
 * @return An instance of the MsalOAuth2TokenCache.
 */
public static MsalOAuth2TokenCache<MicrosoftStsOAuth2Strategy, MicrosoftStsAuthorizationRequest, MicrosoftStsTokenResponse, MicrosoftAccount, MicrosoftRefreshToken> create(@NonNull final Context context) {
    final String methodName = ":create";
    Logger.verbose(TAG + methodName, "Creating MsalOAuth2TokenCache");
    // Init the new-schema cache
    final ICacheKeyValueDelegate cacheKeyValueDelegate = new CacheKeyValueDelegate();
    final IStorageHelper storageHelper = new StorageHelper(context);
    final ISharedPreferencesFileManager sharedPreferencesFileManager = SharedPreferencesFileManager.getSharedPreferences(context, DEFAULT_ACCOUNT_CREDENTIAL_SHARED_PREFERENCES, storageHelper);
    final IAccountCredentialCache accountCredentialCache = new SharedPreferencesAccountCredentialCache(cacheKeyValueDelegate, sharedPreferencesFileManager);
    final MicrosoftStsAccountCredentialAdapter accountCredentialAdapter = new MicrosoftStsAccountCredentialAdapter();
    return new MsalOAuth2TokenCache<>(context, accountCredentialCache, accountCredentialAdapter);
}
Also used : IStorageHelper(com.microsoft.identity.common.adal.internal.cache.IStorageHelper) StorageHelper(com.microsoft.identity.common.adal.internal.cache.StorageHelper) IStorageHelper(com.microsoft.identity.common.adal.internal.cache.IStorageHelper)

Example 4 with StorageHelper

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

the class AuthenticationActivity method onCreate.

// Turn off the deprecation warning for CookieSyncManager.  It was deprecated in API 21, but
// is still necessary for API level 20 and below.
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(final Bundle savedInstanceState) {
    final String methodName = ":onCreate";
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_authentication);
    mWebView = findViewById(R.id.authentication_activity_webView);
    mSpinner = findViewById(R.id.authentication_activity_progressBar);
    CookieSyncManager.createInstance(getApplicationContext());
    CookieSyncManager.getInstance().sync();
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    Logger.verbose(TAG + methodName, "AuthenticationActivity was created.");
    // Get the message from the intent
    mAuthRequest = getAuthenticationRequestFromIntent(getIntent());
    if (mAuthRequest == null) {
        Logger.warn(TAG + methodName, "Intent for Authentication Activity doesn't have the request details, returning to caller");
        final Intent resultIntent = new Intent();
        resultIntent.putExtra(RESPONSE_ERROR_CODE, WEBVIEW_INVALID_REQUEST);
        resultIntent.putExtra(RESPONSE_ERROR_MESSAGE, "Intent does not have request details");
        returnToCaller(BROWSER_CODE_ERROR, resultIntent);
        return;
    }
    if (mAuthRequest.getAuthority() == null || mAuthRequest.getAuthority().isEmpty()) {
        returnError(ADALError.ARGUMENT_EXCEPTION, ACCOUNT_AUTHORITY);
        return;
    }
    if (mAuthRequest.getResource() == null || mAuthRequest.getResource().isEmpty()) {
        returnError(ADALError.ARGUMENT_EXCEPTION, ACCOUNT_RESOURCE);
        return;
    }
    if (mAuthRequest.getClientId() == null || mAuthRequest.getClientId().isEmpty()) {
        returnError(ADALError.ARGUMENT_EXCEPTION, ACCOUNT_CLIENTID_KEY);
        return;
    }
    if (mAuthRequest.getRedirectUri() == null || mAuthRequest.getRedirectUri().isEmpty()) {
        returnError(ADALError.ARGUMENT_EXCEPTION, ACCOUNT_REDIRECT);
        return;
    }
    mRedirectUrl = mAuthRequest.getRedirectUri();
    Telemetry.getInstance().startEvent(mAuthRequest.getTelemetryRequestId(), EventStrings.UI_EVENT);
    mUIEvent = new UIEvent(EventStrings.UI_EVENT);
    mUIEvent.setRequestId(mAuthRequest.getTelemetryRequestId());
    mUIEvent.setCorrelationId(mAuthRequest.getCorrelationId().toString());
    // Disable hardware acceleration in WebView if needed
    if (!AuthenticationSettings.INSTANCE.getDisableWebViewHardwareAcceleration()) {
        mWebView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
        Logger.warn(TAG + methodName, "Hardware acceleration is disabled in WebView");
    }
    mStartUrl = "about:blank";
    try {
        final Oauth2 oauth = new Oauth2(mAuthRequest);
        mStartUrl = oauth.getCodeRequestUrl();
    } catch (UnsupportedEncodingException e) {
        Logger.error(TAG + methodName, "Encoding format is not supported. ", e);
        final Intent resultIntent = new Intent();
        resultIntent.putExtra(RESPONSE_REQUEST_INFO, mAuthRequest);
        returnToCaller(BROWSER_CODE_ERROR, resultIntent);
        return;
    }
    // Create the broadcast receiver for cancel
    Logger.verbose(TAG + methodName, "Init broadcastReceiver with request. " + "RequestId:" + mAuthRequest.getRequestId());
    Logger.verbosePII(TAG + methodName, mAuthRequest.getLogInfo());
    mReceiver = new ActivityBroadcastReceiver();
    mReceiver.mWaitingRequestId = mAuthRequest.getRequestId();
    LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(ACTION_CANCEL));
    String userAgent = mWebView.getSettings().getUserAgentString();
    mWebView.getSettings().setUserAgentString(userAgent + CLIENT_TLS_NOT_SUPPORTED);
    userAgent = mWebView.getSettings().getUserAgentString();
    Logger.verbosePII(TAG + methodName, "UserAgent:" + userAgent);
    if (isBrokerRequest(getIntent())) {
        // This activity is started from calling app and running in
        // Authenticator's process
        mCallingPackage = getCallingPackage();
        if (mCallingPackage == null) {
            Logger.verbose(TAG + methodName, "Calling package is null, startActivityForResult is not used to call this activity");
            final Intent resultIntent = new Intent();
            resultIntent.putExtra(RESPONSE_ERROR_CODE, WEBVIEW_INVALID_REQUEST);
            resultIntent.putExtra(RESPONSE_ERROR_MESSAGE, "startActivityForResult is not used to call this activity");
            returnToCaller(BROWSER_CODE_ERROR, resultIntent);
            return;
        }
        Logger.info(TAG + methodName, "It is a broker request for package:" + mCallingPackage);
        mAccountAuthenticatorResponse = getIntent().getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
        if (mAccountAuthenticatorResponse != null) {
            mAccountAuthenticatorResponse.onRequestContinued();
        }
        final PackageHelper info = new PackageHelper(AuthenticationActivity.this);
        mCallingPackage = getCallingPackage();
        mCallingUID = info.getUIDForPackage(mCallingPackage);
        final String signatureDigest = info.getCurrentSignatureForPackage(mCallingPackage);
        mStartUrl = getBrokerStartUrl(mStartUrl, mCallingPackage, signatureDigest);
        if (!isCallerBrokerInstaller()) {
            Logger.verbose(TAG + methodName, "Caller needs to be verified using special redirectUri");
            mRedirectUrl = PackageHelper.getBrokerRedirectUrl(mCallingPackage, signatureDigest);
        }
        Logger.verbosePII(TAG + methodName, "Broker redirectUrl: " + mRedirectUrl + " The calling package is: " + mCallingPackage + " Signature hash for calling package is: " + signatureDigest + " Current context package: " + getPackageName() + " Start url: " + mStartUrl);
    } else {
        Logger.verbose(TAG + methodName, "Non-broker request for package " + getCallingPackage());
        Logger.verbosePII(TAG + methodName, "Start url: " + mStartUrl);
    }
    mRegisterReceiver = false;
    final String postUrl = mStartUrl;
    Logger.infoPII(TAG + methodName, "Device info:" + android.os.Build.VERSION.RELEASE + " " + android.os.Build.MANUFACTURER + android.os.Build.MODEL);
    mStorageHelper = new StorageHelper(getApplicationContext());
    setupWebView();
    // Also log correlation id
    if (mAuthRequest.getCorrelationId() == null) {
        Logger.verbose(TAG + methodName, "Null correlation id in the request.");
    } else {
        Logger.verbose(TAG + methodName, "Correlation id for request sent is:" + mAuthRequest.getCorrelationId().toString());
    }
    if (savedInstanceState == null) {
        mWebView.post(new Runnable() {

            @Override
            public void run() {
                // load blank first to avoid error for not loading webview
                Logger.verbose(TAG + methodName, "Launching webview for acquiring auth code.");
                mWebView.loadUrl("about:blank");
                mWebView.loadUrl(postUrl);
            }
        });
    } else {
        Logger.verbose(TAG + methodName, "Reuse webview");
    }
}
Also used : IntentFilter(android.content.IntentFilter) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Intent(android.content.Intent) StorageHelper(com.microsoft.identity.common.adal.internal.cache.StorageHelper) CookieManager(android.webkit.CookieManager) SuppressLint(android.annotation.SuppressLint)

Example 5 with StorageHelper

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

the class TokenCacheAccessorTests method testMsalCacheIsUpdated.

/**
 * This test asserts that the MSAL cache is updated by writes to the ADAL cache.
 * The ADAL class {@link TokenCacheAccessor} receives an instance of the cache supplied by the host
 * app. If the caller has set an instance of {@link DefaultTokenCacheStore}, then ADAL should write a
 * matching ID, AT, and Account to the MSAL cache for migration/SSO purposes.
 */
@Test
public void testMsalCacheIsUpdated() throws ServiceException, MalformedURLException {
    // Assert our cache is configured for WW
    assertEquals(WORLDWIDE_AUTHORITY, mTokenCacheAccessor.getAuthorityUrlWithPreferredCache());
    // Create a request to WW
    final AuthenticationRequest request = new AuthenticationRequest(WORLDWIDE_AUTHORITY, RESOURCE, CLIENT, REDIRECT, "", PromptBehavior.Auto, "", UUID.randomUUID(), false, null);
    final AuthenticationResult result = new AuthenticationResult(MOCK_AT, MOCK_RT, new Date(System.currentTimeMillis() + (3600 * 1000)), false, new UserInfo(USERID_1, GIVEN_NAME, FAMILY_NAME, IDENTITY, USERID_1), TID, MOCK_ID_TOKEN_WITH_CLAIMS, null, CLIENT);
    result.setAuthority(WORLDWIDE_AUTHORITY);
    result.setClientInfo(new ClientInfo(MOCK_CLIENT_INFO));
    result.setResponseReceived(System.currentTimeMillis());
    result.setExpiresIn(TimeUnit.HOURS.toSeconds(1));
    // Save this to the cache
    mTokenCacheAccessor.updateTokenCache(request, result);
    assertEquals(WORLDWIDE_AUTHORITY, mTokenCacheAccessor.getAuthorityUrlWithPreferredCache());
    // Assert the MSAL replicated cache now contains the account & RT
    final IAccountCredentialCache accountCredentialCache = new SharedPreferencesAccountCredentialCache(new CacheKeyValueDelegate(), new SharedPreferencesFileManager(mContext, DEFAULT_ACCOUNT_CREDENTIAL_SHARED_PREFERENCES, new StorageHelper(mContext)));
    final MsalOAuth2TokenCache msalCache = new MsalOAuth2TokenCache(mContext, accountCredentialCache, new MicrosoftStsAccountCredentialAdapter());
    // Assert the presence of the account
    final AccountRecord accountRecord = msalCache.getAccount(LOGIN_WINDOWS_NET, CLIENT, MOCK_UID + "." + MOCK_UTID, MOCK_UTID);
    Assert.assertNotNull(accountRecord);
    // The RT
    final ICacheRecord cacheRecord = msalCache.load(CLIENT, null, accountRecord, new BearerAuthenticationSchemeInternal());
    final IdTokenRecord idToken = cacheRecord.getIdToken();
    final RefreshTokenRecord refreshToken = cacheRecord.getRefreshToken();
    Assert.assertEquals(MOCK_UTID, idToken.getRealm());
    Assert.assertEquals(CLIENT, idToken.getClientId());
    Assert.assertEquals(accountRecord.getHomeAccountId(), idToken.getHomeAccountId());
    Assert.assertEquals(LOGIN_WINDOWS_NET, refreshToken.getEnvironment());
    Assert.assertEquals(CLIENT, refreshToken.getClientId());
    Assert.assertEquals(accountRecord.getHomeAccountId(), refreshToken.getHomeAccountId());
}
Also used : IdTokenRecord(com.microsoft.identity.common.internal.dto.IdTokenRecord) ICacheRecord(com.microsoft.identity.common.internal.cache.ICacheRecord) BearerAuthenticationSchemeInternal(com.microsoft.identity.common.internal.authscheme.BearerAuthenticationSchemeInternal) SharedPreferencesFileManager(com.microsoft.identity.common.internal.cache.SharedPreferencesFileManager) RefreshTokenRecord(com.microsoft.identity.common.internal.dto.RefreshTokenRecord) MsalOAuth2TokenCache(com.microsoft.identity.common.internal.cache.MsalOAuth2TokenCache) IAccountCredentialCache(com.microsoft.identity.common.internal.cache.IAccountCredentialCache) Date(java.util.Date) CacheKeyValueDelegate(com.microsoft.identity.common.internal.cache.CacheKeyValueDelegate) MicrosoftStsAccountCredentialAdapter(com.microsoft.identity.common.internal.cache.MicrosoftStsAccountCredentialAdapter) SharedPreferencesAccountCredentialCache(com.microsoft.identity.common.internal.cache.SharedPreferencesAccountCredentialCache) AccountRecord(com.microsoft.identity.common.internal.dto.AccountRecord) StorageHelper(com.microsoft.identity.common.adal.internal.cache.StorageHelper) ClientInfo(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo) Test(org.junit.Test)

Aggregations

StorageHelper (com.microsoft.identity.common.adal.internal.cache.StorageHelper)12 Context (android.content.Context)5 IStorageHelper (com.microsoft.identity.common.adal.internal.cache.IStorageHelper)4 CacheKeyValueDelegate (com.microsoft.identity.common.internal.cache.CacheKeyValueDelegate)4 SharedPreferencesAccountCredentialCache (com.microsoft.identity.common.internal.cache.SharedPreferencesAccountCredentialCache)4 SharedPreferencesFileManager (com.microsoft.identity.common.internal.cache.SharedPreferencesFileManager)3 Test (org.junit.Test)3 IAccountCredentialCache (com.microsoft.identity.common.internal.cache.IAccountCredentialCache)2 AccountRecord (com.microsoft.identity.common.internal.dto.AccountRecord)2 Before (org.junit.Before)2 SuppressLint (android.annotation.SuppressLint)1 Intent (android.content.Intent)1 IntentFilter (android.content.IntentFilter)1 SharedPreferences (android.content.SharedPreferences)1 CookieManager (android.webkit.CookieManager)1 UiThreadTest (androidx.test.annotation.UiThreadTest)1 BearerAuthenticationSchemeInternal (com.microsoft.identity.common.internal.authscheme.BearerAuthenticationSchemeInternal)1 IAccountCredentialAdapter (com.microsoft.identity.common.internal.cache.IAccountCredentialAdapter)1 ICacheKeyValueDelegate (com.microsoft.identity.common.internal.cache.ICacheKeyValueDelegate)1 ICacheRecord (com.microsoft.identity.common.internal.cache.ICacheRecord)1