Search in sources :

Example 1 with Authority

use of com.microsoft.identity.common.internal.authorities.Authority in project microsoft-authentication-library-common-for-android by AzureAD.

the class AdalBrokerRequestAdapter method brokerSilentParametersFromBundle.

@Override
public BrokerSilentTokenCommandParameters brokerSilentParametersFromBundle(Bundle bundle, Context context, Account account) {
    final String methodName = ":brokerSilentParametersFromBundle";
    Logger.verbose(TAG + methodName, "Constructing BrokerAcquireTokenOperationParameters from activity ");
    final int callingAppUid = bundle.getInt(AuthenticationConstants.Broker.CALLER_INFO_UID);
    final Authority authority = Authority.getAuthorityFromAuthorityUrl(bundle.getString(AuthenticationConstants.Broker.ACCOUNT_AUTHORITY));
    String correlationIdString = bundle.getString(AuthenticationConstants.Broker.ACCOUNT_CORRELATIONID);
    if (TextUtils.isEmpty(correlationIdString)) {
        Logger.info(TAG, "Correlation id not set by Adal, creating a new one");
        UUID correlationId = UUID.randomUUID();
        correlationIdString = correlationId.toString();
    }
    final String resource = bundle.getString(AuthenticationConstants.Broker.ACCOUNT_RESOURCE);
    final Set<String> scopes = new HashSet<>();
    scopes.add(TokenCacheItemMigrationAdapter.getScopeFromResource(resource));
    // There are two constants that need to be checked for the presence of the caller pkg name:
    // 1. CALLER_INFO_PACKAGE
    // 2. APP_PACKAGE_NAME
    // 
    // But wait! There are also versions of the ADAL library (Android) that did not send this value
    // in those cases, we simply 'lie' and say that the request came from **current** execution
    // context. This will not always be correct. We'll set a flag here to signal when the param
    // is used.
    final boolean callerPackageNameProvided = packageNameWasProvidedInBundle(bundle);
    final String packageName = getPackageNameFromBundle(bundle, context);
    String redirectUri = bundle.getString(AuthenticationConstants.Broker.ACCOUNT_REDIRECT);
    // Adal might not pass in the redirect uri, in that case calculate from broker validator
    if (callerPackageNameProvided || TextUtils.isEmpty(redirectUri)) {
        redirectUri = BrokerValidator.getBrokerRedirectUri(context, packageName);
    }
    final BrokerSilentTokenCommandParameters commandParameters = BrokerSilentTokenCommandParameters.builder().authenticationScheme(new BearerAuthenticationSchemeInternal()).androidApplicationContext(context).accountManagerAccount(account).sdkType(SdkType.ADAL).callerUid(callingAppUid).callerPackageName(packageName).callerAppVersion(bundle.getString(AuthenticationConstants.AAD.APP_VERSION)).authority(authority).correlationId(correlationIdString).scopes(scopes).clientId(bundle.getString(AuthenticationConstants.Broker.ACCOUNT_CLIENTID_KEY)).localAccountId(bundle.getString(AuthenticationConstants.Broker.ACCOUNT_USERINFO_USERID)).redirectUri(redirectUri).forceRefresh(Boolean.parseBoolean(bundle.getString(AuthenticationConstants.Broker.BROKER_FORCE_REFRESH))).claimsRequestJson(bundle.getString(AuthenticationConstants.Broker.ACCOUNT_CLAIMS)).loginHint(bundle.getString(AuthenticationConstants.Broker.ACCOUNT_NAME)).build();
    return commandParameters;
}
Also used : BearerAuthenticationSchemeInternal(com.microsoft.identity.common.internal.authscheme.BearerAuthenticationSchemeInternal) BrokerSilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerSilentTokenCommandParameters) AzureActiveDirectoryAuthority(com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority) Authority(com.microsoft.identity.common.internal.authorities.Authority) UUID(java.util.UUID) HashSet(java.util.HashSet)

Example 2 with Authority

use of com.microsoft.identity.common.internal.authorities.Authority in project microsoft-authentication-library-common-for-android by AzureAD.

the class MsalBrokerRequestAdapter method brokerSilentParametersFromBundle.

