I need my app to upload files, on the GDrive account, that can be listed and read by other user accounts (same app, other devices)
I am uploading files from aUserFileCreator#gmail.com and set the permission to anyone/reader + make it public with allowFileDiscovery
File file = driveService.files()
.create(fileMetadata, mediaContent)
.setFields("id")
.setSupportsAllDrives(true)
.setIgnoreDefaultVisibility(true)
.execute();
Permission p = new Permission();
p.setType("anyone");
p.setRole("reader");
p.setAllowFileDiscovery(true);
driveService.permissions()
.create(file.getId(), p)
.execute();
Share the file later with TheUserToListAndRead#gmail.com
Permission accessPermission = new Permission();
accessPermission.setEmailAddress("TheUserToListAndRead#gmail.com");
accessPermission.setType("user");
accessPermission.setRole("reader");
driveService.permissions().create(fileId, accessPermission).execute();
When trying to list the files, like below, I am not getting anything back
but the files are visible in the Drive app of TheUserToListAndRead#gmail.com
FileList result = driveService.files().list()
.setQ("not 'me' in owners")
.setIncludeItemsFromAllDrives(true)
.setSupportsAllDrives(true)
.setSpaces("drive,appDataFolder")
.setCorpora("allDrives")
.execute();
Alternatively I used setQ("sharedWithMe") with no success
The code works for files in the readers Drive account (only created and owned by the reader) when I remove setQ completely or set it to a mime-type of some sort
First let me say I am NOT an android developer, i do however know the google api java client library. I do not know if this works in andorid or not and would love to hear if it does.
What you are looking for is something called a service account. Service accounts are like dummy users. If you share a directory with a service account then the service account will have access to this directory without having to authorize a user to access it.
GoogleCredential credential = GoogleCredential.fromStream(new
FileInputStream("MyProject-1234.json"))
.createScoped(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN));
How to create service account credetials. just remember to enable the google drive api under library.
Related
Hello I am implementing Box API,
I want to let external user select their existing files and then want to download those files in my application.
For that I have enterprise Application and I am using JWT Authorization.
I am able to generate Access Token using this code
JWTEncryptionPreferences jwtPreferences = new JWTEncryptionPreferences();
jwtPreferences.setPublicKeyID("xxxx");
jwtPreferences.setPrivateKeyPassword("xxx");
jwtPreferences.setPrivateKey("-----BEGIN ENCRYPTED PRIVATE KEY-----\nxxxxxx\n-----END ENCRYPTED PRIVATE KEY-----\n");
jwtPreferences.setEncryptionAlgorithm(EncryptionAlgorithm.RSA_SHA_256);
BoxConfig boxConfig = new BoxConfig("xxxx", "xxxx", "xxx", jwtPreferences);
try {
BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig);
LOG.info("token --" + api.getAccessToken());
return api;
} catch (BoxAPIException e) {
}
Then I am sending this token to the front end and Opening the Content Picker using that token. Code is same as below link
https://developer.box.com/docs/box-content-picker#section-sample-html
Now I am able to open picker just like the demo. But it is specific to one account. I want to implement the same for External Users of Box.
Is this possible?
What I am missing here?
Okay. I found solution for this. Posting this if it can help anyone.
I found that picking JWT for existing app user is not a good choice.
So I have to choose OAuth2 for authenticating external users
From doc:
When to Use Choose OAuth 2 as your authentication method if:
You are only working with users that have existing Box accounts.
I was playing around with youtube api samples that they provide in this link
with JAVA
I can search for videos upload videos to specific channel and all the code that they provide works fine.
the only problem I face is "when I try to upload it opens my default browser and asks me to sign in"
like this screenshot.
here is what in my head I know it's not that simple it's just a imagination of what I want to achieve.
// String myaccount = "username#gmail.com"
// String mypassword = "123456789"
// String mychannel_id = "UCU7mv98lde1hon2DXIgGMKg"
// signin(myaccount,mypassword,mychannel_id);
// upload(video.mp4);
what I have:
client_id, client_secret in json file
the channel id, account, and the password
i was searching for about a day and all i got is ..
access token
,Token Service API
,identity toolkit api
,onBehalfOfContent,onBehalfOfContentOwner
however I don't know how they work or where I can get them
finally I have small idea I traced the code and I found it saves a file with all credentials in C://users/user-name/.oauth-credentials
it's not readable but it seems like it is used to authorize the account with the password and channel id
can I use this?
would it expire for any reason and i have to refresh and if so how can I refresh it?
thanks for help BTW
My standard AppEngine application needs to perform changes in a Google Sheet documents (among others).
To achieve this, I need to obtain a credential for service account, and somehow configure that it should act in behalf of a user.
This method allows gives me default service account credentials:
private static GoogleCredential getDefaultServiceAccountCredential() throws IOException {
return GoogleCredential.getApplicationDefault()
.createScoped(MY_SCOPES);
}
but it does not work in behalf of a user.
Following code is similar, uses other (non-default) service account, but still no impersonation happens:
private static GoogleCredential getNonDefaultServiceAccountCredential() throws IOException {
return GoogleCredential.fromStream(IncomingMailHandlerServlet.class.getResourceAsStream("/tokens/anoher-e6351a8c5b91.json"))
.createScoped(MY_SCOPES);
}
For impersonation, Google Docs (and many SO advices) mentions how to do it with use of PKCS12 file; however, that file can only be read as PrivateKey on installed application and not on AppEngine.
Is there any way to obtain impersonated credential for java application running in AppEngine?
Or, is there a trick to read from a File on AppEngine?
Note that, for all service accounts that I tried, I configured them with role Owner and with DwD (Domain-wide delegation). Is there anything else to configure?
The GoogleCredential reference offers a sample to
also use the service account flow to impersonate a user in a domain that you own. This is very similar to the service account flow above, but you additionally call GoogleCredential.Builder.setServiceAccountUser(String)
public static GoogleCredential createCredentialForServiceAccountImpersonateUser(
HttpTransport transport,
JsonFactory jsonFactory,
String serviceAccountId,
Collection<String> serviceAccountScopes,
File p12File,
String serviceAccountUser) throws GeneralSecurityException, IOException {
return new GoogleCredential.Builder().setTransport(transport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(serviceAccountId)
.setServiceAccountScopes(serviceAccountScopes)
.setServiceAccountPrivateKeyFromP12File(p12File)
.setServiceAccountUser(serviceAccountUser)
.build();
}
There are multiple options on how to access a file from App Engine Standard. Below, you have two options explained:
Option 1: the p12File (credentials file) is an App Engine Standard resource file. Check this answer to see how to access such files, code-wise. I strongly recommend this approach because
These files are only available to your code on a read-only basis and not for traffic serving.
File f = new File("path/below/my/project/directory/credentials.json");
and the appengine-web.xml should define the resource files:
<resource-files>
<include path="path/below/my/project/directory/credentials.json"/>
</resource-files>
Option 2: the credentials file is in Cloud Storage. This document explains how to reach files in Cloud Storage from App Engine Standard. But I believe it's too much of a hassle. I provided this option as well because I have mentioned it.
I am working on Google Sheets <-> Salesforce integration and developing it in Salesforce programming language - Apex on Force.com platform.
Currently I am attempting to connect to Google Sheets API. I am using Service Account Key, so Salesforce can pull the data from Google Sheets without the requirement for manual authorisation every time it sends out a query.
I am at the point where I set up the Service Account Key and I am successfully sending a request to it to obtain the access_code.
Then I am attempting to query the API, using the following class:
/****** API CALLOUT *******/
public static HttpResponse googleSheetsCallout (){
//the below line provides a string containing access token to google
string accessCode = getAccessToken();
//I found this endpoint structure online, this may be why my script
//isn't working. However, I am struggling to find the alternative.
string endpoint = 'https://sheets.googleapis.com/v4/spreadsheets/params=[SPREADSHEET ID GOES HERE]/values/[RANGE GOES HERE]?access_token=';
httpRequest req = new httpRequest();
req.setEndpoint(endpoint+accessCode);
req.setMethod('GET');
req.setTimeout(120000);
httpResponse res = new http().send(req);
System.debug ('res is ' +res);
return res;
}
When I run the function this is what the log returns:
|CALLOUT_RESPONSE|[71]|System.HttpResponse[Status=Forbidden, StatusCode=403]
|USER_DEBUG|[72]|DEBUG|res is System.HttpResponse[Status=Forbidden, StatusCode=403]
I enabled Google Sheets access in the google developer console menu, and what's interesting is when loking at the console it appears that Google notices API requests being sent out (they are appearing on the activity chart).
I solved it, and the issue was not the code itself.
The problem was sharing my sheet. To allow read/edit access to your sheet from the service account it must be shared with the Service Account ID email address, the same way it's shared with any other user. If this isn't done the script will produce 403 error.
Hello I want to build an java web application in which I want the user to tweet on his account from my java application.
Now when we are considering twitter4J the code which is it shows is using our own registered application on twitter dev portal. Its is not asking for clients credentials. So please tell me how to figure out that I just want guidance not the code.
I read many post but all are confusing and I am not understanding.
I want to make the user tweet into his/her twitter account from java web application.
Information I gathered
http://blog.blprnt.com/blog/blprnt/quick-tutorial-twitter-processing
Read this tutorial
Import the twitter4j library – you do this by simply dragging the twitter4j-2.0.8.jar file onto your sketch window. If you want to check, you should now see this file in your sketch folder, inside of a new code directory.
We’ll put the guts of this example into the setup enclosure, but you could wrap it into a function or build a simple Class around it if you’d like:
Twitter myTwitter = new Twitter("yourTwitterUserName", "yourTwitterPassword");
But now twitter 4j is upgraded to
twitter4j-3.0.3
and now Twitter is an interface. What to do
As added by juned's answer below
I have to supply for a particular user
oauth.consumerKey=*********************
oauth.consumerSecret=******************************************
oauth.accessToken=**************************************************
oauth.accessTokenSecret=******************************************
So I know for a particular registered app twitter provides this keys. But I want to know for an random user from where to get this keys.
I believe you cannot do it by simply using username and password. You need to generate the key secret token and tokensecret. Read these properties for example from a file:
oauth.consumerKey=*********************
oauth.consumerSecret=******************************************
oauth.accessToken=**************************************************
oauth.accessTokenSecret=******************************************
And then using java code use these properties to get the access to the user account for tweeting, here is the sample code:
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("*********************")
.setOAuthConsumerSecret("******************************************")
.setOAuthAccessToken("**************************************************")
.setOAuthAccessTokenSecret("******************************************");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();