How can I get an oauth access token in sharepoint 2013? - javascript

I have this site here:
http://msdn.microsoft.com/en-us/library/jj164022(v=office.15).aspx
the text in some part says:
The following JavaScript code demonstrates how to make this GET request that returns a JSON representation of all of a site’s lists by using JQuery. It also assumes that you have a valid OAuth access token that is stored in the accessToken variable. You do not need the access token if you make this call from inside an app web, as you would in a SharePoint-hosted app.
jQuery.ajax({
url: http:// site url/_api/web/lists,
type: "GET",
headers: {
"ACCEPT","application/json;odata=verbose",
"Authorization", "Bearer " + accessToken
},
})
the specific question is how can I get the access token??

There doesn't seem to be a way to get the access token only using JavaScript. You need to use an app to generate the access token. See the Sharepoint OAuth Tips and FAQs for more information about how to get the token.

Your entire approach is incorrect. When it comes to accessing the REST services of a sharepoint 2013 server using javascript you don't need an Access Token. You have to use the Sharepoint 2013 cross-domain library instead.
The page at http://msdn.microsoft.com/en-us/library/jj164022.aspx explains after showing a classic REST request using an oauth token:
This request would look a little different if you are writing your app in JavaScript but using the SharePoint 2013 cross-domain library. In this case, you don’t need to provide an access token. The following code demonstrates how this request would look if you are using the cross-domain library and want to receive the OData representation of the lists as XML instead of JSON. See How to: Access SharePoint 2013 data from remote apps using the cross-domain library for more information about using the cross-domain library.
This is currently the url to that article
http://msdn.microsoft.com/en-us/library/fp179927.aspx
This should be your correct answer

This answers the question for sharepoint online.
It should be similar
for any SharePoint list with OAuth2
This talks about Postman or Fiddler, but we can modify this for JavaScript / JQuery

Related

Vimeo API GET request in javascript

I'm trying to get information about videos hosted by Vimeo (from my client's channel, so no rights issues). I'm using Javascript, specifically d3.js.
The request works fine when using the old API, with this type of url :
http://vimeo.com/api/v2/video/video_id.output
For instance, this works in d3.js :
d3.json("http://vimeo.com/api/v2/video/123456789.json", function(error,data){
console.log(data);
}):
But I can't get the new API to work as easily in a simple request, using this type of url for instance :
https://api.vimeo.com/videos?links=https://vimeo.com/123456789
What do I need to do ? Authenticate ? If so, how ? I'd be grateful to get examples in either jQuery of d3.
Vimeo's API documentation is not the best, so you have to dig a little around to actually get the information you need. In your case, you do not need to go through the whole OAuth2 loop if you are simply requesting data from endpoints that do not require user authentication, such as retrieving metadata of videos, as per your use case.
First, you will need to create a new app, by going to https://developer.vimeo.com/apps:
You can simply generate a Personal access token from your Vimeo app page under the section that says Generate an Access Token:
Remember that this token will only be visible once (so copy it when it is generated): and you have to keep it secure! The access token should be part of the Authorization header's bearer token. If you are using cURL, it will look like this:
curl -H "Authorization: Bearer <YourPersonalAccessToken>" https://api.vimeo.com/videos/123456789
Therefore, while you can do the following on your page to retrieve video metadata on the clientside, note that you are actually exposing your private token to the world:
d3.json("https://api.vimeo.com/videos/123456789/")
.header("Authorization", "Bearer <YourPersonalAccessToken>")
.get(function(error, data) {
console.log(data);
});
However, I strongly recommend that you proxy this request through your own server, i.e. create a custom endpoint on your server, say /getVimeoVideoMetadata. This API endpoint will receive the video ID, and will add the secretly stored access token you have on your server before making the request. This will mask your access token from your website visitors.

AngularJS API token

I want to build something with dribbbble's API.
As I'm reading the API docs I need a HEADER set to my API_KEY.
var token = 'MY TOKEN HERE';
$http({
method: 'GET',
url: 'https://api.dribbble.com/v1/my_user',
headers: {
'Authorization': 'Bearer ' + token
}
}).success(function() { ... });
Its possible to hide the token, preventing users to see my API KEY in page source?
Can someone explain me whats the best practice using API KEYS in $http?
Your best bet is likely going to be to create your own web service and call the dribble api server side. There is simply nothing you can do to secure information like that client side.
It's possible that dribble validates your api requests as a combination of hostname & key so it may not be is significant of an issue as you perceive it to be.
tl;dr - Nothing is secure client side.
There is nothing you can do to completely protect your API key if it's somewhere in your JavaScript. Which is why a lot of third-party services ask you to provide the domain from which you will call their API so that they can validate the key only if it originates from the domain you registered.
The right way to protect your API key is to create a server-side wrapper that will make the request, and call that from JavaScript. And even having the API keys hardcoded in your server-side code is a bad idea - the best practice is to set them as environment variables.
I usually use this method when I need to create custom headers in Angular JS.
At the beginning of a Module using $http I set my headers for get and post like this.
$http.defaults.headers.get = { 'apikeyName' : 'yourkey' }
$http.defaults.headers.post = { 'apikeyName' : 'yourkey' }
These headers will then be send everytime you use $http in that module and you won't need to specify them each time.
Its possible to hide the token, preventing users to see my API KEY in page source? No, your Angular JS is client side so every client can see the key. (see answer above)
Kind regards

how to hide or secure the token when passing from javascript to web api 2