@Override
public BrokerSilentTokenCommandParameters brokerSilentParametersFromBundle(@NonNull final Bundle bundle, @NonNull final Context context, @NonNull final Account account) {
    Logger.info(TAG, "Constructing BrokerAcquireTokenSilentOperationParameters from result bundle");
    final BrokerRequest brokerRequest = brokerRequestFromBundle(bundle);
    if (brokerRequest == null) {
        Logger.error(TAG, "Broker Result is null, returning empty parameters, " + "validation is expected to fail", null);
        return BrokerSilentTokenCommandParameters.builder().build();
    }
    int callingAppUid = bundle.getInt(CALLER_INFO_UID);
    final Authority authority = Authority.getAuthorityFromAuthorityUrl(brokerRequest.getAuthority());
    if (authority instanceof AzureActiveDirectoryAuthority) {
        ((AzureActiveDirectoryAuthority) authority).setMultipleCloudsSupported(brokerRequest.isMultipleCloudsSupported());
    }
    String correlationIdString = brokerRequest.getCorrelationId();
    if (TextUtils.isEmpty(correlationIdString)) {
        UUID correlationId = UUID.randomUUID();
        correlationIdString = correlationId.toString();
    }
    final String negotiatedBrokerProtocolVersion = bundle.getString(NEGOTIATED_BP_VERSION_KEY);
    List<Pair<String, String>> extraOptions = QueryParamsAdapter._fromJson(brokerRequest.getExtraOptions());
    final BrokerSilentTokenCommandParameters commandParameters = BrokerSilentTokenCommandParameters.builder().authenticationScheme(getAuthenticationScheme(context, brokerRequest)).androidApplicationContext(context).accountManagerAccount(account).sdkType(brokerRequest.getSdkType() == null ? SdkType.MSAL : brokerRequest.getSdkType()).sdkVersion(brokerRequest.getMsalVersion()).callerUid(callingAppUid).applicationName(brokerRequest.getApplicationName()).applicationVersion(brokerRequest.getApplicationVersion()).callerPackageName(brokerRequest.getApplicationName()).callerAppVersion(brokerRequest.getApplicationVersion()).authority(authority).correlationId(correlationIdString).scopes(getScopesAsSet(brokerRequest.getScope())).redirectUri(brokerRequest.getRedirect()).extraOptions(extraOptions).clientId(brokerRequest.getClientId()).forceRefresh(brokerRequest.isForceRefresh()).claimsRequestJson(brokerRequest.getClaims()).loginHint(brokerRequest.getUserName()).homeAccountId(brokerRequest.getHomeAccountId()).localAccountId(brokerRequest.getLocalAccountId()).negotiatedBrokerProtocolVersion(negotiatedBrokerProtocolVersion).powerOptCheckEnabled(brokerRequest.isPowerOptCheckEnabled()).build();
    // Set Global environment variable for instance discovery if present
    if (!TextUtils.isEmpty(brokerRequest.getEnvironment())) {
        AzureActiveDirectory.setEnvironment(Environment.valueOf(brokerRequest.getEnvironment()));
    }
    return commandParameters;
}
Also used : BrokerSilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerSilentTokenCommandParameters) AzureActiveDirectoryAuthority(com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority) Authority(com.microsoft.identity.common.internal.authorities.Authority) AzureActiveDirectoryAuthority(com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority) BrokerRequest(com.microsoft.identity.common.internal.broker.BrokerRequest) GzipUtil.compressString(com.microsoft.identity.common.internal.util.GzipUtil.compressString) GzipUtil.decompressBytesToString(com.microsoft.identity.common.internal.util.GzipUtil.decompressBytesToString) UUID(java.util.UUID) Pair(android.util.Pair)

Example 3 with Authority

use of com.microsoft.identity.common.internal.authorities.Authority in project microsoft-authentication-library-common-for-android by AzureAD.

the class BaseController method performSilentTokenRequest.

