How to get Microsoft Graph API Access token using ajax call - javascript

I am using Microsoft Graph API on a SharePoint Online page to get user's events from outlook calendar. I am using ADAL.JS. When I go to that page, the page redirected to MS login to get access token from Azure AD and come to page again.
I tried to get access token using ajax call, but token does not working. I tried to call that page in iFrame on another page, but it is not getting work in iFrame.
Can you anyone suggest if I can get access token in background so that page does not redirected to Microsoft login.
We tried below code, but it is giving error as "No mailbox was found that includes the specified identity: xxxxxxx"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
requestToken();
});
var token;
function requestToken() {
$.ajax({
"async": true,
"crossDomain": true,
"url": "https://cors-anywhere.herokuapp.com/https://login.microsoftonline.com/tenantname.onmicrosoft.com/oauth2/v2.0/token", // Pass your tenant name instead of tenantname
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded"
},
"data": {
"grant_type": "client_credentials",
"client_id": "****************************", //Provide your app id
"client_secret": "******************", //Provide your client secret
"scope": "https://graph.microsoft.com/.default"
},
success: function(response) {
console.log(response);
token = response.access_token;
document.getElementById('content').innerHTML = token;
}
})
}
</script>
<p id="content"></p>
Thanks,

When I test this in my online environment follow this thread, the request fail as it require user consent(official guideline).
So I grant the app Application Permissions and approve it by admin with admin consent url(https://login.microsoftonline.com/common/adminconsent?client_id=appid&state=12345)
Now, I could access the calendar view by below endpoint:
https://graph.microsoft.com/v1.0/users/userid/calendarView/delta?startdatetime=2018-12-04T12:11:08Z&enddatetime=2019-01-04T12:11:08Z
My test code:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
requestToken();
});
var token;
function requestToken() {
$.ajax({
"async": true,
"crossDomain": true,
"url": "https://cors-anywhere.herokuapp.com/https://login.microsoftonline.com/tenant.onmicrosoft.com/oauth2/v2.0/token", // Pass your tenant name instead of sharepointtechie
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded"
},
"data": {
"grant_type": "client_credentials",
"client_id ": "xxx", //Provide your app id
"client_secret": "xxx", //Provide your client secret genereated from your app
"scope ": "https://graph.microsoft.com/.default"
},
success: function (response) {
console.log(response);
token = response.access_token;
document.getElementById('content').innerHTML = token;
$.ajax({
url: 'https://graph.microsoft.com/v1.0/users/userid/calendarView/delta?startdatetime=2018-12-04T12:11:08Z&enddatetime=2019-01-04T12:11:08Z',
type: 'GET',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer '+token+'');
},
data: {},
success: function (results) {
console.log(response);
debugger;
},
error: function (error) {
console.log("Error in getting data: " + error);
}
});
}
})
}
</script>

Thanks for the solution. I am able to get it now.
Can you please let me know if I can get outlook tasks using same bearer token.
I tried same by below URL.
https://graph.microsoft.com/beta/me/outlook/tasks
But getting access denied error.
I also tried
https://graph.microsoft.com/v1.0/users/userid/outlook/tasks
but it says "Bad request"

Related

Calling Outlook API to Add event to outlook calendar using ajax call

I need to Add an event from my database to outlook calendar for which I have been trying to make an ajax call to the outlook auth API first which looks like this
$scope.authorizeOutlook = function () {
let redirect = 'http://localhost:51419';
let clientId = 'xxx';
var authData = 'client_id=' + clientId + '&response_type=code&redirect_uri=' + redirect + '&response_mode=query&scope=https%3A%2F%2Fgraph.microsoft.com%2Fcalendars.readwrite%20&state=12345';
debugger
$.ajax({
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
type: 'POST',
host: 'https://login.microsoftonline.com',
contentType: "application/x-www-form-urlencoded",
contentLength: "600",
data: authData,
success: function (response) {
debugger;
alert(response.status);
//alert("success");
},
error: function (response) {
alert(response.status);
//alert("fail");
}
});
}
But I am getting response status as 0. What does that mean? Where am I doing it wrong?
If you use Oauth2.0, you need to add " token-type: Bearer ".
Reference from:
Get access tokens to call Microsoft Graph

Can't get facebook user's email using facebook javascript sdk