I'm using javascript (angularjs) on UI site/project and Web API 2 and other site/project
UI project: localhost/12345
Web API : localhost/98777
UI project is calling the Web API (C#) project passing the token from UI to WebAPI for CRUD requests.
I've generated the token in ServerSide project - WEB API2 (localhost/98777), 1- username / password
2- then the url localhost:/98777/Token, passing username + password + token
wit this way it returns a token if you call it in fiddler: with content-type:
application/x-www-form-urlencoded. Like this a token is generated and written to the localDB, later on this generated token can be use in your UI app to call with javascript (ajax/angular) passing to WebAPI project.
I've implemented the bearer token calling the GET/POST/PUT methods in my client site.
localhost/12345 defined in Client site to get employee records via token:
----------------------------------------------
method: 'GET'
contenttype: 'application/json, charset=utf-8',
authorization: "Bearer 040jdU6ry....."
url: localhost/98777/api/employees/
this returns me the data all employees... it works.
localhost/98777 defined in server site web.config:
---------------------------------
<httpProtocol>
<customHEaders>
<remove name="Access-Control-Allow-Origin" />
<add name="Access-Control-Alllow-Origin" value ="*"/>
<customHeaders>
</httpProtocol>
PROBLEM?
The problem is people can do and open Developer tools in IE/Chrome/FF and see the sources of javascript and look at the token.
and then execute the code in Fiddler/ composer and add records :(.
so why do I need a token then ????
Can someone advice what part am I missing ? Is it normal that people can see the token?
This app will be used in intranet and used by developers, so I need to secure it maximum...
Is it normal that people can see the token?
Yes, it is normal. As far as I know, the token just holds identity information, as well as some claims the client can not modify. That's the only thing it can be trusted for : Identity.
Server-side you have to check (roles/rights/business rules) that the user corresponding to the token's identity is entitled to perform the requested action.
Never rely on the business rules enforcement of your client-side UI. Always double check server-side and you will be safe.
You can think about following steps,
Have a public key
Encrypt the key using Time stamp
Send the Encrypted key with the Time stamp in header
Encrypt the key in the API with the same Time stamp
Compare both keys.
Check the Time stamp with the system time.

Google OAuth2 - Exchange Access Code For Token - not working

I am currently in the process of implementing a server-side OAuth2 flow in order to authorize my application.
The JS application will be displaying YouTube Analytics data on behalf of a registered CMS account to an end user (who own's a channel partnered with the CMS account). As a result of this, the authorization stage needs to be completely hidden from the user. I am attempting to authorize once, then use the 'permanent' authorization code to retrieve access tokens as and when they're needed.
I am able to successfully authorize, and retrieve an access code. The problem begins when i attempt to exchange the access code for a token.
The HTTP POST Request to achieve this needs to look like this...
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code
I am using this code to achieve this:
var myPOSTRequest = new XMLHttpRequest();
myPOSTRequest.open('POST', 'https://accounts.google.com/o/oauth2/token', true);
myPOSTRequest.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
myPOSTRequest.send('code=' + myAuthCode + '&redirect_uri=http%3A%2F%2Flocalhost%2FCMSAuth3.html&client_id=626544306690-kn5m3vu0dcgb17au6m6pmr4giluf1cle.apps.googleusercontent.com&scope=&client_secret={my_client_secret}&grant_type=authorization_code');
I can successfully get a 200 OK response to this Request however no access token is returned, and myPOSTRequest.responseText returns an empty string.
I have played with Google's OAuth Playground - and can successfully get a token using my own credentials.
Am i missing something here?
You cannot do this, because there is the same origin policy. This is a security concept of modern browsers, which prevents javascript to get responses from another origin, than your site. This is an important concept, because it gives you the ability, to protect you against CSRF. So don't use the code authorization flow, use instead the token authorization flow.
Try and build up the full URL. Then dump it in a webbrowser. If its corect you will get the json back. You have the corect format.
https://accounts.google.com/o/oauth2/token?code=<myAuthCode>&redirect_uri=<FromGoogleAPIS>&client_id=<clientID>&client_secret={my_client_secret}&grant_type=authorization_code
Other things to check:
Make sure that you are using the same redirect_uri that is set up in google apis.
How are you getting the Authcode back? If you are riping it from the title of the page i have had issues with it not returning the full authcode in the title try checking the body of the page. This doesnt happen all the time. I just ocationally.

read wikipedia url's content using jquery, cross domain network call

jQuery.ajax(
{
url:'http://en.wikipedia.org/wiki/Football',
type:'get',
dataType:'jsonp',
success:function(data){alert(data);},
}
i want to read wikipedia page from my domain using jQuery, iam doing as above.
as expected wikipedia is sending data as pure html, but when we use $.ajax to get cross domain data it expects data received to be in json format so iam getting error and unable to read the wikiepedia response.
please suggest me how can i read wikipedia url using jquery/javascript (without involving any server side tech) also is there any api available through which i get json from wikipedia.
There is a Wikipedia API (more precisely, MediaWiki, the engine of Wikipedia, has an API). You can read more about it here: http://www.mediawiki.org/wiki/API
Here is a jQuery example on how to fetch the formatted content of the "Football" page:
$.getJSON("http://en.wikipedia.org/w/api.php?action=parse&format=json&callback=?", {page:"Football", prop:"text"}, function(data) {console.log(data);});
The endpoint has to be configured to serve jsonp which in this case it is not. It will not magically transform the normal html response type into jsonp for you. You will need to create a proxy on your server which will serve you the remote content for example if you are using php then check out this link.
You can use YQL for page fetching and get the JSONP response.
http://developer.yahoo.com/yql/console/#h=select%20*%20from%20html%20where%20url%3D%22http%3A//en.wikipedia.org/wiki/Football%22%0A

Categories