Accessing OneNote notebooks with graph api with JavaScript - javascript

I am building a single page app with JavaScript to access a users OneNote notebooks.
Using this git project as a starting point: https://github.com/OfficeDev/O365-Angular-Microsoft-Graph-Connect
I set up the app in Azure AD with full permissions to MS graph.
I can login and get a bearer token, however I can't pull any information from my OneNote notebooks using this endpoint:
graph.microsoft.com/beta/me/notes/notebooks.
Here's my function:
function connectToOneNote(){
var request = {
method: 'GET',
url: 'https://graph.microsoft.com/beta/me/notes/notebooks',
};
// Execute the HTTP request.
$http(request)
.then(function (response) {
$log.debug('HTTP request to Microsoft Graph API returned successfully.', response);
response.status === 202 ? vm.requestSuccess = true : vm.requestSuccess = false;
vm.requestFinished = true;
}, function (error) {
$log.error('HTTP request to Microsoft Graph API failed.');
vm.requestSuccess= false;
vm.requestFinished = true;
});
};
I get this error: "The OneDriveForBusiness for this user account cannot be retrieved."
However when using the endpoint in the graph explorer: https://graph.microsoft.io/en-us/graph-explorer, my notebooks are retrieved without issue.
Any ideas?

Thanks for the responses. The answer for me was pretty simple. I had added the app to a newly created AD, which didn't have an O365 account associated with it. I was logging in as a global admin with an active O365 account on a different AD, but because it was a global admin, it had permissions on all AD instances. SMH.

Related

Google reCAPTCHA, 405 error and CORS issue

