Search in sources :

Example 16 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 acquireToken.

@Override
public AcquireTokenResult acquireToken(@NonNull final InteractiveTokenCommandParameters parameters) throws ExecutionException, InterruptedException, ClientException, IOException, ArgumentException {
    final String methodName = ":acquireToken";
    Logger.verbose(TAG + methodName, "Acquiring token...");
    Telemetry.emit(new ApiStartEvent().putProperties(parameters).putApiId(TelemetryEventStrings.Api.LOCAL_ACQUIRE_TOKEN_INTERACTIVE));
    final AcquireTokenResult acquireTokenResult = new AcquireTokenResult();
    // 00) Validate MSAL Parameters
    parameters.validate();
    // Add default scopes
    final Set<String> mergedScopes = addDefaultScopes(parameters);
    final InteractiveTokenCommandParameters parametersWithScopes = parameters.toBuilder().scopes(mergedScopes).build();
    logParameters(TAG, parametersWithScopes);
    // 0) Get known authority result
    throwIfNetworkNotAvailable(parametersWithScopes.getAndroidApplicationContext(), parametersWithScopes.isPowerOptCheckEnabled());
    Authority.KnownAuthorityResult authorityResult = Authority.getKnownAuthorityResult(parametersWithScopes.getAuthority());
    // 0.1 If not known throw resulting exception
    if (!authorityResult.getKnown()) {
        Telemetry.emit(new ApiEndEvent().putException(authorityResult.getClientException()).putApiId(TelemetryEventStrings.Api.LOCAL_ACQUIRE_TOKEN_INTERACTIVE));
        throw authorityResult.getClientException();
    }
    // Build up params for Strategy construction
    final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
    strategyParameters.setContext(parametersWithScopes.getAndroidApplicationContext());
    // 1) Get oAuth2Strategy for Authority Type
    @SuppressWarnings(WarningType.rawtype_warning) final OAuth2Strategy oAuth2Strategy = parametersWithScopes.getAuthority().createOAuth2Strategy(strategyParameters);
    // 2) Request authorization interactively
    @SuppressWarnings(WarningType.rawtype_warning) final AuthorizationResult result = performAuthorizationRequest(oAuth2Strategy, parametersWithScopes.getAndroidApplicationContext(), parametersWithScopes);
    acquireTokenResult.setAuthorizationResult(result);
    logResult(TAG, result);
    if (result.getAuthorizationStatus().equals(AuthorizationStatus.SUCCESS)) {
        // 3) Exchange authorization code for token
        final TokenResult tokenResult = performTokenRequest(oAuth2Strategy, mAuthorizationRequest, result.getAuthorizationResponse(), parametersWithScopes);
        acquireTokenResult.setTokenResult(tokenResult);
        if (tokenResult != null && tokenResult.getSuccess()) {
            // 4) Save tokens in token cache
            final List<ICacheRecord> records = saveTokens(oAuth2Strategy, mAuthorizationRequest, tokenResult.getTokenResponse(), parametersWithScopes.getOAuth2TokenCache());
            // The first element in the returned list is the item we *just* saved, the rest of
            // the elements are necessary to construct the full IAccount + TenantProfile
            final ICacheRecord newestRecord = records.get(0);
            acquireTokenResult.setLocalAuthenticationResult(new LocalAuthenticationResult(finalizeCacheRecordForResult(newestRecord, parametersWithScopes.getAuthenticationScheme()), records, SdkType.MSAL, false));
        }
    }
    Telemetry.emit(new ApiEndEvent().putResult(acquireTokenResult).putApiId(TelemetryEventStrings.Api.LOCAL_ACQUIRE_TOKEN_INTERACTIVE));
    return acquireTokenResult;
}
Also used : AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) ICacheRecord(com.microsoft.identity.common.internal.cache.ICacheRecord) Authority(com.microsoft.identity.common.internal.authorities.Authority) 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) InteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.InteractiveTokenCommandParameters) OAuth2Strategy(com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy) AuthorizationResult(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult) ApiEndEvent(com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent) ApiStartEvent(com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent) LocalAuthenticationResult(com.microsoft.identity.common.internal.result.LocalAuthenticationResult)

Example 17 with TokenResult

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

/**
 * Logs errors from the {@link TokenResult}.
 *
 * @param correlationId The correlation id of the request.
 * @param tokenResult   The TokenResult whose errors should be logged.
 */
public static void logTokenResultError(@NonNull final UUID correlationId, @NonNull final TokenResult tokenResult) {
    final TokenErrorResponse tokenErrorResponse = tokenResult.getErrorResponse();
    Logger.warn(TAG, correlationId.toString(), "Status code: [" + tokenErrorResponse.getStatusCode() + "]");
    Logger.warn(TAG, correlationId.toString(), "Error description: [" + tokenErrorResponse.getErrorDescription() + "]");
}
Also used : TokenErrorResponse(com.microsoft.identity.common.internal.providers.oauth2.TokenErrorResponse)

Example 19 with TokenResult

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

the class MockDelayedResponseStrategy method getTokenResult.

public TokenResult getTokenResult() {
    final TokenResponse tokenResponse = MockTokenResponse.getMockSuccessTokenResponse();
    final TokenResult tokenResult = new TokenResult(tokenResponse);
    return tokenResult;
}
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)

Example 20 with TokenResult

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

the class MockDelayedResponseStrategy method performTokenRequest.

@Override
protected HttpResponse performTokenRequest(final MicrosoftStsTokenRequest tokenRequest) {
    final TokenResult tokenResult = getTokenResult();
    final TokenResponse tokenResponse = tokenResult.getTokenResponse();
    try {
        Thread.sleep(RESPONSE_DELAY);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    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)

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