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;
}
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;
}
}
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;
}
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();
}
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);
}
Aggregations