Upload to OneDrive Business using JavaScript, outside Sharepoint - javascript

Is it possible to upload a file to Office 365 OneDrive Business (SharePoint), using pure JavaScript or jQuery, when running from an external website? (Not a SharePoint site)
I have written some C# code, which authenticates a user, and gets a FormDigestValue. But I don't know where to go from there.
None of the examples I found, seems to work for me.

you can always use the Office365 REST API to access OneDrive Business. This works well with JavaScript, especially using jQuery or AngularJS since they are more easy to use refering to REST.
You will find some examples here:
http://blogs.msdn.com/b/sharepointdev/archive/2013/08/13/access-skydrive-pro-using-the-sharepoint-2013-apis.aspx

Have you checked the new JS library for O365 APIs, including OneDrive Business service?
It should support CORS.

Yes, it is, I am doing it and it works great..
0) Please, have a look here first, it's a great study and helps to understand CORS:
https://msdn.microsoft.com/en-us/office/office365/howto/create-web-apps-using-cors-to-access-files-in-office-365
1) Register your app (www.yourdomain.name) in Azure AD (Active Directory) - you must have Office 365 and Azure AD subscription - make sure you change the manifest in Azure AD and set OAuth Implicit = Yes This allows you to get across
2) make sure you're able to receive oAuth token on your site which is registered in Azure AD - again (your.domain.name)
3) Then you AJAX (http://www.yourdomain.name) should have something like this:
xhr.open("PUT", OneDriveForBusinessEndPointURL, true);
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("Content-Type", fileInput.files[0].type);
xhr.send(fileInput.files[0]);
var FileName = fileInput.files[0];
//// Your Endpoint should be like this
var OneDriveForBusinessEndPointURl = https://mydomain-mysharepoint.com/_api/v2.0/drives/{drive-id}/items/{folder-id}:/FileName:/content
Once you get JSON with xhr.status = 201 or 200, you've won.

Related

Autodesk forge: Get access token using POST/XMLHttpRequest and Javascript?

I am new to the Autodesk API's, and trying to create the Viewer using javascript on my website, which is hosted by a 3rd party (think Weebly, Squarespace, etc.) that supports JavaScript. I can successfully get an access token if I use Postman to make the POST call to https://developer.api.autodesk.com/authentication/v1/authenticate, but that doesn't help me from a general use perspective. When I try to use XMLHttpRequest and make the same POST call from my javascript, I get an error related to CORS ("No 'Access-Control-Allow-Origin' header is present on the requested resource."). I can't find anywhere where it seems possible to use javascript to call out to Autodesk's API's and create an Autodesk viewer on my own website. Is this possible using javascript alone? Any info would be great.
I am working from the step-by-step API tutorial at https://developer.autodesk.com/en/docs/viewer/v2/tutorials/basic-viewer/, which is great, but doesn't seem to indicate how an actual POST call is worked into your application, instead of getting the token via Postman or some other testing tool.
JavaScript:
function getToken() {
var xhttp = new XMLHttpRequest();
var url = "https://developer.api.autodesk.com/authentication/v1/authenticate";
var params = "client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET&grant_type=client_credentials&scope=data:read";
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
}
Thanks.
You cannot, this is not supported. Autodesk Forge only supports OAuth from the server side, which is more secure. Explaining, your approach requires the Client ID & Secret to be exposed on the client, so the API blocks it via CORS header.
If you are using one of the following programming languages: JavaScript (node.js), .Net, Java, Ruby, simply use the existing SDK. It will make things much easier.
See here for more details.

Twitter OAuth Pin based authorization 'oob' in Google Apps Script

I am trying to use Twitter Pin-based authorization in my Google Apps Script to eventually send tweets on behalf of other uses.
I freely admit that I don't relay know what I'm doing but I have read a lot of info on the internet and feel I have tried everything.
My current Google Apps Script JavaScript code:
var method = 'post';
var url = 'https://api.twitter.com/oauth/request_token';
var consumerKey = '[my consumer key]';
var ticks = '1422745454';
var nonce = '6826266';
var options = {
'method': method,
'oauth_callback': 'oob',
'oauth_consumer_key': consumerKey,
'oauth_nonce': nonce,
'oauth_signature': 'cIFeptE5HjHp7xrp%2BZt9xFhHox4%3D',
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': ticks,
'oauth_version': '1.0'
};
var response = UrlFetchApp.fetch(url, options);
For testing I set the ticks just before each test run to the value here
The nonce is a random number between 111111 and 9999999 which is regenerated before each test run.
The oauth signature I have been generating with some c# code lifted from the linq2twitter project
I suspect the problem is the signature. I have read the twitter documentation on creating a signature and I think the C# code is doing it correctly but I am not sure.
The problem is that whatever I try I always get this error:
"Request failed for https://api.twitter.com/oauth/request_token returned code 401. Truncated server response: Failed to validate oauth signature and token (use muteHttpExceptions option to examine full response)"
I have been trying to find an example of Twitter Pin-based authorization in a Google Apps Script but have so far not found anything.
My attempts to translate examples in C#, PHP, etc. have also failed.
Please help.
Apps Script provides an Oauth API that works with UrlFetchApp, they even use twitter in their examples. Work with those if at all possible, troubleshooting signature generation is a real hassle.
https://developers.google.com/apps-script/reference/url-fetch/o-auth-config
https://developers.google.com/apps-script/articles/twitter_tutorial
If you absolutely must do it from scratch, the best approach is to get requests working with an existing library (like the c# one you mention), then work on getting your apps script to generate the exact same request.
I get the sense that is what you are doing now, so it may just be a matter of base64 encoding your Signature in the outgoing request:
https://developers.google.com/apps-script/reference/utilities/utilities#base64Encode(String)
Ultimately, it's very difficult to do the whole Oauth process manually in Apps Script. When I tried something like this from scratch about a year ago I ultimately gave up and used a Python application deployed to Google App Engine instead. I submit requests from Apps Script to the App Engine application, and the App Engine application handles Oauth and relays my requests on to the external service, before returning requests to my Apps Script. This approach comes with complications of it's own.

How to set up a Google Drive Client ID for access without a local server?

I'm wondering if it's possible to, say, open up a jsfiddle on a random computer and log in and authenticate and use the drive API, without having to have a local server running all the time? And how exactly does one go about setting this up? I'm sorry if this is a simple question but I'm just sorta lost because the instructions that I've found so far are unclear.
Edit:
So far I have, following from here and here:
Created a project via the Google Developers Console.
Opened up that project there, navigated to APIs under APIs & auth, and ensured that Drive API was enabled
Went into credentials, and clicked on "Create a new Client ID"
Selected "Web Application"
Set authorized javascript origins to http://localhost:4567
Deleted any contents in Redirect URI's and left it blank, then pressed "Create Client ID."
Took a sample like this, this, or this, and stored it in a local file named named index.html.
This wouldn't run by simply opening in a brower, so I had to host a local server
I navigated into that directory in the command line and then typed "python -m SimpleHTTPServer 4567" (without the quotes) and this hosted a local server
Opened http://localhost:4567 in my web brower, and all of these samples work fine, after copying the newly created client ID into these files where they ask for it.
I also have made a python application, to use pydrive I:
Clicked on "Create a new Client ID", then "Installed Application" and "Other", then "Create Client ID."
Next I went to the Old Google APIs Console, clicked on API Access, found that client ID, and clicked Download JSON.
I placed this client_secrets.json next to my python application, and this allowed pydrive to authenticate successfully and I could access and modify my google drive files anywhere using that client ID. Though of course I deleted this client_secrets.json before giving the application to another person, and showed them how to do this process as well.
However, beyond this, I'm a little unsure about, specifically:
How one can use the drive api in web applications without having to set up a local server, say simply by running code in jsfiddle and having requests sent through my project via using a Client ID, and
If a local server is set up that can be accessed by anyone on the web, how one can modify the above steps to allow any client to open that server's webpage to use the google drive API?
I know that I most likely need to set up a Public API access in the developers console, but am not entirely sure what Referers I should use as well. So is there a simple way to do any of this?
I also know that gspread can open google excell spreadsheets only using the client's username and password, so I'm suspecting that what I'm looking for is possible, but I'm not sure.
Okay, so I found a solution that works pretty well:
Make an OAuth.io account (It's free).
Once you're logged in, go to your oauth.io dashboard.
You should be looking at a Default App, or you can make another one it doesn't really matter.
Under "Domains & URLs whitelist", you'll see a little box that says "localhost." Type in "
http://fiddle.jshell.net/" (without the quotes) and press enter. This allows any jsfiddle to authenticate with your application
Next, we need to enable Google Drive support
Go to the Google Developers Console
Like before, navigate to Credentials under APIs and Auth.
Click "Create new Client ID"
Select Web Application
Under "Redirect URIs" put "https://oauth.io/auth" and "http://oauth.io/auth" (without quotes, on separate lines)
Under "Javascript Origins" put "https://oauth.io" and "http://oauth.io"
Press "Create Client ID"
Now go to your Oauth.io key manager. Click on Google Drive in the list to the left. Press next, and enter your client_id and client_secret that you created in the previous step (via the Google Developers Console)
Select online (at least online is preferred since offline should be for server side only)
Click on the Scope text book, and select "https://www.googleapis.com/auth/drive (View and manage the files in your google Drive)."
Press finish. Now click on the Try Auth button, and hopefully you should get some output like
{
"access_token": "ya29.AwH-1N_gnstLBuZfOR4W9CCcggKrQpMyKYV4QVEtCiIzHozNU5AfUJoYQzukALfjdiw2iOCUve7JbQ",
"token_type": "Bearer",
"expires_in": 3600,
"provider": "google_drive"
}
To use this, you can do something like:
// This only works because we're set to "No wrap - in <head>"
function ShowDriveFileList() {
var accessToken;
// Initialize OAuth with our key
OAuth.initialize('lmGlb8BaftfF4Y5en_c8XYOSq2A');
// Connect to google drive, and print out file list
OAuth.popup('google_drive').done(function (result) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "https://www.googleapis.com/drive/v2/files", false);
xmlHttp.setRequestHeader("Authorization", "Bearer " + result.access_token);
xmlHttp.send(null);
alert(xmlHttp.responseText);
}).fail(function (err) {
alert(err);
});;
}
Which you can find at http://jsfiddle.net/JMTVz/41/. This uses my oauth.io client id, but you can replace it with yours and it should work as well.
You can do the same thing using the OAuth Playground.
See How do I authorise an app (web or installed) without user intervention? (canonical ?)
Step 11 will be different. Instead of pasting the refresh token into your server app (which you don't have), you'll paste the access token into your JS in the same way as you are doing in your answer.

Read csv directly from url in html using js

I am working on html & js in which i display yahoo finance stock in table format. The data get in csv. I want js directly read data from url
The url is http://ichart.finance.yahoo.com/table.csv?s=RIL.BO
The code i try which i get from stackoverflow is working in localhost url.
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://ichart.finance.yahoo.com/table.csv?s=RIL.BO", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
lines = txtFile.responseText.split("\n"); // Will separate each line into an array
alert(allText);
}
}
}
Thanks
In order to get around the Cross Domain request restrictions put in place by the Same Origin Policy, you need an endpoint that allows you to do a JSONP request or that has enabled CORS. Unfortunately, the Yahoo! Finance endpoint has neither.
So, as James mentioned, you ned a middle man.
Usually, my recommendation for this is to use YQL, which allows you to quickly and easily build a server that sits between you and the finance site. In fact, they already have a Yahoo! Finance endpoint for exactly the data you're trying to get: link
However, as that can be unreliable, I also have a website scraper that I've used in various projects. It's hosted on Heroku and allows you to fetch almost any content from any site. I don't recommend using it for high volume projects, but for occaisional data fetches it's great. In your case, you would use it like this:
http://websitescraper.herokuapp.com/?url=http://ichart.finance.yahoo.com/table.csv?s=RIL.BO&callback=jsCallback
Edit: ichart.finance.yahoo.com has been deprecated, so this fails. Keeping it here for reference
Now that you have that out of the way, I recommend using jQuery and the csv-to-array plugin:
jQuery.getJSON('http://websitescraper.herokuapp.com/?url=http://ichart.finance.yahoo.com/table.csv?s=RIL.BO&callback=?', function (csvdata) {
console.log(csvdata.csvToArray());
});
Also, if you want to launch your own middle man, you can use the website-scraper that I've built. The source code is on GitHub and it's released under the MIT license.
You are trying to do a cross domain request so its being blocked.
You will need to write a server side script to fetch the data for you.

