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;
}
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);
}
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);
}
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");
}
}
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());
}
Aggregations