I am using AngularJS and trying to work with Google's reCAPTCHA,
I am using the "Explicitly render the reCAPTCHA widget" method for displaying the reCAPTCHA on my web page,
HTML code -
<script type="text/javascript">
var onloadCallback = function()
{
grecaptcha.render('loginCapcha', {
'sitekey' : 'someSiteKey',
'callback' : verifyCallback,
'theme':'dark'
});
};
var auth='';
var verifyCallback = function(response)
{
//storing the Google response in a Global js variable auth, to be used in the controller
auth = response;
var scope = angular.element(document.getElementById('loginCapcha')).scope();
scope.auth();
};
</script>
<div id="loginCapcha"></div>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
So far, I am able to achieve the needed functionality of whether the user is a Human or a Bot,
As per my code above, I have a Callback function called 'verifyCallback' in my code,
which is storing the response created by Google, in a global variable called 'auth'.
Now, the final part of reCAPCHA is calling the Google API, with "https://www.google.com/recaptcha/api/siteverify" as the URL and using a POST method,And passing it the Secret Key and the Response created by Google, which I've done in the code below.
My Controller -
_myApp.controller('loginController',['$rootScope','$scope','$http',
function($rootScope,$scope,$http){
var verified = '';
$scope.auth = function()
{
//Secret key provided by Google
secret = "someSecretKey";
/*calling the Google API, passing it the Secretkey and Response,
to the specified URL, using POST method*/
var verificationReq = {
method: 'POST',
url: 'https://www.google.com/recaptcha/api/siteverify',
headers: {
'Access-Control-Allow-Origin':'*'
},
params:{
secret: secret,
response: auth
}
}
$http(verificationReq).then(function(response)
{
if(response.data.success==true)
{
console.log("Not a Bot");
verified = true;
}
else
{
console.log("Bot or some problem");
}
}, function() {
// do on response failure
});
}
So, the Problem I am actually facing is that I am unable to hit the Google's URL, Following is the screenshot of the request I am sending and the error.
Request made -
Error Response -
As far as I understand it is related to CORS and Preflight request.So what am I doing wrong? How do I fix this problem?
As stated in google's docs https://developers.google.com/recaptcha/docs/verify
This page explains how to verify a user's response to a reCAPTCHA challenge from your application's backend.
Verification is initiated from the server, not the client.
This is an extra security step for the server to ensure requests coming from clients are legitimate. Otherwise a client could fake a response and the server would be blindly trusting that the client is a verified human.
If you get a cors error when trying to sign in with recaptcha, it could be that your backend server deployment is down.

TFS 2015 REST API Authentication

We are trying to invoke the TFS 2015 REST API's from a web-page using Javascript and have a challenge in establishing valid authentication with the TFS server.
We do not know how to generate a personal access tokens or an OAuth access tokens. The instruction below seem to apply more toward VSO than on-premise TFS.
https://www.visualstudio.com/en-us/integrate/get-started/rest/basics
How can I generate an authentication key/token?
UPDATE: As on Mar 2017, the latest release of On-Prem TFS supports creating personal access tokens for all users. Using the below javascript code by #Elmar you can make requests to update, edit TFS workitems from REST API.
The OAuth mechanism is used against the VSO api at the time of writing this as you've seemingly identified. official docs for VSO OAuth tokens here.
For on-prem however, the following is required:
Via a javascript client (note I'm using jquery for the ajax request here)
Since alternative creds or token based auth isn't available on-prem to match current vso implementation; You can consider the following approach: If you have admin permissions on the TFS app tier, you can configure basic authentication for the tfs application in IIS, and set the default domain.
And then invoke as follows:
var self = this;
self.tasksURI = 'https://<SERVER>/tfs/<COLLECTION>/<PROJECT>/_apis/build/builds?api-version=2.0';
self.username = "<USERNAME>"; //basic username so no domain here.
self.password = "<PASSWORD>";
self.ajax = function (uri, method, data) {
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify(data),
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(self.username + ":" + self.password));
},
error: function (jqXHR) {
console.log("ajax error " + jqXHR.status);
}
};
return $.ajax(request);
}
self.ajax(self.tasksURI, 'GET').done(function (data) {
alert(data);
});
IMPORTANT NOTE! : If you enable basic auth you really should configure your site to use https too or your credentials will be sent in clear text (as indicated in the warning seen -> top right of the image above).
Via a .NET client
In on-prem (currently rtm'd: 2015 update 1) the api is generally gated/fenced off with NTLM, meaning a pre-flight request is made, 401 returned from server to challenge for auth, in this case, setting the request Credential as follows allows the request to auth against the server once the preflight challenge is received.
To accommodate the challenge you can do this:
request.Credentials = new NetworkCredential(this.UserName, this.Password);
//you may want to specify a domain too
If you've enabled basic auth for tfs on prem you can attempt authenticating as follows, this pattern matches the mechanism used when invoking vso after enabling alternative credentials in the ui:
request.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(this.UserName + ":" + this.Password));
Note: In some code I modified a few weeks ago; support for both VSO and on-prem was required so I used the two patterns above to deal with the specific scenario.
My question is old but as on Mar 2017, the latest release of On-Prem TFS supports creating personal access tokens for all users. Using the javascript code by #Elmar you can make requests to update, edit TFS workitems from REST API.
If possible, I would recommend using the .NET client libraries for Visual Studio Team Services (and TFS):
https://www.visualstudio.com/en-us/docs/integrate/get-started/client-libraries/dotnet
You can use windows authentication (which is what I needed). After including the following nuget packages in my code:
Microsoft.TeamFoundationServer.Client
Microsoft.VisualStudio.Services.Client
Microsoft.VisualStudio.Services.InteractiveClient
I was able to write this code:
// Create instance of VssConnection using Windows credentials (NTLM)
var connection = new VssConnection(new Uri("http://mytfsserver:8080/tfs/CollectionName"), new VssClientCredentials());
// Create instance of WorkItemTrackingHttpClient using VssConnection
var gitClient = connection.GetClient<GitHttpClient>();
var items = gitClient.GetRepositoriesAsync().Result;
foreach (var item in items)
{
Console.WriteLine(item.Name);
}
See also: https://www.visualstudio.com/en-us/docs/integrate/get-started/client-libraries/samples

Javascript SDK delete request issuing unexpected OAuthException

Using the code from the docs:
function deleteRequest(requestId) {
FB.api(requestId, 'delete', function(response) {
console.log(response);
});
}
I am returned an error:
(#2) App Request Recipient Must Be Specified: The recipient for this app request must be specified through a user-signed access token or the fully specified app request ID.
I'm definitely connected to the FB REST before this, any thoughts?
if your app has migrated to Requests 2.0 efficient, than the requestId must contain both the apprequest id and the user id with _ between (because the same apprequest might be sent to multiple users)
for example:
apprequest=1111111 and
user_id=2222222
then the requestId will be 1111111_2222222
function deleteRequest(appRequestId, userId) {
FB.api(appRequestId+"_"+userId, 'delete', function(response) {
console.log(response);
});
}
If you use the C# facebook SDK you can use this:
var fb = new FacebookClient(Config.FacebookAppId, Config.FacebookAppSecret);
var result = fb.Delete(string.Format("{0}_{1}?access_token={2}", facebookRequestId, facebookUserId, fb.AccessToken));
(see also this question: Facebook Deleting Requests)

Should I handle CODE using Javascript SDK FB.login POP-UP or is it handled automatically to gain the access_token?

In the authentication flow documentation here it mentions the CODE which is returned upon oAuth authentication.
Is this required for the Javascript SDK or is this handled automatically in the background in this code?
By "is this required?" I mean, do I have to handle this code to verify the authenticity of the request, or does the JavaScript SDK use the code automatically to gain the access_token.
The documentation explains the client side flow, and how to get the access token using the 'code' so until now. I've been assuming that the SDK manages this automatically in the background, because it produces an access code as response.authResponse.accessToken.
FB.login(function(response) {
if (response.authResponse) {
// User is logged in to Facebook and accepted permissions
// Assign the variables required
var access_token = response.authResponse.accessToken;
var fb_uid = response.authResponse.userID;
alert(dump(response.authResponse));
// Construct data string to pass to create temporary session using PHP
var fbDataString = "uid=" + fb_uid + "&access_token=" + access_token;
// Call doLogin.php to log the user in
$.ajax({
type: "POST",
url: "ajax/doLogin.php",
data: fbDataString,
dataType: "json",
success: function(data) {
// Get JSON response
if (data.result == "failure")
{
alert(data.error_message);
window.location.reload();
return false;
}
else if (data.result == "success")
{
window.location.reload();
return true;
}
},
error: function() {
return false;
}
});
} else {
// user is not logged in and did not accept any permissions
return false;
}
}, {scope:'publish_stream,email'});
I would like to know, because I want to ensure that my code is secure.
From the documentation
With this code in hand, you can proceed to the next step, app authentication, to gain the access token you need to make API calls.
In order to authenticate your app, you must pass the authorization code and your app secret to the Graph API token endpoint at https://graph.facebook.com/oauth/access_token. The app secret is available from the Developer App and should not be shared with anyone or embedded in any code that you will distribute (you should use the client-side flow for these scenarios).
If you plan on using the FB.api function to make calls to their Graph API, then you need the code to get the access token. But if you only need to authenticate the user, then what you have will do that just fine.

Is there a JavaScript API for sending notifications to Facebook users?

I am currently developing a Facebook application on a website that would need to send a notification to the app's users without using a user interface dialog. After reading some blogs I concluded that the option is available in example in PHP API only. I could only find this example:
http://developers.facebook.com/docs/channels/
Is there a JavaScript API to do this?
After some sort of more reading, I found out that FB.api could handle graph object apis and also the rest apis which are to be deprecated, and I got the following working:
FB.api('/1175241653/apprequests', 'post',
{ message: "This is a Good Request!!" },
function (response) {
if (!response || response.error) {
alert('Error occured , Request Failed :(( ');
} else {
alert('Request is sent successfully');
}
});
However, that id number 1175241653 does not work if the logged in user's id is not that id.
Therefore this would required the same functionaliy that Facebook uses to retrieve the ID of whomever signed into the application. Is there any way to do this?
Now , I got this working in all means and I'd like to share it with those who may deal with :))
lets say 1st as to do a single app request from ur application to any of facebook registered users in your application would be like this:
var data =
{
message: "Hey there, something good happened over here !",
access_token: "AAADdf39DLxgBANEwZA9ZCfZCSbtdfcZBtstWMMsW5JiZBjVW2Ucx234sedhHSZCm8aEABzvhWPBNWi1bTKwZBq0EcgZD"
}
FB.api('/68751034/apprequests',
'post',
data,
function (response) {
console.log(response);
if (!response || response.error) {
} else {
}
});
access_token should be provided as to authenticate the request from the application to the registered user.
If you do not know about access tokens, you can read about it over at the facebook site:
http://developers.facebook.com/docs/authentication/
Also, if you want to send batch requests to a set of users in one request call, there's a support page from the facebook site about that too:
http://developers.facebook.com/docs/reference/api/batch/
and here's a sample of what I mean :
var _batch = [];
for (var i = 0; i < _socialids.length; i++) {
_batch.push({
method: 'post',
relative_url: _socialids[i] + '/apprequests/?access_token=' + _accessTokens[i],
body: "message= This is a request sent to many users" });
}
if (_batch.length > 0) {
FB.api('/', 'POST', { batch: _batch }, function (res) {
// Do whatever when the batch request is sent
});
}

Categories