How to get file content on O365 sharepoint folder using graph API - microsoft-graph-api

Using Python and the adal and requests packages I'm attempting to use the MS graph API to find files on sharepoint (when providing a sharepoint site name, folder name where the file is expected to be, and name of file.
Using various calls I can manage to do the following
Get an authentication token (using user auth to an app which has full permission to use users credentials and do all read/write on files being accessed)
establish a valid session
search sites and obtain details on my current site
microsoft_info = SESSION.get('https://graph.microsoft.com/v1.0/sites?search=nameOfSite')
Obtain drive information associated with the site
for site in microsoft_info['value']:
if site['displayName'] == siteDisplayNameInput:
siteId = site['id']
drives = SESSION.get("https://graph.microsoft.com/v1.0/sites/"+siteId+"/drives")
drives = drives.json()
Obtain file information from drive of interest
for drive in drives['value']:
if(drive['name']) == folderNameInput:
driveId = drive['id']
files = SESSION.get("https://graph.microsoft.com/v1.0/drives/" + driveId +"/root/search(q='')")
files = files.json()
And then at point 6 everything falls apart and I get 404 errors returned saying that resource is not found - despite using the identifiers provided by the API which are clearly indicating the presence of a resource.
if file['name'] == 'Pipeline Pilot Forms.pptx':
print("List of properties on file")
for x in file:
print(x+" "+str(file[x]))
fileId = file['id']
print(fileId)
callToDLFile = SESSION.get("https://graph.microsoft.com/v1.0/drives/"+driveId+"/items/"+fileId+"/content"
appears to be the code that should work for this (indentation appears to have failed copying things into this, but it is all good) but it returns 404 errors - any help would be greatly appreciated on this, I don't see (in a reasonably lengthy search) anything which matches this issue exactly out there.

Related

temporary link / url for the attachments of an issue in jira cloud instance

JIRA provides a way to access the attachments of an issue using basic auth, jwt auth mechanisms. Using which we can download those files. We're able to download the files using both authentication mechanisms.
sample jwt auth:
curl -X GET --url https://{site-name}.atlassian.net/secure/attachment/1001/example.txt -H 'Authorization: jwt '
Issue / Our requirement:
But is there a way to generate temporarily accessible url for the JIRA issue's attachments which will have token embedded into the URI itself. I've added the example of that below
example url:
https://{site-name}.atlassian.net/attachment/1001/example.txt?token={temp_access_token}
While accessing / clicking on the above mentioned url the download should automatically start even if the user isn't logged into their account
Reason for our requirement:
We're creating jira cloud based service / app and one of its feature is providing access to the user's attachments through our application. Our limitation(cloud service cost) is that we can't download all the huge sized attachments and store and manage it. So we're looking for a solution using which user's can download from the JIRA's server directly
In your JWT generation steps, you can define how long the JWT should be valid. And you can attach a JWT to the URL like this: <Jira Base Url>/rest/api/3/...?jwt=.... This way, you could generate a JWT on demand and it'll only be valid for the given time that you define.
In the Java Example on the page Understanding JWT for Connect apps you can see how they are setting the expirationTime. Just do the same, on demand. Here is the important part of the code snippet:
public class JWTSample {
public String createUriWithJwt()
throws UnsupportedEncodingException, NoSuchAlgorithmException {
long issuedAt = System.currentTimeMillis() / 1000L;
long expiresAt = issuedAt + 180L;
/* ... */
JwtJsonBuilder jwtBuilder = new JsonSmartJwtJsonBuilder()
.issuedAt(issuedAt)
.expirationTime(expiresAt)
.issuer(key);
/* ... */
String jwtToken = /* ... */;
String apiUrl = baseUrl + apiPath + "?jwt=" + jwtToken;
return apiUrl;
}
}
Security concern: I'm explicitly mentioning that you should generate these links on demand because you should not set the expiration date to more than 5-10 minutes (which is already quite high). Otherwise an attacker just needs to retrieve your generated link (URLs are often logged somewhere) and is also able to retrieve the attachment as well.
Alternative Approach
Since you mentioned you'll build a service/app, why not chain the attachment download through your service? This way you wouldn't have to expose a JWT which is a potential security threat. For example: you offer a download button in your UI, this sends a HTTP request to your service and your service downloads the attachment and then forwards it to your user. However, this would not comply with your requirement to give access to unauthenticated users - if that's really what you want to do.

Reading the contents of a file in a Sharepoint group folder

I'm trying to read the contents of a file in a Sharepoint group folder using the Microsoft Graph Explorer, however the query I'm using doesn't seem to be working:
https://graph.microsoft.com/v1.0/groups/<group_id>/drive/root/children/<filename>/$value
Is there a way to define a query that I can pull the file contents in Postman if Graph Explorer can't do it?
So after doing a bit of digging, if I substitute /$value with /content in Postman, I get the following:
Failure - Status Code 0,
{
"isTrusted": true
}
Not sure what it means though.

Microsoft graph - Unable to get thumbnails

I have problem with OneDrive thumbnails.
I'm authorised as admin, I have all neccesary permissions, so I'm able to search user files and download them, edit and so on, but when I'm trying to bind thumbnail url to image src I'm getting error:
{"code":"invalidRequest","message":"The access token is not a valid token issued by SP: nameid ...}
And my query is:
https://graph.microsoft.com/v1.0/users/{id}/drive/root?$expand = thumbnails, children($expand = thumbnails($select = medium))
Do you have any solution? For first approach I was logging in from javascript and had to type a password every time, but everything worked fine

Can I POST data to a Google Web App without having to authenticate?

I'm trying to POST data to a Google Web App to automatically enter some tedious data. Whenever I try I get a response back asking me to log in, the Web App is deployed to be accessible by anyone.
Can I POST data to the form without authentication? If not, what type of authentication is required?
Edit: Quick code sample I threw together:
WebClient client = new WebClient();
var keyValue = new NameValueCollection();
keyValue.Add("agentName", "John Doe");
keyValue.Add("dayOff", "Sunday");
keyValue.Add("startTime", "8:00 AM");
Uri uri = new Uri("mywebapp url");
byte[] response = client.UploadValues(uri, "POST", keyValue);
string result = Encoding.UTF8.GetString(response);
In order to allow anyone to execute your script, even if they are not signed in to a Google account, you need to use the following settings in the "Deploy as web app" dialog:
Project version: if in doubt, select "New" to ensure that you are deploying the latest copy of the script's code.
Execute the app as: select "Me". This ensures that the "even anonymous" option will be available.
Who has access to the app: select "Anyone, even anonymous". (Note that if you select "Anyone", only users that are signed-in to a Google account will be able to execute your script.)
Once you have selected these options, click the "Update" button and copy the script URL. It should look like https://script.google.com/a/macros/<APPS DOMAIN>/s/<SCRIPT KEY>/exec. At this point an unauthenticated GET or POST to the script's URL should be successful.
Be aware that the script's execution will count against your daily Apps Script quota.

uploading a file from iOS mobile application to SharePoint

I'm working on a SharePoint mobile solution where I'm using the web services exposed in server/_vti_bin/sitedata.asmx, server/_vti_bin/Lists.asmx and server/_vti_bin/copy.asmx.
I'm able to successfully fetch the list of sites, document libraries and files using the services defined in server/_vti_bin/sitedata.asmx.
Now I'm actually trying to upload an image file from Photo Albums available in iOS to SharePoint. For this, I tried using CopyIntoItems web service, where in I'm getting the following error response.
<CopyResult ErrorCode="DestinationInvalid" ErrorMessage="The Copy web service method must be called on the same domain that contains the destination url." DestinationUrl="http://xxxxserveripxxxxxx/Shared Documents/image1.png"/>
But came to know that this service is used only if the file to be uploaded is also from the same source(i.e., from sharepoint).
Is there any other way to upload a file available in iPhone to SharePoint.
Also tired addAttachment service defiend in server/_vti_bin/Lists.asmx but I'm unable to identify the input parameters which requires list name and list Item ID.
I'm trying to upload a file to Shared Documents, so I've List Name value which is the one in curly braces of Shared Documents but now what should be the List Item Id value?
These are the details I've with regard to "Shared Documents" document library.
{
AllowAnonymousAccess = false;
AnonymousViewListItems = false;
BaseTemplate = DocumentLibrary;
BaseType = DocumentLibrary;
DefaultViewUrl = "/Shared Documents/Forms/AllItems.aspx";
Description = "Share a document with the team by adding it to this document library.";
InheritedSecurity = true;
InternalName = "{425F837A-F110-4876-98DE-C92902446935}";
LastModified = "2013-07-26 20:09:58Z";
ReadSecurity = 1;
Title = "Shared Documents";
},
So, I'm using the using InternalName value for listName tag.
What should be the value of listItemID?
Am I going in the right way or is there any other approach to upload a local file from mobile to SharePoint?
Thanks
Sudheer
Are you actually calling a URL or are you using the IP (you x'ed it out and said server IP)? If you don't have Alternate Access Mappings defined for the IP, uploads will fail but the GET requests will generally work ok.

Resources