當前位置: 首頁>>代碼示例>>Java>>正文


Java GoogleTokenResponse類代碼示例

本文整理匯總了Java中com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse的典型用法代碼示例。如果您正苦於以下問題:Java GoogleTokenResponse類的具體用法?Java GoogleTokenResponse怎麽用?Java GoogleTokenResponse使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


GoogleTokenResponse類屬於com.google.api.client.googleapis.auth.oauth2包,在下文中一共展示了GoogleTokenResponse類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: authorize

import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; //導入依賴的package包/類
private static void authorize(DataStoreFactory storeFactory, String userId) throws Exception {
  // Depending on your application, there may be more appropriate ways of
  // performing the authorization flow (such as on a servlet), see
  // https://developers.google.com/api-client-library/java/google-api-java-client/oauth2#authorization_code_flow
  // for more information.
  GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
      new NetHttpTransport(),
      new JacksonFactory(),
      CLIENT_ID,
      CLIENT_SECRET,
      Arrays.asList(SCOPE))
      .setDataStoreFactory(storeFactory)
      // Set the access type to offline so that the token can be refreshed.
      // By default, the library will automatically refresh tokens when it
      // can, but this can be turned off by setting
      // api.dfp.refreshOAuth2Token=false in your ads.properties file.
      .setAccessType("offline").build();

  String authorizeUrl =
      authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();
  System.out.printf("Paste this url in your browser:%n%s%n", authorizeUrl);

  // Wait for the authorization code.
  System.out.println("Type the code you received here: ");
  @SuppressWarnings("DefaultCharset") // Reading from stdin, so default charset is appropriate.
  String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();

  // Authorize the OAuth2 token.
  GoogleAuthorizationCodeTokenRequest tokenRequest =
      authorizationFlow.newTokenRequest(authorizationCode);
  tokenRequest.setRedirectUri(CALLBACK_URL);
  GoogleTokenResponse tokenResponse = tokenRequest.execute();

  // Store the credential for the user.
  authorizationFlow.createAndStoreCredential(tokenResponse, userId);
}
 
開發者ID:googleads,項目名稱:googleads-java-lib,代碼行數:37,代碼來源:AdvancedCreateCredentialFromScratch.java

示例2: authorize

import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; //導入依賴的package包/類
/**
 * Creates a new authorized Credential object from a response token
 * @param token (String)
 * @param userId (String)
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize(String token, String userId) throws IOException
{
    // Load client secrets.
    InputStream in = new FileInputStream(Main.getBotSettingsManager().getGoogleOAuthSecret());
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = (new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES))
            .setDataStoreFactory(DATA_STORE_FACTORY)
            .setAccessType("offline")
            .build();

    // remove any account previously associated with the token
    flow.getCredentialDataStore().delete(userId);

    // create the new credential
    GoogleTokenResponse response = flow.newTokenRequest(token)
            .setRedirectUri(clientSecrets.getDetails().getRedirectUris().get(0)).execute();
    return flow.createAndStoreCredential(response, userId);
}
 
開發者ID:notem,項目名稱:Saber-Bot,代碼行數:28,代碼來源:GoogleAuth.java

示例3: getUserInfoJson

import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; //導入依賴的package包/類
private User getUserInfoJson(final String authCode) throws IOException {
    try {
        final GoogleTokenResponse response = flow.newTokenRequest(authCode)
                .setRedirectUri(getCallbackUri())
                .execute();
        final Credential credential = flow.createAndStoreCredential(response, null);
        final HttpRequest request = HTTP_TRANSPORT.createRequestFactory(credential)
                .buildGetRequest(new GenericUrl(USER_INFO_URL));
        request.getHeaders().setContentType("application/json");
        final JSONObject identity = 
                new JSONObject(request.execute().parseAsString());
        return new User(
                identity.getString("id"),
                identity.getString("email"),
                identity.getString("name"),
                identity.getString("picture"));
    } catch (JSONException ex) {
        Logger.getLogger(AuthenticationResource.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}
 
開發者ID:PacktPublishing,項目名稱:Java-9-Programming-Blueprints,代碼行數:22,代碼來源:AuthenticationResource.java

示例4: testAuthenticateTokenParseException

import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; //導入依賴的package包/類
@Test(expected = GoogleOauthException.class)
public void testAuthenticateTokenParseException() throws Exception {
    GoogleOauthAccessRequestInfo input = prepGoogleCall();

    GoogleTokenResponse googleTokenResponse = mock(GoogleTokenResponse.class);
    GoogleResponseData googleData = new GoogleResponseData(
            googleTokenResponse,
            new Person()
    );

    /* Train the mocks. */
    when(
            googleOauthService.getUserDataFromGoogle(
                    anyString(),
                    anyString(),
                    anyString(),
                    anyString()
            )
    ).thenReturn(
            googleData
    );
    when(googleTokenResponse.parseIdToken()).thenThrow(new IOException("test-io-exception"));

    /* Make the call. */
    toTest.authenticate(input);
}
 
