com.google.api.client.http.BasicAuthentication Java Examples

The following examples show how to use com.google.api.client.http.BasicAuthentication. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OAuthServlet.java    From vpn-over-dns with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
	return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(),
			new NetHttpTransport(),
			new JacksonFactory(),
			// token server URL:
			// new GenericUrl("https://server.example.com/token"),
			new GenericUrl("https://accounts.google.com/o/oauth2/auth"),
			new BasicAuthentication("458072371664.apps.googleusercontent.com",
					"mBp75wknGsGu0WMzHaHhqfXT"),
			"458072371664.apps.googleusercontent.com",
			// authorization server URL:
			"https://accounts.google.com/o/oauth2/auth").
			// setCredentialStore(new JdoCredentialStore(JDOHelper.getPersistenceManagerFactory("transactions-optional")))
			setCredentialStore(new MemoryCredentialStore()).setScopes("https://mail.google.com/")
			// setCredentialStore(new MyCredentialStore())
			.build();
}
 
Example #2
Source File: SnapshotAPIRequest.java    From writelatex-git-bridge with MIT License 6 votes vote down vote up
@Override
protected void onBeforeRequest(
        HttpRequest request
) throws IOException {
    if (oauth2 != null) {
        request.setInterceptor(request1 -> {
            new BasicAuthentication(
                    USERNAME,
                    PASSWORD
            ).intercept(request1);
            oauth2.intercept(request1);
        });
    } else {
        request.setInterceptor(request1 -> {
            new BasicAuthentication(
                    USERNAME,
                    PASSWORD
            ).intercept(request1);
        });
    }
}
 
Example #3
Source File: CredentialTest.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
public void testRefreshToken_refreshTokenErrorWith500() throws Exception {
  AccessTokenTransport transport = new AccessTokenTransport();
  transport.statusCode = 500;
  Credential access =
      new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(transport)
          .setJsonFactory(JSON_FACTORY)
          .setTokenServerUrl(TOKEN_SERVER_URL)
          .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET))
          .build()
          .setExpiresInSeconds(3600L)
          .setAccessToken(ACCESS_TOKEN)
          .setRefreshToken(REFRESH_TOKEN);

  assertFalse(access.refreshToken());
  assertNotNull(access.getAccessToken());
  assertEquals("refreshToken", access.getRefreshToken());
  assertNotNull(access.getExpirationTimeMilliseconds());
}
 
Example #4
Source File: CredentialTest.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
public void testRefreshToken_refreshTokenErrorWith400() throws Exception {
  AccessTokenTransport transport = new AccessTokenTransport();
  transport.statusCode = 400;
  Credential access =
      new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(transport)
          .setJsonFactory(JSON_FACTORY)
          .setTokenServerUrl(TOKEN_SERVER_URL)
          .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET))
          .build()
          .setExpiresInSeconds(3600L)
          .setAccessToken(ACCESS_TOKEN)
          .setRefreshToken(REFRESH_TOKEN);
  try {
    access.refreshToken();
    fail("Expected " + TokenResponseException.class);
  } catch (TokenResponseException e) {
    // Expected
  }
  assertNull(access.getAccessToken());
  assertEquals("refreshToken", access.getRefreshToken());
  assertNull(access.getExpirationTimeMilliseconds());
}
 
Example #5
Source File: CredentialTest.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
private void subtestRefreshToken_request(AccessTokenTransport transport, int expectedCalls)
    throws Exception {
  Credential credential =
      new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(transport)
          .setJsonFactory(JSON_FACTORY)
          .setTokenServerUrl(TOKEN_SERVER_URL)
          .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET))
          .build()
          .setRefreshToken(REFRESH_TOKEN)
          .setAccessToken(ACCESS_TOKEN);
  HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
  HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  request.execute();

  assertEquals(expectedCalls, transport.calls);
}
 
Example #6
Source File: AuthorizationCodeFlowTest.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
public void testPKCE() {
  AuthorizationCodeFlow flow =
      new AuthorizationCodeFlow.Builder(BearerToken.queryParameterAccessMethod(),
          new AccessTokenTransport(),
          new JacksonFactory(),
          TOKEN_SERVER_URL,
          new BasicAuthentication(CLIENT_ID, CLIENT_SECRET),
          CLIENT_ID,
          "https://example.com")
      .enablePKCE()
      .build();

  AuthorizationCodeRequestUrl url = flow.newAuthorizationUrl();
  assertNotNull(url.getCodeChallenge());
  assertNotNull(url.getCodeChallengeMethod());
  Set<String> methods = new HashSet<>(Arrays.asList("plain", "s256"));
  assertTrue(methods.contains(url.getCodeChallengeMethod().toLowerCase()));
  assertTrue(url.getCodeChallenge().length() > 0);
}
 
