本文整理汇总了Java中com.google.api.client.auth.oauth2.TokenResponse类的典型用法代码示例。如果您正苦于以下问题:Java TokenResponse类的具体用法?Java TokenResponse怎么用?Java TokenResponse使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
TokenResponse类属于com.google.api.client.auth.oauth2包,在下文中一共展示了TokenResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doInBackground
import com.google.api.client.auth.oauth2.TokenResponse; //导入依赖的package包/类
@Override
protected Boolean doInBackground(String... args) {
String authCode = args[0];
String returnedState = args[1];
boolean didStoreTokens = false;
if (secureState.equalsIgnoreCase(returnedState)) {
Log.i(TAG, "Requesting access_token with AuthCode : " + authCode);
try {
TokenResponse response = requestManager.requestTokensWithCodeGrant(authCode);
didStoreTokens = createOrUpdateAccount(response);
} catch (IOException e) {
Log.e(TAG, "Could not get response from the token endpoint", e);
}
} else {
Log.e(TAG, "Local and returned states don't match");
}
return didStoreTokens;
}
示例2: createAccount
import com.google.api.client.auth.oauth2.TokenResponse; //导入依赖的package包/类
private void createAccount(TokenResponse response) {
Log.d(TAG, "Creating account.");
String accountType = getString(R.string.account_authenticator_type);
String claimAsAccountName = "name"; //FIXME : this be some kind of oidc client parameter. What to do... what to do...
String accountName = getAccountName(response, claimAsAccountName);
account = new Account(accountName, accountType);
accountManager.getAccountManager().addAccountExplicitly(account, null, null);
Log.d(TAG, String.format("Saved tokens : (AT %1$s) (RT %2$s)", response.getAccessToken(), response.getRefreshToken()));
// Store the tokens in the account
saveTokens(response);
Log.d(TAG, "Account created.");
}
示例3: getService
import com.google.api.client.auth.oauth2.TokenResponse; //导入依赖的package包/类
/**
* Returns an authorized Bitbucket API service.
* @param authorizationCode authorization code received by the redirection
* endpoint
* @return authorized Bitbucket API service
* @throws IOException if an I/O exception has occurred
* @throws NullPointerException if this object has no client credentials
* @since 5.0
*/
public Service getService(String authorizationCode)
throws IOException {
AuthorizationCodeFlow flow = getAuthorizationCodeFlow(true);
AuthorizationCodeTokenRequest request
= flow.newTokenRequest(authorizationCode);
if (redirectionEndpointUri != null) {
request.setRedirectUri(redirectionEndpointUri);
}
TokenResponse tokenResponse = request.execute();
String tokenType = tokenResponse.getTokenType();
if (!tokenType.equals(BEARER_TOKEN_TYPE)) {
throw new UnknownServiceException("Unsupported token type");
}
return new RestService(
flow.createAndStoreCredential(tokenResponse, getUser()));
}
示例4: obtainAccessToken
import com.google.api.client.auth.oauth2.TokenResponse; //导入依赖的package包/类
@NotNull
public static GitLabToken obtainAccessToken(@NotNull String gitlabUrl, @NotNull String username, @NotNull String password, boolean sudoScope) throws IOException {
try {
final OAuthGetAccessToken tokenServerUrl = new OAuthGetAccessToken(gitlabUrl + "/oauth/token" + (sudoScope ? "?scope=api%20sudo" : ""));
final TokenResponse oauthResponse = new PasswordTokenRequest(transport, JacksonFactory.getDefaultInstance(), tokenServerUrl, username, password).execute();
return new GitLabToken(TokenType.ACCESS_TOKEN, oauthResponse.getAccessToken());
} catch (TokenResponseException e) {
if (sudoScope && e.getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
// Fallback for pre-10.2 gitlab versions
final GitlabSession session = GitlabAPI.connect(gitlabUrl, username, password);
return new GitLabToken(TokenType.PRIVATE_TOKEN, session.getPrivateToken());
} else {
throw new GitlabAPIException(e.getMessage(), e.getStatusCode(), e);
}
}
}
示例5: storeOAuth2TokenData
import com.google.api.client.auth.oauth2.TokenResponse; //导入依赖的package包/类
/**
* Stores the given OAuth 2 token response within a file data store.
* The stored token response can then retrieved using the getOAuth2TokenDataFromStore method.
*
* @param storageId a string object that is used to store the token response
* @param tokenResponse the token response containing the OAuth 2 token information.
* @return If the token response was stored or not.
*/
public Boolean storeOAuth2TokenData(String storageId, TokenResponse tokenResponse) {
Boolean wasStored = false;
try {
File oauth2StorageFolder = new File(this.context.getFilesDir(),"oauth2StorageFolder");
oauth2StorageFolder.mkdirs();
FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(oauth2StorageFolder);
DataStore<StoredCredential> storedCredentialDataStore = fileDataStoreFactory.getDataStore(storageId);
Credential oauth2Credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setFromTokenResponse(
tokenResponse);
StoredCredential storedOAuth2Credential = new StoredCredential(oauth2Credential);
storedCredentialDataStore.set(storageId,storedOAuth2Credential);
wasStored = true;
} catch ( Exception exception ) {
logInfo("Exception storing OAuth2TokenData :" + exception.getLocalizedMessage());
}
return wasStored;
}
示例6: oauth2AccessToken
import com.google.api.client.auth.oauth2.TokenResponse; //导入依赖的package包/类
/**
* Used to get an OAuth 2 access_token using the password grant_type synchronously.
*
* @param accessTokenURL The accessTokenURL
* @param username The username of the user to login
* @param password The password of the user to login
* @param clientId The clientId
* @return The TokenResponse object if we successfully gathered the token or null if the attempt was not successful.
*/
public TokenResponse oauth2AccessToken(String accessTokenURL, String username, String password, String clientId) {
validateNonEmptyParam(accessTokenURL, "accessTokenURL");
validateNonEmptyParam(username, "username");
validateNonEmptyParam(password, "password");
TokenResponse tokenResponse = null;
// Make sure clientId is just non-null. Otherwise we will possibly crash or get an unneeded exception.
if( clientId == null ) {
clientId = "";
}
try {
AuthorizationRequestUrl authorizationRequestUrl = new AuthorizationRequestUrl(accessTokenURL, clientId, Collections.singleton("token"));
PasswordTokenRequest passwordTokenRequest = new PasswordTokenRequest(new NetHttpTransport(), new JacksonFactory(), authorizationRequestUrl, username, password);
tokenResponse = passwordTokenRequest.execute();
} catch (Exception exception) {
}
return tokenResponse;
}
示例7: createCredentialWithRefreshToken
import com.google.api.client.auth.oauth2.TokenResponse; //导入依赖的package包/类
private Credential createCredentialWithRefreshToken(
HttpTransport transport,
JsonFactory jsonFactory,
TokenResponse tokenResponse) {
String clientId =
settingsService.getSettings().getCalendarSettings().getGoogleCalendarSettings().getClientId();
String clientSecret =
settingsService.getSettings().getCalendarSettings().getGoogleCalendarSettings().getClientSecret();
return new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()).setTransport(
transport)
.setJsonFactory(jsonFactory)
.setTokenServerUrl(
new GenericUrl(GOOGLEAPIS_OAUTH2_V4_TOKEN))
.setClientAuthentication(new BasicAuthentication(
clientId,
clientSecret))
.build()
.setFromTokenResponse(tokenResponse);
}
示例8: getCalendarEventCount
import com.google.api.client.auth.oauth2.TokenResponse; //导入依赖的package包/类
private Integer getCalendarEventCount() throws GeneralSecurityException, IOException {
NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
TokenResponse tokenResponse = new TokenResponse();
tokenResponse.setRefreshToken(REFRESH_TOKEN);
Credential credential = createCredentialWithRefreshToken(httpTransport, jsonFactory, tokenResponse);
Calendar calendar = new com.google.api.services.calendar.Calendar.Builder(
httpTransport, jsonFactory, credential).setApplicationName(APPLICATION_NAME).build();
Calendar.Events.List events = calendar.events().list(CALENDAR_ID);
return events.execute().getItems().size();
}
示例9: refreshAccessToken
import com.google.api.client.auth.oauth2.TokenResponse; //导入依赖的package包/类
@Override
public AccessToken refreshAccessToken() throws IOException {
logger.info("Exchanging refresh token for access token");
RefreshTokenRequest refreshRequest = requestFactory.newRequest(
oauthClient, refreshTokenSecret, tokenExchangeUrl);
TokenResponse refreshResponse = refreshRequest.execute();
logger.info("Refresh successful, got access token");
return new AccessToken(
refreshResponse.getAccessToken(),
computeExpirtyDate(refreshResponse.getExpiresInSeconds()));
}
示例10: retrieveAndStoreAccessToken
import com.google.api.client.auth.oauth2.TokenResponse; //导入依赖的package包/类
public void retrieveAndStoreAccessToken(String authorizationCode) throws IOException {
Log.i(BnConstants.TAG, "retrieveAndStoreAccessToken for code ".concat(authorizationCode));
TokenResponse tokenResponse = flow.newTokenRequest(authorizationCode).setScopes(convertScopesToString(oauth2Params.getScope())).setRedirectUri(oauth2Params.getRederictUri()).execute();
Log.i(BnConstants.TAG, "Found tokenResponse");
if (null != tokenResponse.getAccessToken()) {
Log.i(BnConstants.TAG, "Access Token : ".concat(tokenResponse.getAccessToken()));
}
if (null != tokenResponse.getRefreshToken()) {
Log.i(BnConstants.TAG, "Refresh Token : ".concat(tokenResponse.getRefreshToken()));
}
flow.createAndStoreCredential(tokenResponse, oauth2Params.getUserId());
}
示例11: getServiceAccountToken
import com.google.api.client.auth.oauth2.TokenResponse; //导入依赖的package包/类
private String getServiceAccountToken(GoogleCredential credential, String targetAudience)
throws IOException, GeneralSecurityException {
final TokenRequest request = new TokenRequest(
this.httpTransport, JSON_FACTORY,
new GenericUrl(credential.getTokenServerEncodedUrl()),
"urn:ietf:params:oauth:grant-type:jwt-bearer");
final Header header = jwtHeader();
final Payload payload = jwtPayload(
targetAudience, credential.getServiceAccountId(), credential.getTokenServerEncodedUrl());
request.put("assertion", JsonWebSignature.signUsingRsaSha256(
credential.getServiceAccountPrivateKey(), JSON_FACTORY, header, payload));
final TokenResponse response = request.execute();
return (String) response.get("id_token");
}
示例12: getUserToken
import com.google.api.client.auth.oauth2.TokenResponse; //导入依赖的package包/类
private String getUserToken(GoogleCredential credential) throws IOException {
final TokenRequest request = new RefreshTokenRequest(
this.httpTransport, JSON_FACTORY,
new GenericUrl(credential.getTokenServerEncodedUrl()),
credential.getRefreshToken())
.setClientAuthentication(credential.getClientAuthentication())
.setRequestInitializer(credential);
final TokenResponse response = request.execute();
return (String) response.get("id_token");
}
示例13: authorize
import com.google.api.client.auth.oauth2.TokenResponse; //导入依赖的package包/类
/**
* Authenticates your client application against the Ambiverse API endpoint via the OAuth 2
* protocol. Your client credentials are read from client_secrets.json on your classpath and
* exchanged for an API access token, which is stored within the API client throughout your
* session.
* @see <a href="https://developers.google.com/api-client-library/python/guide/aaa_client_secrets">Google Client Secrets file format</a>
* @return Credential object holding your API access token
* @throws IOException
*/
public static Credential authorize(HttpTransport transport, JsonFactory jsonFactory)
throws IOException {
// Read the credentials from the provided client_secrets.json file
GoogleClientSecrets clientSecrets = null;
try {
clientSecrets = GoogleClientSecrets.load(jsonFactory,
new InputStreamReader(AmbiverseApiClient.class.getClassLoader().getResourceAsStream(CLIENT_SECRETS_FILENAME)));
} catch (NullPointerException e) {
logger.severe("Copy src/main/resources/client_secrets_template.json to src/main/resources" + CLIENT_SECRETS_FILENAME + " , " +
System.lineSeparator() +
"and make sure to specify your client credentials there.");
System.exit(1);
}
// Request an access token
TokenResponse response = new ClientCredentialsTokenRequest(
transport,
jsonFactory,
new GenericUrl(clientSecrets.getWeb().getTokenUri()))
.setClientAuthentication(new ClientParametersAuthentication(
clientSecrets.getWeb().getClientId(),
clientSecrets.getWeb().getClientSecret()))
.execute();
// Return the Credential object
Credential c = new Credential(BearerToken.authorizationHeaderAccessMethod());
c.setAccessToken(response.getAccessToken());
return c;
}
示例14: execute
import com.google.api.client.auth.oauth2.TokenResponse; //导入依赖的package包/类
@Override
public TokenResponse execute() throws IOException {
MicrosoftTokenResponse response = executeUnparsed().parseAs(MicrosoftTokenResponse.class);
TokenResponse tokenResponse = new TokenResponse();
tokenResponse
.setAccessToken(response.getAccessToken())
.setScope(response.getScope())
.setRefreshToken(response.getRefreshToken())
.setExpiresInSeconds(Long.parseLong(response.getExpiresInSeconds()));
return tokenResponse;
}
示例15: saveTokens
import com.google.api.client.auth.oauth2.TokenResponse; //导入依赖的package包/类
public void saveTokens(Account account, TokenResponse tokenResponse) throws UserNotAuthenticatedWrapperException {
if (tokenResponse instanceof IdTokenResponse) {
saveToken(account, Authenticator.TOKEN_TYPE_ID, ((IdTokenResponse) tokenResponse).getIdToken());
}
saveToken(account, Authenticator.TOKEN_TYPE_ACCESS, tokenResponse.getAccessToken());
saveToken(account, Authenticator.TOKEN_TYPE_REFRESH, tokenResponse.getRefreshToken());
}