use of com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo 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());
}
use of com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo in project azure-activedirectory-library-for-android by AzureAD.
the class Oauth2 method processUIResponseParams.
public AuthenticationResult processUIResponseParams(Map<String, String> response) throws AuthenticationException {
final AuthenticationResult result;
// Protocol error related
if (response.containsKey(AuthenticationConstants.OAuth2.ERROR)) {
// Error response from the server
// CorrelationID will be same as in request headers. This is
// retrieved in result in case it was not set.
String correlationInResponse = response.get(AuthenticationConstants.AAD.CORRELATION_ID);
if (!StringExtensions.isNullOrBlank(correlationInResponse)) {
try {
final UUID correlationId = UUID.fromString(correlationInResponse);
Logger.setCorrelationId(correlationId);
} catch (IllegalArgumentException ex) {
Logger.e(TAG, "CorrelationId is malformed: " + correlationInResponse, "", ADALError.CORRELATION_ID_FORMAT);
}
}
Logger.i(TAG, "OAuth2 error:" + response.get(AuthenticationConstants.OAuth2.ERROR), " Description:" + response.get(AuthenticationConstants.OAuth2.ERROR_DESCRIPTION));
result = new AuthenticationResult(response.get(AuthenticationConstants.OAuth2.ERROR), response.get(AuthenticationConstants.OAuth2.ERROR_DESCRIPTION), response.get(AuthenticationConstants.OAuth2.ERROR_CODES));
if (null != response.get(AuthenticationConstants.OAuth2.HTTP_RESPONSE_BODY)) {
HashMap<String, String> responseBody = null;
try {
extractJsonObjects(responseBody, response.get(AuthenticationConstants.OAuth2.HTTP_RESPONSE_BODY));
result.setHttpResponseBody(responseBody);
} catch (final JSONException exception) {
Logger.e(TAG, "Json exception", ExceptionExtensions.getExceptionMessage(exception), ADALError.SERVER_INVALID_JSON_RESPONSE);
}
}
if (null != response.get(AuthenticationConstants.OAuth2.HTTP_RESPONSE_HEADER)) {
HashMap<String, List<String>> responseHeaders = null;
try {
responseHeaders = HashMapExtensions.jsonStringAsMapList(response.get(AuthenticationConstants.OAuth2.HTTP_RESPONSE_HEADER));
result.setHttpResponseHeaders(responseHeaders);
} catch (final JSONException exception) {
Logger.e(TAG, "Json exception", ExceptionExtensions.getExceptionMessage(exception), ADALError.SERVER_INVALID_JSON_RESPONSE);
}
}
if (null != response.get(AuthenticationConstants.OAuth2.HTTP_STATUS_CODE)) {
result.setServiceStatusCode(Integer.parseInt(response.get(AuthenticationConstants.OAuth2.HTTP_STATUS_CODE)));
}
} else if (response.containsKey(AuthenticationConstants.OAuth2.CODE)) {
// The header cloud_instance_host_name points to the right sovereign cloud to use for the given user
// Using this host name we construct the authority that will get the token request and we use this authority
// to save the token in the cache. The app should reinitialize AuthenticationContext with this authority for
// all subsequent requests.
result = new AuthenticationResult(mRequest.getClientId(), response.get(AuthenticationConstants.OAuth2.CODE));
final String cloudInstanceHostName = response.get(AuthenticationConstants.OAuth2.CLOUD_INSTANCE_HOST_NAME);
if (!StringExtensions.isNullOrBlank(cloudInstanceHostName)) {
final URL authorityUrl = StringExtensions.getUrl(mRequest.getAuthority());
final String newAuthorityUrlString = new Uri.Builder().scheme(HTTPS_PROTOCOL_STRING).authority(cloudInstanceHostName).path(authorityUrl.getPath()).build().toString();
setTokenEndpoint(newAuthorityUrlString + DEFAULT_TOKEN_ENDPOINT);
result.setAuthority(newAuthorityUrlString);
}
} else if (response.containsKey(AuthenticationConstants.OAuth2.ACCESS_TOKEN)) {
// Token response
boolean isMultiResourceToken = false;
String expiresIn = response.get(AuthenticationConstants.OAuth2.EXPIRES_IN);
Long expiresInLong;
Calendar expires = new GregorianCalendar();
expiresInLong = (expiresIn == null || expiresIn.isEmpty() ? ((long) AuthenticationConstants.DEFAULT_EXPIRATION_TIME_SEC) : Long.parseLong(expiresIn));
// Compute token expiration
expires.add(Calendar.SECOND, expiresIn == null || expiresIn.isEmpty() ? AuthenticationConstants.DEFAULT_EXPIRATION_TIME_SEC : Integer.parseInt(expiresIn));
final String refreshToken = response.get(AuthenticationConstants.OAuth2.REFRESH_TOKEN);
String resource = null;
if (response.containsKey(AuthenticationConstants.AAD.RESOURCE) && !StringExtensions.isNullOrBlank(refreshToken)) {
isMultiResourceToken = true;
resource = response.get(AuthenticationConstants.AAD.RESOURCE);
}
UserInfo userinfo = null;
String tenantId = null;
String rawIdToken = null;
if (response.containsKey(AuthenticationConstants.OAuth2.ID_TOKEN)) {
// IDtoken is related to Azure AD and returned with token
// response. ADFS does not return that.
rawIdToken = response.get(AuthenticationConstants.OAuth2.ID_TOKEN);
if (!StringExtensions.isNullOrBlank(rawIdToken)) {
Logger.v(TAG, "Id token was returned, parsing id token.");
final IdToken tokenParsed = new IdToken(rawIdToken);
if (tokenParsed != null) {
tenantId = tokenParsed.getTenantId();
userinfo = new UserInfo(tokenParsed);
}
} else {
Logger.v(TAG, "IdToken was not returned from token request.");
}
}
String familyClientId = null;
if (response.containsKey(AuthenticationConstants.OAuth2.ADAL_CLIENT_FAMILY_ID)) {
familyClientId = response.get(AuthenticationConstants.OAuth2.ADAL_CLIENT_FAMILY_ID);
}
ClientInfo clientInfo = null;
if (response.containsKey(AuthenticationConstants.OAuth2.CLIENT_INFO)) {
final String rawClientInfo = response.get(AuthenticationConstants.OAuth2.CLIENT_INFO);
try {
clientInfo = new ClientInfo(rawClientInfo);
} catch (ServiceException e) {
Logger.w(TAG, "ClientInfo decoding/parsing failed.");
}
}
result = new AuthenticationResult(response.get(AuthenticationConstants.OAuth2.ACCESS_TOKEN), refreshToken, expires.getTime(), isMultiResourceToken, userinfo, tenantId, rawIdToken, null, mRequest.getClientId());
result.setResource(resource);
result.setClientInfo(clientInfo);
result.setExpiresIn(expiresInLong);
result.setResponseReceived(System.currentTimeMillis());
if (response.containsKey(AuthenticationConstants.OAuth2.EXT_EXPIRES_IN)) {
final String extendedExpiresIn = response.get(AuthenticationConstants.OAuth2.EXT_EXPIRES_IN);
final Calendar extendedExpires = new GregorianCalendar();
// Compute extended token expiration
extendedExpires.add(Calendar.SECOND, StringExtensions.isNullOrBlank(extendedExpiresIn) ? AuthenticationConstants.DEFAULT_EXPIRATION_TIME_SEC : Integer.parseInt(extendedExpiresIn));
result.setExtendedExpiresOn(extendedExpires.getTime());
}
// Set family client id on authentication result for TokenCacheItem to pick up
result.setFamilyClientId(familyClientId);
} else {
result = null;
}
return result;
}
use of com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo in project microsoft-authentication-library-common-for-android by AzureAD.
the class MicrosoftStsAccountCredentialAdapter method createRefreshToken.
@Override
public RefreshTokenRecord createRefreshToken(final MicrosoftStsOAuth2Strategy strategy, final MicrosoftStsAuthorizationRequest request, final MicrosoftStsTokenResponse response) {
try {
final long cachedAt = getCachedAt();
final ClientInfo clientInfo = new ClientInfo(response.getClientInfo());
final RefreshTokenRecord refreshToken = new RefreshTokenRecord();
// Required
refreshToken.setCredentialType(CredentialType.RefreshToken.name());
refreshToken.setEnvironment(strategy.getIssuerCacheIdentifierFromTokenEndpoint());
refreshToken.setHomeAccountId(SchemaUtil.getHomeAccountId(clientInfo));
refreshToken.setClientId(request.getClientId());
refreshToken.setSecret(response.getRefreshToken());
// Optional
refreshToken.setFamilyId(response.getFamilyId());
refreshToken.setTarget(getTarget(request.getScope(), response.getScope()));
// TODO are these needed? Expected?
// generated @ client side
refreshToken.setCachedAt(String.valueOf(cachedAt));
return refreshToken;
} catch (ServiceException e) {
// TODO handle this properly
throw new RuntimeException(e);
}
}
use of com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo in project microsoft-authentication-library-common-for-android by AzureAD.
the class MicrosoftStsAccountCredentialAdapter method createIdToken.
@Override
public IdTokenRecord createIdToken(final MicrosoftStsOAuth2Strategy strategy, final MicrosoftStsAuthorizationRequest request, final MicrosoftStsTokenResponse response) {
try {
final ClientInfo clientInfo = new ClientInfo(response.getClientInfo());
final IdTokenRecord idToken = new IdTokenRecord();
// Required fields
idToken.setHomeAccountId(SchemaUtil.getHomeAccountId(clientInfo));
idToken.setEnvironment(strategy.getIssuerCacheIdentifierFromTokenEndpoint());
idToken.setRealm(getRealm(strategy, response));
idToken.setCredentialType(SchemaUtil.getCredentialTypeFromVersion(response.getIdToken()));
idToken.setClientId(request.getClientId());
idToken.setSecret(response.getIdToken());
idToken.setAuthority(strategy.getAuthorityFromTokenEndpoint());
return idToken;
} catch (ServiceException e) {
// TODO handle this properly
throw new RuntimeException(e);
}
}
use of com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo in project microsoft-authentication-library-common-for-android by AzureAD.
the class MicrosoftStsAccountCredentialAdapter method createAccessToken.
@Override
public AccessTokenRecord createAccessToken(final MicrosoftStsOAuth2Strategy strategy, final MicrosoftStsAuthorizationRequest request, final MicrosoftStsTokenResponse response) {
try {
final long cachedAt = getCachedAt();
final long expiresOn = getExpiresOn(response);
final ClientInfo clientInfo = new ClientInfo(response.getClientInfo());
final AccessTokenRecord accessToken = new AccessTokenRecord();
// Required fields
accessToken.setCredentialType(getCredentialType(response.getTokenType()));
accessToken.setHomeAccountId(SchemaUtil.getHomeAccountId(clientInfo));
accessToken.setRealm(getRealm(strategy, response));
accessToken.setEnvironment(strategy.getIssuerCacheIdentifierFromTokenEndpoint());
accessToken.setClientId(request.getClientId());
accessToken.setTarget(getTarget(request.getScope(), response.getScope()));
// generated @ client side
accessToken.setCachedAt(String.valueOf(cachedAt));
accessToken.setExpiresOn(String.valueOf(expiresOn));
accessToken.setSecret(response.getAccessToken());
// Optional fields
accessToken.setExtendedExpiresOn(getExtendedExpiresOn(response));
accessToken.setAuthority(strategy.getAuthorityFromTokenEndpoint());
accessToken.setAccessTokenType(response.getTokenType());
// Use case insensitive match - ESTS will not capitalize scheme...
if (SCHEME_POP.equalsIgnoreCase(response.getTokenType())) {
accessToken.setKid(strategy.getDeviceAtPopThumbprint());
}
return accessToken;
} catch (ServiceException e) {
// TODO handle this properly
throw new RuntimeException(e);
}
}
Aggregations