Example #7
Source File: AuthorizationCodeFlowTest.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
public void subsetTestNewAuthorizationUrl(Collection<String> scopes) {
  AuthorizationCodeFlow flow =
      new AuthorizationCodeFlow.Builder(BearerToken.queryParameterAccessMethod(),
          new AccessTokenTransport(),
          new JacksonFactory(),
          TOKEN_SERVER_URL,
          new BasicAuthentication(CLIENT_ID, CLIENT_SECRET),
          CLIENT_ID,
          "https://example.com").setScopes(scopes).build();

  AuthorizationCodeRequestUrl url = flow.newAuthorizationUrl();
  if (scopes.isEmpty()) {
    assertNull(url.getScopes());
  } else {
    assertEquals(Joiner.on(' ').join(scopes), url.getScopes());
  }
}
 
Example #8
Source File: OAuthServletCallback.java    From vpn-over-dns with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
	return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(),
			new NetHttpTransport(),
			new JacksonFactory(),
			// token server URL:
			// new GenericUrl("https://server.example.com/token"),
			new GenericUrl("https://accounts.google.com/o/oauth2/auth"),
			new BasicAuthentication("458072371664.apps.googleusercontent.com",
					"mBp75wknGsGu0WMzHaHhqfXT"),
			"458072371664.apps.googleusercontent.com",
			// authorization server URL:
			"https://accounts.google.com/o/oauth2/auth").
			// setCredentialStore(new JdoCredentialStore(JDOHelper.getPersistenceManagerFactory("transactions-optional")))
			setCredentialStore(new MemoryCredentialStore()).setScopes("https://mail.google.com/")
			// setCredentialStore(new MyCredentialStore())
			.build();
}
 
Example #9
Source File: FileCredentialStoreTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
private Credential createCredential() {
  Credential access = new Credential.Builder(
      BearerToken.queryParameterAccessMethod()).setTransport(new AccessTokenTransport())
      .setJsonFactory(JSON_FACTORY)
      .setTokenServerUrl(TOKEN_SERVER_URL)
      .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET))
      .build()
      .setAccessToken(ACCESS_TOKEN)
      .setRefreshToken(REFRESH_TOKEN)
      .setExpirationTimeMilliseconds(EXPIRES_IN);
  return access;
}
 
Example #10
Source File: FileCredentialStoreTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
private Credential createEmptyCredential() {
  Credential access = new Credential.Builder(
      BearerToken.queryParameterAccessMethod()).setTransport(new AccessTokenTransport())
      .setJsonFactory(JSON_FACTORY)
      .setTokenServerUrl(TOKEN_SERVER_URL)
      .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET))
      .build();
  return access;
}
 
Example #11
Source File: AuthorizationCodeFlowTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public void testCredentialCreatedListener() throws IOException {
  MyCredentialCreatedListener listener = new MyCredentialCreatedListener();
  AuthorizationCodeFlow flow =
      new AuthorizationCodeFlow.Builder(BearerToken.queryParameterAccessMethod(),
          new AccessTokenTransport(),
          new JacksonFactory(),
          TOKEN_SERVER_URL,
          new BasicAuthentication(CLIENT_ID, CLIENT_SECRET),
          CLIENT_ID,
          "authorizationServerEncodedUrl").setCredentialCreatedListener(listener).build();
  assertFalse(listener.called);
  flow.createAndStoreCredential(new TokenResponse(), "userId");
  assertTrue(listener.called);
}
 
Example #12
Source File: AuthorizationCodeFlowTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public void testRefreshListeners() throws IOException {
  MyCredentialRefreshListener listener1 = new MyCredentialRefreshListener();
  MyCredentialRefreshListener listener2 = new MyCredentialRefreshListener();

  AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken
      .queryParameterAccessMethod(),
      new AccessTokenTransport(),
      new JacksonFactory(),
      TOKEN_SERVER_URL,
      new BasicAuthentication(CLIENT_ID, CLIENT_SECRET),
      CLIENT_ID,
      "authorizationServerEncodedUrl").addRefreshListener(listener1)
      .addRefreshListener(listener2).build();
  TokenResponse tokenResponse = new TokenResponse();
  tokenResponse.setAccessToken(ACCESS_TOKEN);
  tokenResponse.setRefreshToken(REFRESH_TOKEN);
  Credential cred = flow.createAndStoreCredential(tokenResponse, "userId");
  assertFalse(listener1.calledOnResponse);
  assertFalse(listener2.calledOnResponse);
  assertFalse(listener1.calledOnError);
  assertFalse(listener2.calledOnError);
  assertTrue(cred.refreshToken());
  assertTrue(listener1.calledOnResponse);
  assertTrue(listener2.calledOnResponse);
  assertFalse(listener1.calledOnError);
  assertFalse(listener2.calledOnError);
}
 