開發者ID:healthbam,項目名稱:healthbam,代碼行數:27,代碼來源:DefaultAuthenticationServiceTest.java

示例5: getCredentials

import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; //導入依賴的package包/類
/**
 * Retrieve OAuth 2.0 credentials.
 * 
 * @return OAuth 2.0 Credential instance.
 * @throws IOException
 */
private Credential getCredentials() throws IOException {
  String code = tokenField.getText();
  HttpTransport transport = new NetHttpTransport();
  JacksonFactory jsonFactory = new JacksonFactory();
  String CLIENT_SECRET = "EPME5fbwiNLCcMsnj3jVoXeY";

  // Step 2: Exchange -->
  GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(
      transport, jsonFactory, CLIENT_ID, CLIENT_SECRET, code,
      REDIRECT_URI).execute();
  // End of Step 2 <--

  // Build a new GoogleCredential instance and return it.
  return new GoogleCredential.Builder()
      .setClientSecrets(CLIENT_ID, CLIENT_SECRET)
      .setJsonFactory(jsonFactory).setTransport(transport).build()
      .setAccessToken(response.getAccessToken())
      .setRefreshToken(response.getRefreshToken());
}
 
開發者ID:sih4sing5hong5,項目名稱:google-sites-liberation,代碼行數:26,代碼來源:GuiMain.java

示例6: getDrive

import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; //導入依賴的package包/類
public static Drive getDrive() throws IOException, Docx4JException {
 
  HttpTransport httpTransport = new NetHttpTransport();
  JsonFactory jsonFactory = new JacksonFactory();
 
  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      httpTransport, jsonFactory, getClientSecrets(jsonFactory), Arrays.asList(DriveScopes.DRIVE))
      .setAccessType("online")
      .setApprovalPrompt("auto").build();
  
  String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
  System.out.println("Please open the following URL in your browser then type the authorization code:");
  System.out.println("  " + url);
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String code = br.readLine();
  
  GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
  GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);
  
  //Create a new authorized API client
  return new Drive.Builder(httpTransport, jsonFactory, credential).build();
  
}
 
開發者ID:plutext,項目名稱:docx4j-cloud-GoogleDrive,代碼行數:24,代碼來源:CredentialsViaCommandLine.java

示例7: exchangeCode

import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; //導入依賴的package包/類
protected Credential exchangeCode(
		String authorizationCode, String redirectUri)
	throws CodeExchangeException {

	try {
		GoogleAuthorizationCodeFlow flow = getFlow();

		GoogleAuthorizationCodeTokenRequest token = flow.newTokenRequest(
			authorizationCode);

		token.setRedirectUri(redirectUri);

		GoogleTokenResponse response = token.execute();

		return flow.createAndStoreCredential(response, null);
	}
	catch (IOException e) {
		System.err.println("An error occurred: " + e);

		throw new CodeExchangeException();
	}
}
 
開發者ID:sergiogonzalez,項目名稱:google-login-hook,代碼行數:23,代碼來源:GoogleOAuth.java

示例8: handleTokens