I'm using facebook authentication on my website using javascript sdk. I can get my email and name but I can't get their email, if they're loging in, only their name (it's my fb developer app).
It asks for the login, in case no one is logged in on facebook yet but get nothing happens. If I put an alert where it's supposed to login to my app and it indeed returns the name, just not the email. But if it's me I get both. Why's that?
Here's my code:
<%-- Facebook conection script--%>
<script src="//connect.facebook.net/en_US/all.js"></script>
<script> FB.init({
appId: '334351783684824',
cookie: true,
xfbml: true,
version: 'v2.8'
});
function fbAuthUser() {
FB.login(checkLoginStatus);;
}
function checkLoginStatus(response) {
if (response.status === 'connected') {
FB.api('/me', 'GET', { fields: 'email,name' }, function (response) {
alert(response.email + "; " + response.name);
Ajax(response.email, response.name);
});
}
}
function Ajax(expressao1, expressao2) {
var request = { email: expressao1, nome: expressao2 }
$.ajax({
url: 'login.aspx/LoginExterno',
method: 'post',
contentType: 'application/json',
data: JSON.stringify(request),
dataType: 'json',
success: function (resp) {
window.location.href = resp.d;
},
error: function () { }
})
}
</script>
It's supposed to login and, after getting the data, use that ajax function to access a code behind c# function that redirects the user to the index, if he/she already has an account or to the registry if he/she doesn't have one. It doesn't even go in the Ajax function, because the email parameter is undefined, probably. But when both are present it does.
So, how can I get the email?
Ok, I finally got it. On on FB.Login function, I need to add the scope and the user has to give permission. On my code, it would be like:
FB.login(checkLoginStatus,{scope: 'email'});;

CORS error when trying to post message

I have an AngularJS Application I am trying to post a message through. I am successfully able to log the user in, get the access token, and I have ensured I have my domain in the JavaScript Origins within Yammer.
Whenever I try to post a message, however, I get the following error:
The strange thing is when it does the preflight it seems OK but as the error states I can't figure out why it isn't coming back in the CORS header as I have it registered within the Yammer Client area.
Here is the code for posting:
$scope.YammerPost = function (Yammer) {
var _token = Yammer.access_token.token;
var config = {
headers: {
'Authorization': 'Bearer ' + _token
}
};
$http.post('https://api.yammer.com/api/v1/messages.json', { body: 'blah blah', group_id: XXXXXXX }, config);
}
I call that scope variable in the view via a button click.
Here is the logic I use to sign the user in:
function checkYammerLogin() {
$scope.Yammer = {};
yam.getLoginStatus(
function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response); //print user information to the console
}
else {
yam.platform.login(function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response);
}
});
}
}
);
}
I ended up finding the issue.
For some odd reason, every time I would try to use an $http post it would include an Auth token from AD (app using Azure AD for authentication).
I ended up using jQuery inside of my Angular scope function on the button click and it works as I can control the headers for the request.
$.ajax({
url: 'https://api.yammer.com/api/v1/messages.json',
type: 'post',
data: {
body: 'this is a test from jQuery using AngularJS',
group_id: <group_id>
},
headers: {
'Authorization': _token
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Fixed the issue and I can now post.
If anyone sees any issues with this practice please let me know, still a little new to angular

Try to catch all of my contacs using google api v3: ERROR

I need help. I try to catch all of contacs from Google Api V3, Auth2, but it returns this error:
GET https://www.google.com/m8/feeds/contacts/default/full?callback=jQuery171029…+gsession&issued_at=1379496709&expires_at=1379500309&_aa=0&_=1379496719602 401
(Token invalid - AuthSub token has wrong scope)
First I Sign in Google +, and then i try to do the authorization in Google Contacts:
function myContacts() {
var config = {
'client_id': clientId,
'scope': 'https://www.google.com/m8/feeds',
};
gapi.auth.authorize(config, function () {
var authParams = gapi.auth.getToken(); // from Google oAuth
$.ajax({
url: 'https://www.google.com/m8/feeds/contacts/default/full',
dataType: 'jsonp',
type: "GET",
data: authParams,
success: function (data) {
alert("success: " + JSON.stringify(data))
},
error: function (data) {
console.log("error: " + JSON.stringify(data))
}
})
});
}
Is this the correct way to do this?
Thank you
Append access_token into url as request parameter with the token fetched after authorization, instead of sending it to data.
you can't do an hxr (ajax) request given the CORS restriction from goolge.com.
you can use this library to achieve this though. It solves the Oauth login/retrieving contacts from gmail)
http://eventioz.github.io/gcontacts/

How can I get the results of a JSON POST back

I'm posting this JSON from a form page
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.7.1/dojo/dojo.js" type="text/javascript"></script>
<script type="text/javascript">
function poster()
{
var dataToPost = {grant_type: "password", username: dojo.byId("username").value, password: dojo.byId("password").value, redirect_uri: "http://localhost/default.html"};
var xhrArgs =
{
url: "https://localhost/api/did/authenticate?client_id=12345",
handleAs: 'json',
postData: dojo.toJson(dataToPost),
headers: { "Content-Type": "application/json; charset=UTF-8", "Accept" : "application/json" },
load: function(data, args)
{
alert("Data = " + data);
},
error: function(error, args)
{
alert("Error! " + error);
}
}
dojo.rawXhrPost(xhrArgs);
}
</script>
But I'm not able to get the JSON results from said POST. How can I get those results? Please help. The data I get on the load function is null
The script at https://localhost/api/did/authenticate needs to print or echo or write or otherwise return the JSON as text as it exits.
Turns out that what I was trying to do is not possible in JavaScript since I'm trying to do it from one domain into another... so the cross-domain implementation is not possible, unless I use an embedded flash object, or a proxy pass in my server. thanks for the help though...

Categories

Resources