Search in sources :

Example 6 with TokenResult

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResult in project microsoft-authentication-library-common-for-android by AzureAD.

the class MockTestStrategy method performTokenRequest.

@Override
protected HttpResponse performTokenRequest(final MicrosoftStsTokenRequest tokenRequest) {
    final TokenResult tokenResult = getTokenResult();
    final TokenResponse tokenResponse = tokenResult.getTokenResponse();
    final HttpResponse httpResponse = makeHttpResponseFromResponseObject(tokenResponse);
    return httpResponse;
}
Also used : TokenResponse(com.microsoft.identity.common.internal.providers.oauth2.TokenResponse) MockTokenResponse(com.microsoft.identity.internal.testutils.mocks.MockTokenResponse) TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) HttpResponse(com.microsoft.identity.common.internal.net.HttpResponse)

Example 7 with TokenResult

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResult in project microsoft-authentication-library-common-for-android by AzureAD.

the class TokenCacheItemMigrationAdapter method renewToken.

@Nullable
public static Pair<MicrosoftAccount, MicrosoftRefreshToken> renewToken(@Nullable final String redirectUri, @NonNull final ITokenCacheItem targetCacheItemToRenew) {
    Pair<MicrosoftAccount, MicrosoftRefreshToken> resultPair = null;
    if (!StringExtensions.isNullOrBlank(redirectUri)) {
        try {
            final String authority = targetCacheItemToRenew.getAuthority();
            final String clientId = targetCacheItemToRenew.getClientId();
            final String refreshToken = targetCacheItemToRenew.getRefreshToken();
            final MicrosoftStsOAuth2Configuration config = new MicrosoftStsOAuth2Configuration();
            config.setAuthorityUrl(new URL(authority));
            // Create a correlation_id for the request
            final UUID correlationId = UUID.randomUUID();
            final String scopes;
            if (TextUtils.isEmpty(targetCacheItemToRenew.getResource())) {
                scopes = BaseController.getDelimitedDefaultScopeString();
            } else {
                scopes = getScopesForTokenRequest(targetCacheItemToRenew.getResource());
            }
            // Create the strategy
            final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
            final MicrosoftStsOAuth2Strategy strategy = new MicrosoftStsOAuth2Strategy(config, strategyParameters);
            final MicrosoftStsTokenRequest tokenRequest = createTokenRequest(clientId, scopes, refreshToken, redirectUri, strategy, correlationId, "2");
            final TokenResult tokenResult = strategy.requestToken(tokenRequest);
            if (tokenResult.getSuccess()) {
                final MicrosoftStsTokenResponse tokenResponse = (MicrosoftStsTokenResponse) tokenResult.getTokenResponse();
                tokenResponse.setClientId(clientId);
                // Create the Account to save...
                final MicrosoftAccount account = strategy.createAccount(tokenResponse);
                // Create the refresh token...
                final MicrosoftRefreshToken msStsRt = new MicrosoftStsRefreshToken(tokenResponse);
                msStsRt.setEnvironment(AzureActiveDirectory.getAzureActiveDirectoryCloud(new URL(authority)).getPreferredCacheHostName());
                resultPair = new Pair<>(account, msStsRt);
            } else {
                Logger.warn(TAG, correlationId.toString(), "TokenRequest was unsuccessful.");
                if (null != tokenResult.getErrorResponse()) {
                    logTokenResultError(correlationId, tokenResult);
                }
            }
        } catch (Exception e) {
            Logger.errorPII(TAG, "Failed to request new refresh token...", e);
        }
    }
    return resultPair;
}
Also used : TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) MicrosoftStsOAuth2Strategy(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Strategy) MicrosoftStsRefreshToken(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsRefreshToken) URL(java.net.URL) ClientException(com.microsoft.identity.common.exception.ClientException) IOException(java.io.IOException) MicrosoftAccount(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftAccount) MicrosoftRefreshToken(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftRefreshToken) MicrosoftStsTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenRequest) MicrosoftStsOAuth2Configuration(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Configuration) UUID(java.util.UUID) MicrosoftStsTokenResponse(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenResponse) Nullable(androidx.annotation.Nullable)

Example 8 with TokenResult

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResult in project microsoft-authentication-library-common-for-android by AzureAD.

the class TokenCacheItemMigrationAdapter method tryFociTokenWithGivenClientId.

/**
 * Testing whether the given client ID can use the cached foci to refresh token.
 *
 * @param clientId           String of the given client id.
 * @param redirectUri        redirect url string of the given client id.
 * @param accountRecord      account record of request
 * @param refreshTokenRecord refresh token record of FOCI account
 * @return true if the given client id can use the cached foci token. False, otherwise.
 * @throws ClientException
 * @throws IOException
 */
