use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse 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.TokenResponse in project microsoft-authentication-library-common-for-android by AzureAD.
the class ObjectMapperTest method test_JsonToObjectMSResponseNumbersAndStuffWithDupes.
// Here we're leaving off everything that isn't a string, for now. Duplicate values overwrite.
@Test
public void test_JsonToObjectMSResponseNumbersAndStuffWithDupes() {
TokenResponse tr = ObjectMapper.deserializeJsonStringToObject(JSON_TOKEN_REQUEST_OTHER_VALUE_DUPES, TokenResponse.class);
Assert.assertEquals("idtokenval", tr.getIdToken());
final Iterator<Map.Entry<String, String>> iterator = tr.getExtraParameters().iterator();
Map.Entry<String, String> param = iterator.next();
Assert.assertEquals("client_id", param.getKey());
Assert.assertEquals(CLIENT_ID, param.getValue());
Assert.assertFalse(iterator.hasNext());
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project fess by codelibs.
the class OpenIdConnectAuthenticator method processCallback.
protected LoginCredential processCallback(final HttpServletRequest request, final String code) {
try {
final TokenResponse tr = getTokenUrl(code);
final String[] jwt = ((String) tr.get("id_token")).split("\\.");
final String jwtHeader = new String(Base64.decodeBase64(jwt[0]), Constants.UTF_8_CHARSET);
final String jwtClaim = new String(Base64.decodeBase64(jwt[1]), Constants.UTF_8_CHARSET);
final String jwtSigniture = new String(Base64.decodeBase64(jwt[2]), Constants.UTF_8_CHARSET);
if (logger.isDebugEnabled()) {
logger.debug("jwtHeader: {}", jwtHeader);
logger.debug("jwtClaim: {}", jwtClaim);
logger.debug("jwtSigniture: {}", jwtSigniture);
}
// TODO validate signiture
final Map<String, Object> attributes = new HashMap<>();
attributes.put("accesstoken", tr.getAccessToken());
attributes.put("refreshtoken", tr.getRefreshToken() == null ? "null" : tr.getRefreshToken());
attributes.put("tokentype", tr.getTokenType());
attributes.put("expire", tr.getExpiresInSeconds());
attributes.put("jwtheader", jwtHeader);
attributes.put("jwtclaim", jwtClaim);
attributes.put("jwtsign", jwtSigniture);
if (logger.isDebugEnabled()) {
logger.debug("attribute: {}", attributes);
}
parseJwtClaim(jwtClaim, attributes);
return new OpenIdConnectCredential(attributes);
} catch (final IOException e) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to process callbacked request.", e);
}
}
return null;
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project che by eclipse.
the class OAuthAuthenticator method callback.
/**
* Process callback request.
*
* @param requestUrl
* request URI. URI should contain authorization code generated by authorization server
* @param scopes
* specify exactly what type of access needed. This list must be exactly the same as list passed to the method
* {@link #getAuthenticateUrl(URL, java.util.List)}
* @return id of authenticated user
* @throws OAuthAuthenticationException
* if authentication failed or <code>requestUrl</code> does not contain required parameters, e.g. 'code'
*/
public String callback(URL requestUrl, List<String> scopes) throws OAuthAuthenticationException {
if (!isConfigured()) {
throw new OAuthAuthenticationException("Authenticator is not configured");
}
AuthorizationCodeResponseUrl authorizationCodeResponseUrl = new AuthorizationCodeResponseUrl(requestUrl.toString());
final String error = authorizationCodeResponseUrl.getError();
if (error != null) {
throw new OAuthAuthenticationException("Authentication failed: " + error);
}
final String code = authorizationCodeResponseUrl.getCode();
if (code == null) {
throw new OAuthAuthenticationException("Missing authorization code. ");
}
try {
TokenResponse tokenResponse = flow.newTokenRequest(code).setRequestInitializer(request -> {
if (request.getParser() == null) {
request.setParser(flow.getJsonFactory().createJsonObjectParser());
}
request.getHeaders().setAccept(MediaType.APPLICATION_JSON);
}).setRedirectUri(findRedirectUrl(requestUrl)).setScopes(scopes).execute();
String userId = getUserFromUrl(authorizationCodeResponseUrl);
if (userId == null) {
userId = getUser(newDto(OAuthToken.class).withToken(tokenResponse.getAccessToken())).getId();
}
flow.createAndStoreCredential(tokenResponse, userId);
return userId;
} catch (IOException ioe) {
throw new OAuthAuthenticationException(ioe.getMessage());
}
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project OsmAnd-tools by osmandapp.
the class UpdateSubscriptionImpl method getPublisherApi.
private static AndroidPublisher getPublisherApi(String file) throws JSONException, IOException {
Properties properties = new Properties();
properties.load(new FileInputStream(file));
GOOGLE_CLIENT_CODE = properties.getProperty("GOOGLE_CLIENT_CODE");
GOOGLE_CLIENT_ID = properties.getProperty("GOOGLE_CLIENT_ID");
GOOGLE_CLIENT_SECRET = properties.getProperty("GOOGLE_CLIENT_SECRET");
GOOGLE_REDIRECT_URI = properties.getProperty("GOOGLE_REDIRECT_URI");
TOKEN = properties.getProperty("TOKEN");
// getRefreshToken();
String token = TOKEN;
String accessToken = getAccessToken(token);
TokenResponse tokenResponse = new TokenResponse();
// System.out.println("refresh token=" + token);
// System.out.println("access token=" + accessToken);
tokenResponse.setAccessToken(accessToken);
tokenResponse.setRefreshToken(token);
tokenResponse.setExpiresInSeconds(3600L);
tokenResponse.setScope("https://www.googleapis.com/auth/androidpublisher");
tokenResponse.setTokenType("Bearer");
HttpRequestInitializer credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY).setClientSecrets(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET).build().setFromTokenResponse(tokenResponse);
AndroidPublisher publisher = new AndroidPublisher.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(GOOGLE_PRODUCT_NAME).build();
return publisher;
}
Aggregations