Search in sources :

Example 1 with AuthorizationResponse

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

Example 2 with AuthorizationResponse

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

the class BaseController method performTokenRequest.

protected TokenResult performTokenRequest(@SuppressWarnings(WarningType.rawtype_warning) @NonNull final OAuth2Strategy strategy, @SuppressWarnings(WarningType.rawtype_warning) @NonNull final AuthorizationRequest request, @NonNull final AuthorizationResponse response, @NonNull final InteractiveTokenCommandParameters parameters) throws IOException, ClientException {
    final String methodName = ":performTokenRequest";
    HttpWebRequest.throwIfNetworkNotAvailable(parameters.getAndroidApplicationContext(), parameters.isPowerOptCheckEnabled());
    // Suppressing unchecked warnings due to casting of type AuthorizationRequest to GenericAuthorizationRequest and AuthorizationResponse to GenericAuthorizationResponse in arguments of method call to createTokenRequest
    @SuppressWarnings(WarningType.unchecked_warning) final TokenRequest tokenRequest = strategy.createTokenRequest(request, response, parameters.getAuthenticationScheme());
    if (tokenRequest instanceof MicrosoftTokenRequest) {
        ((MicrosoftTokenRequest) tokenRequest).setClientAppName(parameters.getApplicationName());
        ((MicrosoftTokenRequest) tokenRequest).setClientAppVersion(parameters.getApplicationVersion());
    }
    if (tokenRequest instanceof IHasExtraParameters && parameters instanceof IHasExtraParameters) {
        ((IHasExtraParameters) tokenRequest).setExtraParameters(((IHasExtraParameters) parameters).getExtraParameters());
    }
    logExposedFieldsOfObject(TAG + methodName, tokenRequest);
    // Suppressing unchecked warnings due to casting of type TokenRequest to GenericTokenRequest in argument of method call to requestToken
    @SuppressWarnings(WarningType.unchecked_warning) final TokenResult tokenResult = strategy.requestToken(tokenRequest);
    logResult(TAG, tokenResult);
    return tokenResult;
}
Also used : TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) MicrosoftTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftTokenRequest) TokenRequest(com.microsoft.identity.common.internal.providers.oauth2.TokenRequest) MicrosoftTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftTokenRequest) IHasExtraParameters(com.microsoft.identity.common.internal.commands.parameters.IHasExtraParameters)

Example 3 with AuthorizationResponse

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

the class DeviceCodeFlowCommand method execute.

@Override
public AcquireTokenResult execute() throws Exception {
    final String methodName = ":execute";
    Logger.verbose(TAG + methodName, "Device Code Flow command initiating...");
    // Get the controller used to execute the command
    final BaseController controller = getDefaultController();
    // Fetch the parameters
    final DeviceCodeFlowCommandParameters commandParameters = (DeviceCodeFlowCommandParameters) getParameters();
    // Call deviceCodeFlowAuthRequest to get authorization result (Part 1 of DCF)
    @SuppressWarnings(WarningType.rawtype_warning) final AuthorizationResult authorizationResult = controller.deviceCodeFlowAuthRequest(commandParameters);
    // Fetch the authorization response
    final MicrosoftStsAuthorizationResponse authorizationResponse = (MicrosoftStsAuthorizationResponse) authorizationResult.getAuthorizationResponse();
    final Date expiredDate = new Date();
    try {
        long expiredInInMilliseconds = TimeUnit.SECONDS.toMillis(Long.parseLong(authorizationResponse.getExpiresIn()));
        expiredDate.setTime(expiredDate.getTime() + expiredInInMilliseconds);
    } catch (final NumberFormatException e) {
        // Shouldn't happen, but if it does, we don't want to fail the request because of this.
        Logger.error(TAG + methodName, "Failed to parse authorizationResponse.getExpiresIn()", e);
    }
    // Communicate with user app and provide authentication information
    @SuppressWarnings(WarningType.rawtype_warning) final DeviceCodeFlowCommandCallback deviceCodeFlowCommandCallback = (DeviceCodeFlowCommandCallback) getCallback();
    deviceCodeFlowCommandCallback.onUserCodeReceived(authorizationResponse.getVerificationUri(), authorizationResponse.getUserCode(), authorizationResponse.getMessage(), expiredDate);
    // Call acquireDeviceCodeFlowToken to get token result (Part 2 of DCF)
    final AcquireTokenResult tokenResult = controller.acquireDeviceCodeFlowToken(authorizationResult, commandParameters);
    Logger.verbose(TAG + methodName, "Device Code Flow command exiting with token...");
    return tokenResult;
}
Also used : AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) MicrosoftStsAuthorizationResponse(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsAuthorizationResponse) BaseController(com.microsoft.identity.common.internal.controllers.BaseController) DeviceCodeFlowCommandParameters(com.microsoft.identity.common.internal.commands.parameters.DeviceCodeFlowCommandParameters) AuthorizationResult(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult) Date(java.util.Date)