public static boolean tryFociTokenWithGivenClientId(@SuppressWarnings(WarningType.rawtype_warning) @NonNull final OAuth2TokenCache brokerOAuth2TokenCache, @NonNull final String clientId, @NonNull final String redirectUri, @NonNull final RefreshTokenRecord refreshTokenRecord, @NonNull final IAccountRecord accountRecord) throws ClientException, IOException {
    final String methodName = ":tryFociTokenWithGivenClientId";
    final MicrosoftStsOAuth2Configuration config = new MicrosoftStsOAuth2Configuration();
    // Get authority url
    final Uri.Builder requestUrlBuilder = new Uri.Builder();
    requestUrlBuilder.scheme("https").authority(refreshTokenRecord.getEnvironment()).appendPath(StringUtil.isEmpty(accountRecord.getRealm()) ? ALL_ACCOUNTS_TENANT_ID : accountRecord.getRealm());
    final URL authorityUrl = new URL(requestUrlBuilder.build().toString());
    // set the token endpoint for the configuration
    config.setAuthorityUrl(authorityUrl);
    // Create the strategy
    final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
    final MicrosoftStsOAuth2Strategy strategy = new MicrosoftStsOAuth2Strategy(config, strategyParameters);
    final String refreshToken = refreshTokenRecord.getSecret();
    final String scopes;
    // https://identitydivision.visualstudio.com/Engineering/_workitems/edit/1222002
    if (TextUtils.equals(clientId, "87749df4-7ccf-48f8-aa87-704bad0e0e16")) {
        scopes = "https://devicemgmt.teams.microsoft.com/.default " + BaseController.getDelimitedDefaultScopeString();
        Logger.info(TAG + methodName, "Teams agent client ID - making a test request with teams agent resource.");
    } else {
        scopes = BaseController.getDelimitedDefaultScopeString();
    }
    // Create a correlation_id for the request
    final UUID correlationId = UUID.randomUUID();
    Logger.verbose(TAG + methodName, "Create the token request with correlationId [" + correlationId + "]");
    final MicrosoftStsTokenRequest tokenRequest = createTokenRequest(clientId, scopes, refreshToken, redirectUri, strategy, correlationId, "2");
    Logger.verbose(TAG + methodName, "Start refreshing token (to verify foci) with correlationId [" + correlationId + "]");
    final TokenResult tokenResult = strategy.requestToken(tokenRequest);
    Logger.verbose(TAG + methodName, "Is the client ID able to use the foci? [" + tokenResult.getSuccess() + "] with correlationId [" + correlationId + "]");
    if (tokenResult.getSuccess()) {
        // Save the token record in tha cache so that we have an entry in BrokerApplicationMetadata for this client id.
        final MicrosoftStsAuthorizationRequest authorizationRequest = createAuthRequest(strategy, clientId, redirectUri, scopes, accountRecord, correlationId);
        Logger.verbose(TAG + methodName, "Saving records to cache with client id" + clientId);
        brokerOAuth2TokenCacheSave(brokerOAuth2TokenCache, strategy, tokenResult, authorizationRequest);
    }
    return tokenResult.getSuccess();
}
Also used : MicrosoftStsAuthorizationRequest(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsAuthorizationRequest) MicrosoftStsTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenRequest) TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) MicrosoftStsOAuth2Configuration(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Configuration) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) MicrosoftStsOAuth2Strategy(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Strategy) UUID(java.util.UUID) Uri(android.net.Uri) URL(java.net.URL)

Example 9 with TokenResult

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResult in project microsoft-authentication-library-common-for-android by AzureAD.

the class BaseController method renewAccessToken.

