Hardcoding access token does not work in google spreadsheet api? - java

Using this example ( https://developers.google.com/google-apps/spreadsheets/#creating_a_spreadsheet ), I am able to login and use the Google spreadsheet api using oAuth 1.0 at the moment, because they have a java sample for that.
Here, it gets the access token + secret, and, subsequent calls to the SpreadsheetService work.
But if i want to come back a day later, and use the same access token + secret, that should work as well right?
If i do this, however, it gives me an exception:
com.google.gdata.util.AuthenticationException: Unknown authorization header
What am i missing? Do i have to redirect the user to that URL all the time?
My Java code looks as follows:
SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
OAuthHmacSha1Signer signer = new OAuthHmacSha1Signer();
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(signer);
oauthParameters.setScope(SCOPES);
oauthParameters.setOAuthConsumerKey(CONSUMER_KEY); // hardcoded variable
oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET);// hardcoded variable
oauthParameters.setOAuthTokenSecret(OAUTH_ACCESS_SECRET);// hardcoded variable
oauthParameters.setOAuthToken(OAUTH_ACCESS_TOKEN);// hardcoded variable
service.setOAuthCredentials(oauthParameters,signer);
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
What am i missing?

use the refresh token to get a new access token. The access token does not last long, maybe 1 hour, something like that. The google drive DrEdit tutorial has most of the code for doing the refresh. Was not hard to change the DrEdit code to get a new token. .... (on the other hand, google apps script also has a spreadsheet API)

Related

upload file to dropbox by java