Mobile App for Sharepoint

I'm trying to develop a mobile app that will integrate with Sharepoint 2010 so that my clients can make approvals and stuff from a mobile device. (I'm hoping to build a HTML5/Android Native app that will call webservices and get the job done)
I looked it up and there is a RESTful API for Sharepoint that I think I can use with the ECMAScript library. Can I use this same REST API to view pending approvals, to approve/reject, etc or is the functionality limited to viewing data?
Sorry but i'm a newbie to Sharpoint. Could someone throw a little light on whether I have the right idea?
Thanks
For my needs I am using custom SOAP Web Services to do what I want in SharePoint side. Unfortunately, I have no experience with the built-in services, may be it is enough for your needs, but I don't think so. But you can start your investigation here:
http://msdn.microsoft.com/en-us/library/ff521587.aspx
http://msdn.microsoft.com/en-us/library/ee705814.aspx
Creation of custom Web Services is simple and it can give you great possibilities.
On the mobile part I am using Cordova (PhoneGap) to create mobile application (based on Html+JS). For WebService invokation I am using code like this:
var url=server+"/_layouts/CustomWebServices/MyCustomWebService.asmx";
var req = createXMLHTTPObject();
req.onreadystatechange= function(){
if(req.readyState != 4) return;
if(req.status != 200) {
if (onerror)
onerror('status: '+req.status+req.responseCode+req.responseText);
return;
}
callback();
};
var soapBodyDoc=mkXML(soapBody);
req.open("POST",url,true);
req.setRequestHeader('SOAPAction', 'http://mysite/'+soapAction);
req.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
req.setRequestHeader('Authorization', 'Basic '+auth);
req.setRequestHeader('Expect', '100-continue');
req.setRequestHeader('Connection', 'Keep-Alive');
req.send(soapBodyDoc);
As you can see I am using Basic authorization. Maybe it is not the best approach, but I am a newbie too :). I can't remember for the moment, what I exactly did to allow Basic authentication, but if you couldn't find this information let me know, I'll try to remember.
To create UI you can use jQuery mobile. It is very useful.
If you have additional questions - let me know.

Categories