protected void renewAccessToken(@NonNull final SilentTokenCommandParameters parameters, @NonNull final AcquireTokenResult acquireTokenSilentResult, @SuppressWarnings(WarningType.rawtype_warning) @NonNull final OAuth2TokenCache tokenCache, @SuppressWarnings(WarningType.rawtype_warning) @NonNull final OAuth2Strategy strategy, @NonNull final ICacheRecord cacheRecord) throws IOException, ClientException {
    final String methodName = ":renewAccessToken";
    Logger.info(TAG + methodName, "Renewing access token...");
    RefreshTokenRecord refreshTokenRecord = cacheRecord.getRefreshToken();
    logParameters(TAG, parameters);
    final TokenResult tokenResult = performSilentTokenRequest(strategy, refreshTokenRecord, parameters);
    acquireTokenSilentResult.setTokenResult(tokenResult);
    logResult(TAG + methodName, tokenResult);
    if (tokenResult.getSuccess()) {
        Logger.info(TAG + methodName, "Token request was successful");
        // Suppressing unchecked warnings due to casting of rawtypes to generic types of OAuth2TokenCache's instance tokenCache while calling method saveAndLoadAggregatedAccountData
        @SuppressWarnings(WarningType.unchecked_warning) final List<ICacheRecord> savedRecords = tokenCache.saveAndLoadAggregatedAccountData(strategy, getAuthorizationRequest(strategy, parameters), tokenResult.getTokenResponse());
        final ICacheRecord savedRecord = savedRecords.get(0);
        // Create a new AuthenticationResult to hold the saved record
        final LocalAuthenticationResult authenticationResult = new LocalAuthenticationResult(finalizeCacheRecordForResult(savedRecord, parameters.getAuthenticationScheme()), savedRecords, parameters.getSdkType(), false);
        // Set the client telemetry...
        if (null != tokenResult.getCliTelemInfo()) {
            final CliTelemInfo cliTelemInfo = tokenResult.getCliTelemInfo();
            authenticationResult.setSpeRing(cliTelemInfo.getSpeRing());
            authenticationResult.setRefreshTokenAge(cliTelemInfo.getRefreshTokenAge());
            Telemetry.emit(new CacheEndEvent().putSpeInfo(tokenResult.getCliTelemInfo().getSpeRing()));
        } else {
            // we can't put SpeInfo as the CliTelemInfo is null
            Telemetry.emit(new CacheEndEvent());
        }
        // Set the AuthenticationResult on the final result object
        acquireTokenSilentResult.setLocalAuthenticationResult(authenticationResult);
    } else {
        if (tokenResult.getErrorResponse() != null) {
            final String errorCode = tokenResult.getErrorResponse().getError();
            final String subErrorCode = tokenResult.getErrorResponse().getSubError();
            Logger.info(TAG, "Error: " + errorCode + " Suberror: " + subErrorCode);
            if (INVALID_GRANT.equals(errorCode) && BAD_TOKEN.equals(subErrorCode)) {
                boolean isRemoved = tokenCache.removeCredential(cacheRecord.getRefreshToken());
                Logger.info(TAG, "Refresh token is invalid, " + "attempting to delete the RT from cache, result:" + isRemoved);
            }
        } else {
            Logger.warn(TAG, "Invalid state, No token success or error response on the token result");
        }
    }
}
Also used : CliTelemInfo(com.microsoft.identity.common.internal.telemetry.CliTelemInfo) ICacheRecord(com.microsoft.identity.common.internal.cache.ICacheRecord) TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) CacheEndEvent(com.microsoft.identity.common.internal.telemetry.events.CacheEndEvent) RefreshTokenRecord(com.microsoft.identity.common.internal.dto.RefreshTokenRecord) LocalAuthenticationResult(com.microsoft.identity.common.internal.result.LocalAuthenticationResult)

Example 10 with TokenResult

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResult in project microsoft-authentication-library-common-for-android by AzureAD.

the class LocalMSALController method acquireDeviceCodeFlowToken.