Example #13
Source File: AppEngineCredentialStoreTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
private Credential createCredential() {
  return new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(
      new MockHttpTransport())
      .setJsonFactory(new MockJsonFactory())
      .setTokenServerUrl(TOKEN_SERVER_URL)
      .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET))
      .build()
      .setAccessToken(ACCESS_TOKEN)
      .setRefreshToken(REFRESH_TOKEN)
      .setExpirationTimeMilliseconds(EXPIRES_IN);
}
 
Example #14
Source File: CredentialTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public void testRefreshToken_noRefreshToken2() throws Exception {
  AccessTokenTransport transport = new AccessTokenTransport();
  Credential access =
      new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(transport)
          .setJsonFactory(JSON_FACTORY)
          .setTokenServerUrl(TOKEN_SERVER_URL)
          .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET))
          .build()
          .setAccessToken(ACCESS_TOKEN);
  assertFalse(access.refreshToken());
  assertEquals(ACCESS_TOKEN, access.getAccessToken());
  assertNull(access.getRefreshToken());
  assertNull(access.getExpirationTimeMilliseconds());
}
 
Example #15
Source File: CredentialTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public void testRefreshToken_refreshToken() throws Exception {
  AccessTokenTransport transport = new AccessTokenTransport();
  Credential access =
      new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(transport)
          .setJsonFactory(JSON_FACTORY)
          .setTokenServerUrl(TOKEN_SERVER_URL)
          .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET))
          .build()
          .setRefreshToken(REFRESH_TOKEN)
          .setAccessToken(ACCESS_TOKEN);
  assertTrue(access.refreshToken());
  assertEquals(NEW_ACCESS_TOKEN, access.getAccessToken());
  assertEquals(NEW_REFRESH_TOKEN, access.getRefreshToken());
  assertNotNull(access.getExpirationTimeMilliseconds());
}
 
Example #16
Source File: MendeleyClient.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This Methods uses the refresh Token to retrieve a renewed access token
 * 
 * @param code Refresh Token
 * @return This returns if the request was successful.
 * @throws IOException
 * @throws TokenMgrException
 * @throws ParseException
 */
public boolean requestRefreshAccessToken(String code) throws IOException, TokenMgrException, ParseException {
 try {
   RefreshTokenRequest request =
       new RefreshTokenRequest(new NetHttpTransport(), new JacksonFactory(),
           new GenericUrl("https://api.mendeley.com/oauth/token"),code)
       	  .setRefreshToken(code)
       	  .set("redirect_uri", "https://localhost")
           .setGrantType("refresh_token")
           .setClientAuthentication(
               new BasicAuthentication("4335", "sSFcbUA38RS9Cpm7"));
   
   TokenResponse response = request.execute();
   
   this.access_token = response.getAccessToken();
   this.refresh_token = response.getRefreshToken();
   this.expires_at = this.generateExpiresAtFromExpiresIn(response.getExpiresInSeconds().intValue());
   
   updatePreferenceStore();
   refreshTokenIfNecessary();
   
   return true;
 } catch (TokenResponseException e) {
   if (e.getDetails() != null) {
     System.err.println("Error: " + e.getDetails().getError());
     if (e.getDetails().getErrorDescription() != null) {
       System.err.println(e.getDetails().getErrorDescription());
     }
     if (e.getDetails().getErrorUri() != null) {
       System.err.println(e.getDetails().getErrorUri());
     }
   } else {
     System.err.println(e.getMessage());
   }
   return false;
 }
}
 
Example #17
Source File: MendeleyClient.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This Method exchanges the authorization code for an access token. 
 * If successful the Tokens and Expiration Date will be stored.
 * 
 * @param code The authorization code from the user interface response has to be passed
 * @throws IOException
 * @throws TokenMgrException
 * @throws ParseException
 */
public void requestAccessToken(String code) throws IOException, TokenMgrException, ParseException {
 try {
   TokenResponse response =
       new AuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(),
           new GenericUrl("https://api.mendeley.com/oauth/token"),code)
           .setRedirectUri("https://localhost")
           .setGrantType("authorization_code")
           .setClientAuthentication(
               new BasicAuthentication("4335", "sSFcbUA38RS9Cpm7")).execute();
   
   this.access_token = response.getAccessToken();
   this.refresh_token = response.getRefreshToken();
   this.expires_at = this.generateExpiresAtFromExpiresIn(response.getExpiresInSeconds().intValue());
   
   updatePreferenceStore();
   refreshTokenIfNecessary();
 } catch (TokenResponseException e) {
   if (e.getDetails() != null) {
     System.err.println("Error: " + e.getDetails().getError());
     if (e.getDetails().getErrorDescription() != null) {
       System.err.println(e.getDetails().getErrorDescription());
     }
     if (e.getDetails().getErrorUri() != null) {
       System.err.println(e.getDetails().getErrorUri());
     }
   } else {
     System.err.println(e.getMessage());
   }
 }
}
 