protected TokenResult performSilentTokenRequest(@SuppressWarnings(WarningType.rawtype_warning) @NonNull final OAuth2Strategy strategy, @NonNull final RefreshTokenRecord refreshToken, @NonNull final SilentTokenCommandParameters parameters) throws ClientException, IOException {
    final String methodName = ":performSilentTokenRequest";
    Logger.info(TAG + methodName, "Requesting tokens...");
    HttpWebRequest.throwIfNetworkNotAvailable(parameters.getAndroidApplicationContext(), parameters.isPowerOptCheckEnabled());
    // Check that the authority is known
    final Authority.KnownAuthorityResult authorityResult = Authority.getKnownAuthorityResult(parameters.getAuthority());
    if (!authorityResult.getKnown()) {
        throw authorityResult.getClientException();
    }
    final TokenRequest refreshTokenRequest = strategy.createRefreshTokenRequest(parameters.getAuthenticationScheme());
    refreshTokenRequest.setClientId(parameters.getClientId());
    refreshTokenRequest.setScope(TextUtils.join(" ", parameters.getScopes()));
    refreshTokenRequest.setRefreshToken(refreshToken.getSecret());
    if (refreshTokenRequest instanceof MicrosoftTokenRequest) {
        ((MicrosoftTokenRequest) refreshTokenRequest).setClaims(parameters.getClaimsRequestJson());
        ((MicrosoftTokenRequest) refreshTokenRequest).setClientAppName(parameters.getApplicationName());
        ((MicrosoftTokenRequest) refreshTokenRequest).setClientAppVersion(parameters.getApplicationVersion());
    }
    // NOTE: this should be moved to the strategy; however requires a larger refactor
    if (parameters.getSdkType() == SdkType.ADAL) {
        ((MicrosoftTokenRequest) refreshTokenRequest).setIdTokenVersion("1");
    }
    // Set Broker version to Token Request if it's a brokered request.
    if (parameters instanceof BrokerSilentTokenCommandParameters) {
        ((MicrosoftTokenRequest) refreshTokenRequest).setBrokerVersion(((BrokerSilentTokenCommandParameters) parameters).getBrokerVersion());
    }
    if (!StringExtensions.isNullOrBlank(refreshTokenRequest.getScope())) {
        Logger.infoPII(TAG + methodName, "Scopes: [" + refreshTokenRequest.getScope() + "]");
    }
    return strategyRequestToken(strategy, refreshTokenRequest);
}
Also used : BrokerSilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerSilentTokenCommandParameters) AzureActiveDirectoryAuthority(com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority) Authority(com.microsoft.identity.common.internal.authorities.Authority) 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)

Example 4 with Authority

use of com.microsoft.identity.common.internal.authorities.Authority 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 5 with Authority

use of com.microsoft.identity.common.internal.authorities.Authority in project microsoft-authentication-library-common-for-android by AzureAD.

the class ApiStartEvent method putProperties.

