Search in sources :

Example 1 with RefreshToken

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

the class MicrosoftStsAccountCredentialAdapter method asIdToken.

@Override
public IdTokenRecord asIdToken(MicrosoftAccount msAccount, MicrosoftRefreshToken refreshToken) {
    final long cachedAt = getCachedAt();
    IDToken msIdToken = msAccount.getIDToken();
    final IdTokenRecord idToken = new IdTokenRecord();
    // Required fields
    idToken.setHomeAccountId(refreshToken.getHomeAccountId());
    idToken.setEnvironment(refreshToken.getEnvironment());
    idToken.setRealm(msAccount.getRealm());
    idToken.setCredentialType(CredentialType.IdToken.name());
    idToken.setClientId(refreshToken.getClientId());
    idToken.setSecret(msIdToken.getRawIDToken());
    idToken.setCachedAt(String.valueOf(cachedAt));
    // Optional fields
    idToken.setAuthority(SchemaUtil.getAuthority(msIdToken));
    return idToken;
}
Also used : IdTokenRecord(com.microsoft.identity.common.internal.dto.IdTokenRecord) IDToken(com.microsoft.identity.common.internal.providers.oauth2.IDToken)

Example 2 with RefreshToken

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

the class AdalMigrationAdapter method createAccount.

/**
 * Creates a {@link MicrosoftAccount} from the supplied {@link ADALTokenCacheItem}.
 *
 * @param refreshToken The credential used to derive the new account.
 * @return The newly created MicrosoftAccount.
 */
@Nullable
public static MicrosoftAccount createAccount(@NonNull final ADALTokenCacheItem refreshToken) {
    final String methodName = ":createAccount";
    try {
        final String rawIdToken = refreshToken.getRawIdToken();
        final String uid = refreshToken.getUserInfo().getUserId();
        final String utid = refreshToken.getTenantId();
        final String environment = new URL(refreshToken.getAuthority()).getHost();
        final JsonObject clientInfo = new JsonObject();
        clientInfo.addProperty("uid", uid);
        clientInfo.addProperty("utid", utid);
        final String clientInfoJson = clientInfo.toString();
        final String base64EncodedClientInfo = new String(Base64.encode(clientInfoJson.getBytes(), 0));
        final ClientInfo clientInfoObj = new ClientInfo(base64EncodedClientInfo);
        final IDToken idToken = new IDToken(rawIdToken);
        AzureActiveDirectoryAccount account = new AzureActiveDirectoryAccount(idToken, clientInfoObj);
        account.setEnvironment(environment);
        return account;
    } catch (MalformedURLException | ServiceException e) {
        final String errorMsg = "Failed to create Account";
        Logger.error(TAG + methodName, errorMsg, null);
        Logger.errorPII(TAG + methodName, errorMsg, e);
        return null;
    }
}
Also used : AzureActiveDirectoryAccount(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryAccount) MalformedURLException(java.net.MalformedURLException) ServiceException(com.microsoft.identity.common.exception.ServiceException) JsonObject(com.google.gson.JsonObject) IDToken(com.microsoft.identity.common.internal.providers.oauth2.IDToken) ClientInfo(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo) URL(java.net.URL) Nullable(androidx.annotation.Nullable)

Example 3 with RefreshToken

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

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

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

Aggregations

OAuth2StrategyParameters (com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters)3 TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)3 URL (java.net.URL)3 Nullable (androidx.annotation.Nullable)2 ClientException (com.microsoft.identity.common.exception.ClientException)2 AzureActiveDirectoryAuthority (com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority)2 MicrosoftRefreshToken (com.microsoft.identity.common.internal.providers.microsoft.MicrosoftRefreshToken)2 MicrosoftStsOAuth2Configuration (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Configuration)2 MicrosoftStsOAuth2Strategy (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Strategy)2 MicrosoftStsTokenRequest (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenRequest)2 IDToken (com.microsoft.identity.common.internal.providers.oauth2.IDToken)2 RefreshToken (com.microsoft.identity.common.internal.providers.oauth2.RefreshToken)2 TokenRequest (com.microsoft.identity.common.internal.providers.oauth2.TokenRequest)2 UUID (java.util.UUID)2 Uri (android.net.Uri)1 JsonObject (com.google.gson.JsonObject)1 BaseAccount (com.microsoft.identity.common.BaseAccount)1 ServiceException (com.microsoft.identity.common.exception.ServiceException)1 AccountsInOneOrganization (com.microsoft.identity.common.internal.authorities.AccountsInOneOrganization)1 Authority (com.microsoft.identity.common.internal.authorities.Authority)1