Example #18
Source File: OIDCRequestManager.java    From android-java-connect-rest-sample with MIT License 5 votes vote down vote up
/**
 *  Exchanges a Refresh Token for a new set of tokens.
 *
 *  Note that the Token Server may require you to use the `offline_access` scope to receive
 *  Refresh Tokens.
 *
 * @param refreshToken the refresh token used to request new Access Token / idToken.
 * @return the parsed successful token response received from the token endpoint
 * @throws IOException for an error response
 */
public TokenResponse refreshTokens(String refreshToken) throws IOException {

    List<String> scopesList = Arrays.asList(scopes);

    RefreshTokenRequest request = new RefreshTokenRequest(
            AndroidHttp.newCompatibleTransport(),
            new GsonFactory(),
            new GenericUrl(tokenEndpoint),
            refreshToken);

    if (!scopesList.isEmpty()) {
        request.setScopes(scopesList);
    }

    // This are extra query parameters that can be specific to an OP. For instance prompt -> consent
    // tells the Authorization Server that it SHOULD prompt the End-User for consent before returning
    // information to the Client.
    if (extras != null) {
        for (Map.Entry<String, String> queryParam : extras.entrySet()) {
            request.set(queryParam.getKey(), queryParam.getValue());
        }
    }

    // If the oidc client is confidential (needs authentication)
    if (!TextUtils.isEmpty(clientSecret)) {
        request.setClientAuthentication(new BasicAuthentication(clientId, clientSecret));
    } else {
        request.set("client_id", clientId);
    }

    if (useOAuth2) {
        if (scopesList.contains("openid")) {
            Log.w(TAG, "Using OAuth2 only request but scopes contain values for OpenId Connect");
        }
        return request.executeUnparsed().parseAs(TokenResponse.class);
    } else {
        return IdTokenResponse.execute(request);
    }
}
 
Example #19
Source File: OAuthClient.java    From kickflip-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Asynchronously attempt to acquire an OAuth Access Token
 *
 * @param cb called when AccessToken is acquired. Always called
 *           on a background thread suitable for networking.
 */
protected void acquireAccessToken(final OAuthCallback cb) {
    if (isAccessTokenCached()) {
        // Execute the callback immediately with cached OAuth credentials
        if (VERBOSE) Log.d(TAG, "Access token cached");
        if (cb != null) {
            // Ensure networking occurs off the main thread
            // TODO: Use an ExecutorService and expose an application shutdown method to shutdown?
            new Thread(new Runnable() {
                @Override
                public void run() {
                    cb.onSuccess(getRequestFactoryFromCachedCredentials());
                }
            }).start();
        }
    } else if (mOauthInProgress && cb != null) {
        // Add the callback to the queue for execution when outstanding OAuth negotiation complete
        mCallbackQueue.add(cb);
        if (VERBOSE) Log.i(TAG, "Adding cb to queue");
    } else {
        mOauthInProgress = true;
        // Perform an OAuth Client Credentials Request
        // TODO: Replace with new Thread()
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                TokenResponse response = null;
                try {
                    if (VERBOSE)
                        Log.i(TAG, "Fetching OAuth " + mConfig.getAccessTokenRequestUrl());
                    response = new ClientCredentialsTokenRequest(new NetHttpTransport(), new JacksonFactory(), new GenericUrl(mConfig.getAccessTokenRequestUrl()))
                            .setGrantType("client_credentials")
                            .setClientAuthentication(new BasicAuthentication(mConfig.getClientId(), mConfig.getClientSecret()))
                            .execute();
                } catch (IOException e) {
                    // TODO: Alert user Kickflip down
                    //       or client credentials invalid
                    if (cb != null) {
                        postExceptionToCallback(cb, e);
                    }
                    e.printStackTrace();
                }
                if (response != null) {
                    if (VERBOSE)
                        Log.i(TAG, "Got Access Token " + response.getAccessToken().substring(0, 5) + "...");
                    storeAccessToken(response);
                    mOauthInProgress = false;
                    if (cb != null)
                        cb.onSuccess(getRequestFactoryFromAccessToken(mStorage.getString(ACCESS_TOKEN_KEY, null)));
                    executeQueuedCallbacks();
                } else {
                    mOauthInProgress = false;
                    Log.w(TAG, "Failed to get Access Token");
                }
                return null;
            }
        }.execute();
    }
}