Search in sources :

Example 1 with OAuth2Strategy

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

the class AzureActiveDirectoryClientCredentialsGrantTest method test_ClientCredentials.

@Test
public void test_ClientCredentials() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, IOException {
    final CertificateCredential credential = new CertificateCredential.CertificateCredentialBuilder(CLIENT_ID).clientCertificateMetadata(new ClientCertificateMetadata(CERTIFICATE_ALIAS, null)).keyStoreConfiguration(new KeyStoreConfiguration(KEYSTORE_TYPE, KEYSTORE_PROVIDER, null)).build();
    final String audience = AAD_CLIENT_ASSERTION_AUDIENCE;
    final MicrosoftClientAssertion assertion = new MicrosoftClientAssertion(audience, credential);
    final AzureActiveDirectoryTokenRequest tr = new AzureActiveDirectoryTokenRequest();
    tr.setClientAssertionType(assertion.getClientAssertionType());
    tr.setClientAssertion(assertion.getClientAssertion());
    tr.setClientId(CLIENT_ID);
    tr.setResourceId(RESOURCE);
    tr.setGrantType(GRANT_TYPE);
    final OAuth2StrategyParameters options = new OAuth2StrategyParameters();
    final OAuth2Strategy strategy = new AzureActiveDirectoryOAuth2Strategy(new AzureActiveDirectoryOAuth2Configuration(), options);
    try {
        final TokenResult tokenResult = strategy.requestToken(tr);
        assertEquals(true, tokenResult.getSuccess());
    } catch (final ClientException exception) {
        fail("Unexpected exception.");
    }
}
Also used : AzureActiveDirectoryOAuth2Strategy(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryOAuth2Strategy) MicrosoftClientAssertion(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftClientAssertion) TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) AzureActiveDirectoryTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryTokenRequest) ClientCertificateMetadata(com.microsoft.identity.common.internal.providers.keys.ClientCertificateMetadata) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) KeyStoreConfiguration(com.microsoft.identity.common.internal.providers.keys.KeyStoreConfiguration) OAuth2Strategy(com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy) AzureActiveDirectoryOAuth2Strategy(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryOAuth2Strategy) CertificateCredential(com.microsoft.identity.common.internal.providers.keys.CertificateCredential) AzureActiveDirectoryOAuth2Configuration(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryOAuth2Configuration) ClientException(com.microsoft.identity.common.exception.ClientException) Test(org.junit.Test)

Example 2 with OAuth2Strategy

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

the class MicrosoftSTSClientCredentialsGrantTest method test_ClientCredentials.

@Test
public void test_ClientCredentials() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, IOException {
    final CertificateCredential credential = new CertificateCredential.CertificateCredentialBuilder(CLIENT_ID).clientCertificateMetadata(new ClientCertificateMetadata(CERTIFICATE_ALIAS, null)).keyStoreConfiguration(new KeyStoreConfiguration(KEYSTORE_TYPE, KEYSTORE_PROVIDER, null)).build();
    final String audience = MSSTS_CLIENT_ASSERTION_AUDIENCE;
    final MicrosoftClientAssertion assertion = new MicrosoftClientAssertion(audience, credential);
    final TokenRequest tr = new MicrosoftStsTokenRequest();
    tr.setClientAssertionType(assertion.getClientAssertionType());
    tr.setClientAssertion(assertion.getClientAssertion());
    tr.setClientId(CLIENT_ID);
    tr.setScope(SCOPE);
    tr.setGrantType(GRANT_TYPE);
    final OAuth2StrategyParameters options = new OAuth2StrategyParameters();
    final OAuth2Strategy strategy = new MicrosoftStsOAuth2Strategy(new MicrosoftStsOAuth2Configuration(), options);
    try {
        final TokenResult tokenResult = strategy.requestToken(tr);
        assertEquals(true, tokenResult.getSuccess());
    } catch (final ClientException exception) {
        fail("Unexpected exception.");
    }
}
Also used : MicrosoftClientAssertion(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftClientAssertion) TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) ClientCertificateMetadata(com.microsoft.identity.common.internal.providers.keys.ClientCertificateMetadata) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) MicrosoftStsOAuth2Strategy(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Strategy) KeyStoreConfiguration(com.microsoft.identity.common.internal.providers.keys.KeyStoreConfiguration) MicrosoftStsOAuth2Strategy(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Strategy) OAuth2Strategy(com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy) CertificateCredential(com.microsoft.identity.common.internal.providers.keys.CertificateCredential) MicrosoftStsTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenRequest) MicrosoftStsOAuth2Configuration(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Configuration) TokenRequest(com.microsoft.identity.common.internal.providers.oauth2.TokenRequest) MicrosoftStsTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenRequest) ClientException(com.microsoft.identity.common.exception.ClientException) Test(org.junit.Test)