public ApiStartEvent putProperties(@Nullable final CommandParameters parameters) {
    if (parameters == null) {
        return this;
    }
    if (parameters.getSdkType() != null) {
        put(Key.SDK_NAME, parameters.getSdkType().name());
    }
    put(Key.SDK_VERSION, parameters.getSdkVersion());
    // Pii
    put(Key.REDIRECT_URI, parameters.getRedirectUri());
    // Pii
    put(Key.CLIENT_ID, parameters.getClientId());
    put(Key.BROKER_PROTOCOL_VERSION, String.valueOf(parameters.getRequiredBrokerProtocolVersion()));
    if (parameters instanceof TokenCommandParameters) {
        final TokenCommandParameters tokenCommandParameters = (TokenCommandParameters) parameters;
        final Authority authority = tokenCommandParameters.getAuthority();
        if (authority != null) {
            if (authority.getAuthorityURL() != null) {
                // Pii
                put(Key.AUTHORITY, authority.getAuthorityURL().getAuthority());
            }
            put(Key.AUTHORITY_TYPE, authority.getAuthorityTypeString());
        }
        put(Key.CLAIM_REQUEST, StringUtil.isEmpty(tokenCommandParameters.getClaimsRequestJson()) ? Value.FALSE : Value.TRUE);
        if (tokenCommandParameters.getScopes() != null) {
            put(Key.SCOPE_SIZE, String.valueOf(tokenCommandParameters.getScopes().size()));
            // Pii
            put(Key.SCOPE, tokenCommandParameters.getScopes().toString());
        }
        final AbstractAuthenticationScheme authScheme = tokenCommandParameters.getAuthenticationScheme();
        if (null != authScheme) {
            put(Key.AUTHENTICATION_SCHEME, authScheme.getName());
        }
    }
    if (parameters instanceof InteractiveTokenCommandParameters) {
        final InteractiveTokenCommandParameters atOperationParameters = (InteractiveTokenCommandParameters) parameters;
        if (atOperationParameters.getAuthorizationAgent() != null) {
            put(Key.USER_AGENT, atOperationParameters.getAuthorizationAgent().name());
        }
        put(// Pii
        Key.LOGIN_HINT, atOperationParameters.getLoginHint());
        if (atOperationParameters.getExtraQueryStringParameters() != null) {
            put(// Pii
            Key.REQUEST_QUERY_PARAMS, String.valueOf(atOperationParameters.getExtraQueryStringParameters().size()));
        }
        if (atOperationParameters.getPrompt() != null) {
            put(Key.PROMPT_BEHAVIOR, atOperationParameters.getPrompt().toString());
        }
    }
    if (parameters instanceof SilentTokenCommandParameters) {
        final SilentTokenCommandParameters silentParameters = (SilentTokenCommandParameters) parameters;
        if (silentParameters.getAccount() != null) {
            // Pii
            put(Key.USER_ID, silentParameters.getAccount().getHomeAccountId());
        }
        put(Key.IS_FORCE_REFRESH, String.valueOf(silentParameters.isForceRefresh()));
    }
    if (parameters instanceof BrokerInteractiveTokenCommandParameters) {
    // TODO when integrate the telemetry with broker.
    }
    if (parameters instanceof BrokerSilentTokenCommandParameters) {
    // TODO when integrate the telemetry with broker.
    }
    return this;
}
Also used : AbstractAuthenticationScheme(com.microsoft.identity.common.internal.authscheme.AbstractAuthenticationScheme) SilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters) BrokerSilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerSilentTokenCommandParameters) BrokerSilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerSilentTokenCommandParameters) InteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.InteractiveTokenCommandParameters) BrokerInteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters) SilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters) TokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.TokenCommandParameters) BrokerSilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerSilentTokenCommandParameters) Authority(com.microsoft.identity.common.internal.authorities.Authority) InteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.InteractiveTokenCommandParameters) BrokerInteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters) BrokerInteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters)

Aggregations

Authority (com.microsoft.identity.common.internal.authorities.Authority)5 BrokerSilentTokenCommandParameters (com.microsoft.identity.common.internal.commands.parameters.BrokerSilentTokenCommandParameters)4 AzureActiveDirectoryAuthority (com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority)3 InteractiveTokenCommandParameters (com.microsoft.identity.common.internal.commands.parameters.InteractiveTokenCommandParameters)2 UUID (java.util.UUID)2 Pair (android.util.Pair)1 AbstractAuthenticationScheme (com.microsoft.identity.common.internal.authscheme.AbstractAuthenticationScheme)1 BearerAuthenticationSchemeInternal (com.microsoft.identity.common.internal.authscheme.BearerAuthenticationSchemeInternal)1 BrokerRequest (com.microsoft.identity.common.internal.broker.BrokerRequest)1 ICacheRecord (com.microsoft.identity.common.internal.cache.ICacheRecord)1 BrokerInteractiveTokenCommandParameters (com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters)1 SilentTokenCommandParameters (com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters)1 TokenCommandParameters (com.microsoft.identity.common.internal.commands.parameters.TokenCommandParameters)1 MicrosoftTokenRequest (com.microsoft.identity.common.internal.providers.microsoft.MicrosoftTokenRequest)1 AuthorizationResult (com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult)1 OAuth2Strategy (com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy)1 OAuth2StrategyParameters (com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters)1 TokenRequest (com.microsoft.identity.common.internal.providers.oauth2.TokenRequest)1 TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)1 AcquireTokenResult (com.microsoft.identity.common.internal.result.AcquireTokenResult)1