Search in sources :

Example 6 with ClientInfo

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

Example 7 with ClientInfo

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;
}
Also used : JWSBuilder(com.microsoft.identity.common.adal.internal.JWSBuilder) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) GregorianCalendar(java.util.GregorianCalendar) JSONException(org.json.JSONException) URL(java.net.URL) ServiceException(com.microsoft.identity.common.exception.ServiceException) List(java.util.List) ClientInfo(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo) UUID(java.util.UUID)

Example 8 with ClientInfo

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);
    }
}
Also used : ServiceException(com.microsoft.identity.common.exception.ServiceException) RefreshTokenRecord(com.microsoft.identity.common.internal.dto.RefreshTokenRecord) ClientInfo(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo)

Example 9 with ClientInfo

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);
    }
}
Also used : IdTokenRecord(com.microsoft.identity.common.internal.dto.IdTokenRecord) ServiceException(com.microsoft.identity.common.exception.ServiceException) ClientInfo(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo)

Example 10 with ClientInfo

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);
    }
}
Also used : ServiceException(com.microsoft.identity.common.exception.ServiceException) ClientInfo(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo) AccessTokenRecord(com.microsoft.identity.common.internal.dto.AccessTokenRecord)

Aggregations

ClientInfo (com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo)10 ServiceException (com.microsoft.identity.common.exception.ServiceException)8 IDToken (com.microsoft.identity.common.internal.providers.oauth2.IDToken)4 Nullable (androidx.annotation.Nullable)2 IdTokenRecord (com.microsoft.identity.common.internal.dto.IdTokenRecord)2 RefreshTokenRecord (com.microsoft.identity.common.internal.dto.RefreshTokenRecord)2 URL (java.net.URL)2 Date (java.util.Date)2 Test (org.junit.Test)2 JsonObject (com.google.gson.JsonObject)1 JWSBuilder (com.microsoft.identity.common.adal.internal.JWSBuilder)1 StorageHelper (com.microsoft.identity.common.adal.internal.cache.StorageHelper)1 ClientException (com.microsoft.identity.common.exception.ClientException)1 BearerAuthenticationSchemeInternal (com.microsoft.identity.common.internal.authscheme.BearerAuthenticationSchemeInternal)1 BrokerResult (com.microsoft.identity.common.internal.broker.BrokerResult)1 CacheKeyValueDelegate (com.microsoft.identity.common.internal.cache.CacheKeyValueDelegate)1 IAccountCredentialCache (com.microsoft.identity.common.internal.cache.IAccountCredentialCache)1 ICacheRecord (com.microsoft.identity.common.internal.cache.ICacheRecord)1 MicrosoftStsAccountCredentialAdapter (com.microsoft.identity.common.internal.cache.MicrosoftStsAccountCredentialAdapter)1 MsalOAuth2TokenCache (com.microsoft.identity.common.internal.cache.MsalOAuth2TokenCache)1