I am working on creating a simple desktop program in Java, and I want to upload files via this program to Dropbox, but the problem is that the access token has a short life (temporary), how can I make the access token have a long life, or if I can use the App key and App secret?
I need a simple solution like a method or a java example.
Is there anything better than Dropbox in this aspect and more flexible?
Thanks for any help.
This method works fine but the access token expires after a few hours
private void testUplaod() throws FileNotFoundException, IOException, DbxException {
DbxClientV2 client;
DbxRequestConfig config = new DbxRequestConfig("dropbox/TestUplaod");
try (InputStream in = new FileInputStream("D:\\t1.txt")) {
client = new DbxClientV2(config, ACCESS_TOKEN);
FileMetadata metadata = client.files().uploadBuilder("/t1.txt")
.uploadAndFinish(in);
}
I was expecting it would work sustainably.
When you get the access token, you should also receive a refresh token. When the access token expires, you make an API call with the refresh token to get a new one.
Dropbox is no longer offering the option for creating new long-lived access tokens. Dropbox is switching to only issuing short-lived access tokens (and optional refresh tokens) instead of long-lived access tokens. You can find more information on this migration here.
Apps can still get long-term access by requesting "offline" access though, in which case the app receives a "refresh token" that can be used to retrieve new short-lived access tokens as needed, without further manual user intervention. It's not possible to get a refresh token from the "Generate" button; you need to use the OAuth flow. You can find more information in the OAuth Guide and authorization documentation. There's a basic outline of processing this flow in this blog post which may serve as a useful example.
The official Dropbox Java SDK can actually handle the process for you automatically, as long as you supply the necessary credentials, e.g., as shown retrieved in the examples.

How to refresh Google OAuth 2 Access Token Kotlin

I am trying to build an application that interacts with Google's API to pull data from the YouTube Data API. I have been able to get an access token and a refresh token by having the user authenticate manually but I want the program to run without user input. My current approach is to get a new access token each time the application run but this seems to, after some time, revoke the current refresh token for the user which I used to get a new access token. My code is below. Does anyone have any suggestions for what I am doing wrong or a better way to do this? Thanks
val scopes: ArrayList<String> = ArrayList()
scopes.add("https://www.googleapis.com/auth/youtube.readonly")
val tokenResponse: TokenResponse = GoogleRefreshTokenRequest(NetHttpTransport(), GsonFactory(), refreshToken, clientID, clientSecret)
.setScopes(scopes).setGrantType("refresh_token").execute()
tokenResponse.accessToken
val cred: GoogleCredential = GoogleCredential.Builder().setTransport(NetHttpTransport()).setJsonFactory(GsonFactory()).setClientSecrets(clientID, clientSecret).build().setAccessToken(tokenResponse.accessToken).setRefreshToken(tokenResponse.refreshToken)

How does one get the id_token using Google's OAuth2 Java Api?

I'm trying to get my head around the OAuth2 Java library that Google provides.
I have everything I need to make the request to Google's token endpoint manually using Springs built-in WebClient. However, this is very verbose and feels like re-inventing the wheel. It got me thinking that there must be a way to get this data using the classes provided by the library. Right?
Currently I am using the com.google.auth.oauth2.UserAuthorizer class to build up a request for the exchange of information.
val userCredentials: UserCredentials = UserAuthorizer.newBuilder()
.setClientId(googleOauthConfig.clientId)
.setTokenStore(tokenStore)
.setScopes(googleOauthConfig.scopes)
.setTokenServerUri(URI.create("https://oauth2.googleapis.com/token"))
.setCallbackUri(redirectUri)
.build()
.getCredentialsFromCode(authorizationCode, redirectUri)
The internals of getCredentialsFromCode() parses the response and it contains all the tokens. Including the id_token but, it gets discarded when constructing the UserCredentials object further down.
return UserCredentials.newBuilder()
.setClientId(clientId.getClientId())
.setClientSecret(clientId.getClientSecret())
.setRefreshToken(refreshToken)
.setAccessToken(accessToken)
.setHttpTransportFactory(transportFactory)
.setTokenServerUri(tokenServerUri)
.build(); // no mention of id_token
Regardless, I want to get this value so I can know basic information about the user such as their name, birthday and email address from a single request.
There does exist a method called idTokenWithAudience() which returns a Google ID Token from the refresh token response. If I call this, I get a token back that doesn't contain all the data that was available in the identically named id_token mentioned earlier making it a no-go either.
You can use IdTokenCredentials to access the ID token like so:
var credentials = UserCredentials.newBuilder()
.setClientId("...")
.setClientSecret("...")
.setRefreshToken("...")
.build()
.createScoped("openid email");
var idToken = IdTokenCredentials
.newBuilder()
.setIdTokenProvider((IdTokenProvider)credentials)
.build();
idToken.refresh();
System.out.println(idToken.getIdToken().getTokenValue());

Using scala to access google API, front end in Ruby on Rails

So my main application is written in Ruby/Rails and that is where the preliminary oauth2 action is happening. Currently I store the email and refresh token from that initial interaction, and now want to use a Scala script to retrieve data from the api in the background using the users credentials. (the point of an API no..?)
After following many examples from the google java api client example page:https://github.com/google/google-api-java-client-samples, I have found that they want me to re-authenticate users via opening a new tab and physically log in. Because I've already authenticated them, is there a way for me to simply continually retrieve data without requiring them to log in again, as this script should be running in the background?
To refresh an access token using the java-api-client library:
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
val credential = new GoogleCredential.Builder()
.setTransport(transport)
.setJsonFactory(jsonFactory)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.build()
credential.setRefreshToken(refreshToken) // get token from DB or wherever you have persisted it
credential.refreshToken()
credential.getAccessToken // returns new, refreshed access token

Setting token and tokenSecret in PayPalAPIInterfaceServiceService

i am trying to implement a Paypal API transaction Search call in java.
The following works:
PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(new File("sdk_config.properties"));
SetAccessPermissionsReq perm = new SetAccessPermissionsReq();
TransactionSearchRequestType transSearch = new TransactionSearchRequestType();
transSearch.setStartDate(startDate);
transSearch.setEndDate(endDate);
TransactionSearchReq request = new TransactionSearchReq();
request.setTransactionSearchRequest(transSearch);
TransactionSearchResponseType response = service.transactionSearch(request);
List ans = response.getPaymentTransactions();
However, I cannot find how to load a token and tokenSecret into the service object to return the transaction search for a third party Paypal account for which I have the proper tokens.
Something simple like
service.setToken(token);
does not work, as PayPalAPIInterfaceServiceService does not have a setToken method.
It is possible to initialize the 'service' object with a java.util.Properties file, but I cannot find an example of this anywhere.
Any ideas?
An example configuration file is available in the SDK itself. If you can't find it then here is a link to the current version on GitHub

Categories

Resources