@Override
public AcquireTokenResult acquireDeviceCodeFlowToken(@SuppressWarnings(WarningType.rawtype_warning) final AuthorizationResult authorizationResult, final DeviceCodeFlowCommandParameters parameters) throws ServiceException, ClientException, IOException {
    // Logging start of method
    final String methodName = ":acquireDeviceCodeFlowToken";
    Logger.verbose(TAG + methodName, "Device Code Flow: Polling for token...");
    // Start telemetry with LOCAL_DEVICE_CODE_FLOW_POLLING
    Telemetry.emit(new ApiStartEvent().putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_POLLING));
    // Create empty AcquireTokenResult object
    final AcquireTokenResult acquireTokenResult = new AcquireTokenResult();
    // Assign authorization result
    acquireTokenResult.setAuthorizationResult(authorizationResult);
    // Fetch the Authorization Response
    final MicrosoftStsAuthorizationResponse authorizationResponse = (MicrosoftStsAuthorizationResponse) authorizationResult.getAuthorizationResponse();
    // DCF protocol step 2: Poll for token
    TokenResult tokenResult = null;
    try {
        // Create OAuth2Strategy using commandParameters and strategyParameters
        final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
        strategyParameters.setContext(parameters.getAndroidApplicationContext());
        @SuppressWarnings(WarningType.rawtype_warning) final OAuth2Strategy oAuth2Strategy = parameters.getAuthority().createOAuth2Strategy(strategyParameters);
        // Create token request outside of loop so it isn't re-created after every loop
        // Suppressing unchecked warnings due to casting of AuthorizationRequest to GenericAuthorizationRequest and MicrosoftStsAuthorizationResponse to GenericAuthorizationResponse in the arguments of call to createTokenRequest method
        @SuppressWarnings(WarningType.unchecked_warning) final MicrosoftStsTokenRequest tokenRequest = (MicrosoftStsTokenRequest) oAuth2Strategy.createTokenRequest(mAuthorizationRequest, authorizationResponse, parameters.getAuthenticationScheme());
        // Fetch wait interval
        final int intervalInMilliseconds = Integer.parseInt(authorizationResponse.getInterval()) * 1000;
        String errorCode = ErrorStrings.DEVICE_CODE_FLOW_AUTHORIZATION_PENDING_ERROR_CODE;
        // Loop to send multiple requests checking for token
        while (authorizationPending(errorCode)) {
            // Wait between polls
            ThreadUtils.sleepSafely(intervalInMilliseconds, TAG, "Attempting to sleep thread during Device Code Flow token polling...");
            // Reset error code
            errorCode = "";
            // Execute Token Request
            // Suppressing unchecked warnings due to casting of MicrosoftStsTokenRequest to GenericTokenRequest in the arguments of call to requestToken method
            @SuppressWarnings(WarningType.unchecked_warning) TokenResult tokenResultFromRequestToken = oAuth2Strategy.requestToken(tokenRequest);
            tokenResult = tokenResultFromRequestToken;
            // Fetch error if the request failed
            if (tokenResult.getErrorResponse() != null) {
                errorCode = tokenResult.getErrorResponse().getError();
            }
        }
        // Validate request success, may throw MsalServiceException
        validateServiceResult(tokenResult);
        // Assign token result
        acquireTokenResult.setTokenResult(tokenResult);
        // If the token is valid, save it into token cache
        final List<ICacheRecord> records = saveTokens(oAuth2Strategy, mAuthorizationRequest, acquireTokenResult.getTokenResult().getTokenResponse(), parameters.getOAuth2TokenCache());
        // Once the token is stored, fetch and assign the authentication result
        final ICacheRecord newestRecord = records.get(0);
        acquireTokenResult.setLocalAuthenticationResult(new LocalAuthenticationResult(finalizeCacheRecordForResult(newestRecord, parameters.getAuthenticationScheme()), records, SdkType.MSAL, false));
    } catch (Exception error) {
        Telemetry.emit(new ApiEndEvent().putException(error).putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_POLLING));
        throw error;
    }
    logResult(TAG, tokenResult);
    // End telemetry with LOCAL_DEVICE_CODE_FLOW_POLLING
    Telemetry.emit(new ApiEndEvent().putResult(acquireTokenResult).putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_POLLING));
    return acquireTokenResult;
}
Also used : AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) ICacheRecord(com.microsoft.identity.common.internal.cache.ICacheRecord) TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) OAuth2Strategy(com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy) ServiceException(com.microsoft.identity.common.exception.ServiceException) ClientException(com.microsoft.identity.common.exception.ClientException) IOException(java.io.IOException) ArgumentException(com.microsoft.identity.common.exception.ArgumentException) ExecutionException(java.util.concurrent.ExecutionException) MicrosoftStsAuthorizationResponse(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsAuthorizationResponse) ApiEndEvent(com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent) MicrosoftStsTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenRequest) ApiStartEvent(com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent) LocalAuthenticationResult(com.microsoft.identity.common.internal.result.LocalAuthenticationResult)

Aggregations

TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)15 OAuth2StrategyParameters (com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters)7 TokenResponse (com.microsoft.identity.common.internal.providers.oauth2.TokenResponse)6 ClientException (com.microsoft.identity.common.exception.ClientException)5 AcquireTokenResult (com.microsoft.identity.common.internal.result.AcquireTokenResult)5 MicrosoftStsTokenRequest (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenRequest)4 OAuth2Strategy (com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy)4 MockTokenResponse (com.microsoft.identity.internal.testutils.mocks.MockTokenResponse)4 IOException (java.io.IOException)4 ICacheRecord (com.microsoft.identity.common.internal.cache.ICacheRecord)3 MicrosoftStsOAuth2Configuration (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Configuration)3 MicrosoftStsOAuth2Strategy (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Strategy)3 AuthorizationResult (com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult)3 TokenRequest (com.microsoft.identity.common.internal.providers.oauth2.TokenRequest)3 LocalAuthenticationResult (com.microsoft.identity.common.internal.result.LocalAuthenticationResult)3 OAuth2CodeGrantFlow (org.glassfish.jersey.client.oauth2.OAuth2CodeGrantFlow)3 TokenResult (org.glassfish.jersey.client.oauth2.TokenResult)3 Authority (com.microsoft.identity.common.internal.authorities.Authority)2 AzureActiveDirectoryAuthority (com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority)2 HttpResponse (com.microsoft.identity.common.internal.net.HttpResponse)2