本文整理匯總了Java中com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow.createAndStoreCredential方法的典型用法代碼示例。如果您正苦於以下問題:Java GoogleAuthorizationCodeFlow.createAndStoreCredential方法的具體用法?Java GoogleAuthorizationCodeFlow.createAndStoreCredential怎麽用?Java GoogleAuthorizationCodeFlow.createAndStoreCredential使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow
的用法示例。
在下文中一共展示了GoogleAuthorizationCodeFlow.createAndStoreCredential方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: authorize
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; //導入方法依賴的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.GoogleAuthorizationCodeFlow; //導入方法依賴的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: exchangeCode
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; //導入方法依賴的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();
}
}
示例4: exchangeCode
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; //導入方法依賴的package包/類
/**
* Exchange an authorization code for OAuth 2.0 credentials.
*
* @param authorizationCode Authorization code to exchange for OAuth 2.0
* credentials.
* @return OAuth 2.0 credentials.
* @throws CodeExchangeException An error occurred.
*/
static Credential exchangeCode(String authorizationCode)
throws CodeExchangeException {
try {
GoogleAuthorizationCodeFlow flow = getFlow();
GoogleTokenResponse response = flow
.newTokenRequest(authorizationCode)
.setRedirectUri(REDIRECT_URI).execute();
return flow.createAndStoreCredential(response, null);
} catch (IOException e) {
System.err.println("An error occurred: " + e);
throw new CodeExchangeException(null);
}
}
示例5: createDriveService
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; //導入方法依賴的package包/類
public static Drive createDriveService(Environment env) throws Exception {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(new File(env.dataDir, "credentials"));
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory,
new InputStreamReader(JdBox.class.getResourceAsStream("/client_secrets.json")));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, clientSecrets, Collections.singletonList(DriveScopes.DRIVE))
.setDataStoreFactory(dataStoreFactory)
.setAccessType("offline")
.build();
Credential credential = flow.loadCredential(env.userAlias);
if (credential == null) {
String redirectUri = "urn:ietf:wg:oauth:2.0:oob";
String url = flow.newAuthorizationUrl().setRedirectUri(redirectUri).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(redirectUri).execute();
credential = flow.createAndStoreCredential(response, env.userAlias);
}
return new Drive.Builder(httpTransport, jsonFactory, credential).setApplicationName("JDBox").build();
}
示例6: authorizeViaWeb
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; //導入方法依賴的package包/類
/**
* Authorizes the installed application to access user's protected data.
*
* @param scopes OAuth 2.0 scopes
* @throws IOException
*/
private Credential authorizeViaWeb(final Collection<String> scopes, final String user) throws IOException {
// get client secrets
final GoogleClientSecrets secrets = getClientSecrets(RESOURCE_LOCATION);
// redirect to an authorization page
final String redirectUri = GoogleOAuthConstants.OOB_REDIRECT_URI;
final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, jsonFactory, secrets, scopes).build();
browse(flow.newAuthorizationUrl().setRedirectUri(redirectUri).build());
// receive authorization code and exchange it for an access token
final String code = receiver.waitForUserInput(UserMessage.get().MSG_ENTER_CODE());
final GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
// store credential and return it
return flow.createAndStoreCredential(response, user);
}
示例7: authorize
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; //導入方法依賴的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.adwords.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);
}
示例8: get
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; //導入方法依賴的package包/類
public Credential get() {
try {
GoogleClientSecrets clientSecrets = loadGoogleClientSecrets(jsonFactory);
DataStore<StoredCredential> dataStore = getStoredCredentialDataStore();
// Allow user to authorize via url.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(
httpTransport,
jsonFactory,
clientSecrets,
ImmutableList.of(
GmailScopes.GMAIL_MODIFY,
GmailScopes.GMAIL_READONLY))
.setCredentialDataStore(dataStore)
.setAccessType("offline")
.setApprovalPrompt("auto")
.build();
// First, see if we have a stored credential for the user.
Credential credential = flow.loadCredential(user.getEmailAddress());
// If we don't, prompt them to get one.
if (credential == null) {
String url = flow.newAuthorizationUrl()
.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
.build();
System.out.println("Please open the following URL in your browser then "
+ "type the authorization code:\n" + url);
// Read code entered by user.
System.out.print("Code: ");
System.out.flush();
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
String code = br.readLine();
// Generate Credential using retrieved code.
GoogleTokenResponse response = flow.newTokenRequest(code)
.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
.execute();
credential =
flow.createAndStoreCredential(response, user.getEmailAddress());
}
Gmail gmail = new Gmail.Builder(httpTransport, jsonFactory, credential)
.setApplicationName(GmailServiceModule.APP_NAME)
.build();
Profile profile = gmail.users()
.getProfile(user.getEmailAddress())
.execute();
System.out.println(profile.toPrettyString());
return credential;
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
示例9: run
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; //導入方法依賴的package包/類
@Override
public Navigation run() throws Exception {
StringBuffer requestURL = request.getRequestURL();
if(request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
AuthorizationCodeResponseUrl responseUrl = new AuthorizationCodeResponseUrl(requestURL.toString());
String code = responseUrl.getCode();
if(responseUrl.getError() != null) {
logger.severe(responseUrl.getError());
return null;
}
if (code == null) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
GoogleAuthorizationCodeFlow flow = FusionService.newFlow();
String redirectUri = FusionService.getRedirectUri(request);
GoogleTokenResponse res = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
flow.createAndStoreCredential(res, FusionService.getUserId());
logger.fine("success");
return null;
}