Search in sources :

Example 16 with TokenResponse

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;
}
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 17 with TokenResponse

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());
}
Also used : TokenResponse(com.microsoft.identity.common.internal.providers.oauth2.TokenResponse) MicrosoftTokenResponse(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftTokenResponse) Map(java.util.Map) Test(org.junit.Test)

Example 18 with TokenResponse

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;
}
Also used : TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) OpenIdConnectCredential(org.codelibs.fess.app.web.base.login.OpenIdConnectCredential) HashMap(java.util.HashMap) IOException(java.io.IOException)

Example 19 with TokenResponse

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());
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Arrays(java.util.Arrays) URLDecoder(java.net.URLDecoder) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) MediaType(javax.ws.rs.core.MediaType) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) JsonParseException(org.eclipse.che.commons.json.JsonParseException) Map(java.util.Map) GenericUrl(com.google.api.client.http.GenericUrl) JsonHelper(org.eclipse.che.commons.json.JsonHelper) Credential(com.google.api.client.auth.oauth2.Credential) URI(java.net.URI) AuthorizationCodeRequestUrl(com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) Logger(org.slf4j.Logger) User(org.eclipse.che.security.oauth.shared.User) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) BearerToken(com.google.api.client.auth.oauth2.BearerToken) OAuthToken(org.eclipse.che.api.auth.shared.dto.OAuthToken) DtoFactory.newDto(org.eclipse.che.dto.server.DtoFactory.newDto) IOException(java.io.IOException) List(java.util.List) AuthorizationCodeResponseUrl(com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) MemoryDataStoreFactory(com.google.api.client.util.store.MemoryDataStoreFactory) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) InputStream(java.io.InputStream) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AuthorizationCodeResponseUrl(com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl) IOException(java.io.IOException)

Example 20 with TokenResponse

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;
}
Also used : TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AndroidPublisher(com.google.api.services.androidpublisher.AndroidPublisher) GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer)

Aggregations

TokenResponse (com.google.api.client.auth.oauth2.TokenResponse)48 IOException (java.io.IOException)23 GenericUrl (com.google.api.client.http.GenericUrl)22 Credential (com.google.api.client.auth.oauth2.Credential)20 ClientParametersAuthentication (com.google.api.client.auth.oauth2.ClientParametersAuthentication)16 AuthorizationCodeFlow (com.google.api.client.auth.oauth2.AuthorizationCodeFlow)15 Map (java.util.Map)13 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)12 TokenResponse (com.microsoft.identity.common.internal.providers.oauth2.TokenResponse)11 BearerToken (com.google.api.client.auth.oauth2.BearerToken)9 TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)8 Logger (org.slf4j.Logger)8 LoggerFactory (org.slf4j.LoggerFactory)8 Test (org.junit.Test)7 URL (java.net.URL)6 HashMap (java.util.HashMap)6 List (java.util.List)6 Timed (com.codahale.metrics.annotation.Timed)5 AuthorizationCodeRequestUrl (com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl)5 Collections (java.util.Collections)5