Example 4 with AuthorizationResponse

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

the class ConfidentialClientHelper method requestAccessTokenForAutomation.

/**
 * Yep.  Hardcoding this method to retrieve access token for MSIDLABS
 */
private String requestAccessTokenForAutomation() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, IOException {
    String accessToken = null;
    final TokenRequest tokenRequest = this.createTokenRequest();
    tokenRequest.setGrantType(CLIENT_CREDENTIALS);
    final AccountsInOneOrganization aadAudience = new AccountsInOneOrganization(TENANT_ID);
    final AzureActiveDirectoryAuthority authority = new AzureActiveDirectoryAuthority(aadAudience);
    try {
        final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
        OAuth2Strategy<AccessToken, BaseAccount, AuthorizationRequest, AuthorizationRequest.Builder, AuthorizationStrategy, OAuth2Configuration, OAuth2StrategyParameters, AuthorizationResponse, RefreshToken, TokenRequest, TokenResponse, TokenResult, AuthorizationResult> strategy = authority.createOAuth2Strategy(strategyParameters);
        TokenResult tokenResult = strategy.requestToken(tokenRequest);
        if (tokenResult.getSuccess()) {
            accessToken = tokenResult.getTokenResponse().getAccessToken();
        } else {
            throw new RuntimeException(tokenResult.getErrorResponse().getErrorDescription());
        }
    } catch (final ClientException e) {
        e.printStackTrace();
    }
    return accessToken;
}
Also used : AuthorizationStrategy(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationStrategy) AuthorizationRequest(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationRequest) TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) AuthorizationResult(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult) AuthorizationResponse(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResponse) RefreshToken(com.microsoft.identity.common.internal.providers.oauth2.RefreshToken) TokenResponse(com.microsoft.identity.common.internal.providers.oauth2.TokenResponse) AccessToken(com.microsoft.identity.common.internal.providers.oauth2.AccessToken) BaseAccount(com.microsoft.identity.common.BaseAccount) AccountsInOneOrganization(com.microsoft.identity.common.internal.authorities.AccountsInOneOrganization) TokenRequest(com.microsoft.identity.common.internal.providers.oauth2.TokenRequest) AzureActiveDirectoryAuthority(com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority) OAuth2Configuration(com.microsoft.identity.common.internal.providers.oauth2.OAuth2Configuration) ClientException(com.microsoft.identity.common.exception.ClientException)

Aggregations

TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)3 AcquireTokenResult (com.microsoft.identity.common.internal.result.AcquireTokenResult)3 ClientException (com.microsoft.identity.common.exception.ClientException)2 MicrosoftStsAuthorizationResponse (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsAuthorizationResponse)2 AuthorizationResult (com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult)2 OAuth2StrategyParameters (com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters)2 TokenRequest (com.microsoft.identity.common.internal.providers.oauth2.TokenRequest)2 BaseAccount (com.microsoft.identity.common.BaseAccount)1 ArgumentException (com.microsoft.identity.common.exception.ArgumentException)1 ServiceException (com.microsoft.identity.common.exception.ServiceException)1 AccountsInOneOrganization (com.microsoft.identity.common.internal.authorities.AccountsInOneOrganization)1 AzureActiveDirectoryAuthority (com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority)1 ICacheRecord (com.microsoft.identity.common.internal.cache.ICacheRecord)1 DeviceCodeFlowCommandParameters (com.microsoft.identity.common.internal.commands.parameters.DeviceCodeFlowCommandParameters)1 IHasExtraParameters (com.microsoft.identity.common.internal.commands.parameters.IHasExtraParameters)1 BaseController (com.microsoft.identity.common.internal.controllers.BaseController)1 MicrosoftTokenRequest (com.microsoft.identity.common.internal.providers.microsoft.MicrosoftTokenRequest)1 MicrosoftStsTokenRequest (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenRequest)1 AccessToken (com.microsoft.identity.common.internal.providers.oauth2.AccessToken)1 AuthorizationRequest (com.microsoft.identity.common.internal.providers.oauth2.AuthorizationRequest)1