Example 3 with OAuth2Strategy

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

the class BrokerOAuth2TokenCache method save.

@Override
public ICacheRecord save(@NonNull final GenericOAuth2Strategy oAuth2Strategy, @NonNull final GenericAuthorizationRequest request, @NonNull final GenericTokenResponse response) throws ClientException {
    final String methodName = ":save";
    final boolean isFoci = !StringExtensions.isNullOrBlank(response.getFamilyId());
    if (isFoci) {
        Logger.verbose(TAG + methodName, "Received FOCI value: [" + response.getFamilyId() + "]");
    }
    Logger.info(TAG + methodName, "Saving to FOCI cache? [" + isFoci + "]");
    OAuth2TokenCache targetCache;
    if (isFoci) {
        targetCache = mFociCache;
    } else {
        // Suppressing unchecked warning as the generic type was not provided for oAuth2Strategy and request of type GenericAuthorizationRequest
        @SuppressWarnings(WarningType.unchecked_warning) final String environment = oAuth2Strategy.getIssuerCacheIdentifier(request);
        // Try to find an existing cache for this application
        targetCache = getTokenCacheForClient(request.getClientId(), environment, mCallingProcessUid);
        if (null == targetCache) {
            // No existing cache could be found... Make a new one!
            Logger.warn(TAG + methodName, "Existing cache not found. A new one will be created.");
            targetCache = initializeProcessUidCache(getContext(), mCallingProcessUid);
        }
    }
    // Suppressing unchecked warnings due to casting of rawtypes to generic types of OAuth2TokenCache's instance targetCache while calling method save
    @SuppressWarnings(WarningType.unchecked_warning) final ICacheRecord result = targetCache.save(oAuth2Strategy, request, response);
    updateApplicationMetadataCache(result.getRefreshToken().getClientId(), result.getRefreshToken().getEnvironment(), result.getRefreshToken().getFamilyId(), mCallingProcessUid);
    return result;
}
Also used : OAuth2TokenCache(com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache)

Example 4 with OAuth2Strategy

use of com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy 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 5 with OAuth2Strategy

use of com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy 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

OAuth2StrategyParameters (com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters)7 TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)7 ClientException (com.microsoft.identity.common.exception.ClientException)6 OAuth2Strategy (com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy)6 AuthorizationResult (com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult)5 AcquireTokenResult (com.microsoft.identity.common.internal.result.AcquireTokenResult)5 ICacheRecord (com.microsoft.identity.common.internal.cache.ICacheRecord)4 TokenRequest (com.microsoft.identity.common.internal.providers.oauth2.TokenRequest)4 LocalAuthenticationResult (com.microsoft.identity.common.internal.result.LocalAuthenticationResult)4 ApiEndEvent (com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent)4 ApiStartEvent (com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent)4 Authority (com.microsoft.identity.common.internal.authorities.Authority)3 OAuth2TokenCache (com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache)3 ArgumentException (com.microsoft.identity.common.exception.ArgumentException)2 ServiceException (com.microsoft.identity.common.exception.ServiceException)2 AzureActiveDirectoryAuthority (com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority)2 CertificateCredential (com.microsoft.identity.common.internal.providers.keys.CertificateCredential)2 ClientCertificateMetadata (com.microsoft.identity.common.internal.providers.keys.ClientCertificateMetadata)2 KeyStoreConfiguration (com.microsoft.identity.common.internal.providers.keys.KeyStoreConfiguration)2 MicrosoftClientAssertion (com.microsoft.identity.common.internal.providers.microsoft.MicrosoftClientAssertion)2