本文整理汇总了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);
}
示例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);
}
示例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;
}
}
示例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);
}
示例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());
}
示例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();
}
示例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();
}
}
示例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);
}
}
示例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;
}
示例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);
}
}
示例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);
}
}
示例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);
}
}
示例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();
}
示例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");
}
示例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);
}