import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; //導入依賴的package包/類
protected void handleTokens(Map<String, String> params) {
    final GoogleClientSecrets secrets = new GoogleClientSecrets().setInstalled(
            new GoogleClientSecrets.Details().
                    setClientId(params.get(constants.getApplicationClientId())).
                    setClientSecret(params.get(constants.getApplicationClientSecret()))
    );

    try {
        final GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(
                this.httpTransport,
                this.jsonFactory,
                secrets.getDetails().getClientId(),
                secrets.getDetails().getClientSecret(),
                params.get(constants.getApplicationOauthCode()),
                constants.getRedirectUri()
        ).execute();

        params.put(constants.getApplicationRefreshToken(), tokenResponse.getRefreshToken());
        params.put(constants.getApplicationAccessToken(), tokenResponse.getAccessToken());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
開發者ID:GoogleCloudPlatform,項目名稱:appengine-tck,代碼行數:24,代碼來源:ReportsFeature.java

示例9: retrieve

import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; //導入依賴的package包/類
/**
 * Retrieves a new access token by exchanging the given code with OAuth2
 * end-points.
 * @param code Exchange code.
 * @return A credential object.
 */
public Credential retrieve(String code) {
  try {
    GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(
        transport,
        jsonFactory,
        clientSecrets.getWeb().getClientId(),
        clientSecrets.getWeb().getClientSecret(),
        code,
        clientSecrets.getWeb().getRedirectUris().get(0)).execute();
    return buildEmpty().setAccessToken(response.getAccessToken());
  } catch (IOException e) {
    new RuntimeException("An unknown problem occured while retrieving token");
  }
  return null;
}
 
開發者ID:googlearchive,項目名稱:drivemarks,代碼行數:22,代碼來源:CredentialManager.java

示例10: getPrincipal

import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; //導入依賴的package包/類
/**
 * Returns the principal authenticated by {@code token}.
 *
 * @param token an instance of {@link GoogleTokenResponse}.
 * @return the principal authenticated by {@code token}.
 */
public final String getPrincipal(final GoogleTokenResponse token) {
    try {
        return token.parseIdToken().getPayload().getEmail();
    } catch (final IOException ex) {
        throw new UncheckedIOException(ex);
    }
}
 
開發者ID:travelaudience,項目名稱:nexus-proxy,代碼行數:14,代碼來源:CachingGoogleAuthCodeFlow.java

示例11: requestToken

import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; //導入依賴的package包/類
/**
 * Returns a {@link GoogleTokenResponse} corresponding to an authorization code token request based on the given
 * authorization code.
 *
 * @param authorizationCode the authorization code to use.
 * @return a {@link GoogleTokenResponse} corresponding to an auth code token request based on the given auth code.
 */
public final GoogleTokenResponse requestToken(final String authorizationCode) {
    try {
        return this.authFlow.newTokenRequest(authorizationCode).setRedirectUri(this.redirectUri).execute();
    } catch (final IOException ex) {
        throw new UncheckedIOException(ex);
    }
}
 
開發者ID:travelaudience,項目名稱:nexus-proxy,代碼行數:15,代碼來源:CachingGoogleAuthCodeFlow.java

示例12: storeCredential

import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; //導入依賴的package包/類
/**
 * Stores the credential corresponding to the specified {@link GoogleTokenResponse}.
 *
 * @param token an instance of {@link GoogleTokenResponse}.
 * @return the {@link Credential} corresponding to the specified {@link GoogleTokenResponse}.
 */
public final Credential storeCredential(final GoogleTokenResponse token) {
    try {
        return this.authFlow.createAndStoreCredential(token, this.getPrincipal(token));
    } catch (final IOException ex) {
        throw new UncheckedIOException(ex);
    }
}
 
開發者ID:travelaudience,項目名稱:nexus-proxy,代碼行數:14,代碼來源:CachingGoogleAuthCodeFlow.java

示例13: setUp

import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; //導入依賴的package包/類
public static People setUp(Context context, String serverAuthCode) throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    // Redirect URL for web based applications.
    // Can be empty too.
    String redirectUrl = "urn:ietf:wg:oauth:2.0:oob";


    // Exchange auth code for access token
    GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(
            httpTransport,
            jsonFactory,
            context.getString(R.string.clientID),
            context.getString(R.string.clientSecret),
            serverAuthCode,
            redirectUrl).execute();

    // Then, create a GoogleCredential object using the tokens from GoogleTokenResponse
    GoogleCredential credential = new GoogleCredential.Builder()
            .setClientSecrets(context.getString(R.string.clientID), context.getString(R.string.clientSecret))
            .setTransport(httpTransport)
            .setJsonFactory(jsonFactory)
            .build();

    credential.setFromTokenResponse(tokenResponse);

    // credential can then be used to access Google services
    return new People.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName(APPLICATION_NAME)
            .build();
}
 
開發者ID:Suleiman19,項目名稱:People-API-App,代碼行數:33,代碼來源:PeopleHelper.java

示例14: GoogleResponseData

import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; //導入依賴的package包/類
/**
 * Constructs a {@link GoogleResponseData}.
 *
 * @param googleOauthToken google's oauth token response
 * @param googlePlusProfile google's g+ profile response
 */
public GoogleResponseData(
        @Nonnull GoogleTokenResponse googleOauthToken,
        @Nonnull Person googlePlusProfile
) {
    this.googleOauthToken = requireNonNull(googleOauthToken, "googleOauthToken cannot be null");
    this.googlePlusProfile = requireNonNull(googlePlusProfile, "googlePlusProfile cannot be null");
}
 
開發者ID:healthbam,項目名稱:healthbam,代碼行數:14,代碼來源:GoogleResponseData.java

示例15: doGet

import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; //導入依賴的package包/類
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Check for a valid XSRF token
    String expectedToken = (String) request.getSession().getAttribute(XsrfUtils.XSRF_KEY);
    String actualToken = request.getParameter("state");
    if (!xsrfUtils.isValid(expectedToken, actualToken)) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    // Check for no errors in the OAuth process
    String[] error = request.getParameterValues(ERROR_URL_PARAM_NAME);
    if (error != null && error.length > 0) {
        response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
        return;
    }

    // Check for the presence of the response code
    String[] code = request.getParameterValues(CODE_URL_PARAM_NAME);
    if (code == null || code.length == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // Get the email address
    String requestUrl = getOAuthCodeCallbackHandlerUrl(request);
    GoogleTokenResponse tokenResponse = exchangeCodeForAccessAndRefreshTokens(code[0], requestUrl);
    String email = tokenResponse.parseIdToken().getPayload().getEmail();

    String token = establishUserAndLogin(response, email);

    request.setAttribute("email", email);
    request.setAttribute("authToken", token);
    getServletConfig().getServletContext().getRequestDispatcher("/home.jsp").forward(request,response);
}
 
開發者ID:technical-rex,項目名稱:spring-security-jwt,代碼行數:36,代碼來源:GoogleAuthorizationResponseServlet.java


注:本文中的com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。