embed feed from yammer using access token - embed

How to Embed Feed from yammer using access token skipping the yammer login?
I have access token for yammer login. I need to get the yammer feed using the access token.

<div id="embedded-feed" style="height:800px;width:400px;"></div>
<script type="text/javascript" src="https://assets.yammer.com/assets/platform_embed.js"></script>
<script type="text/javascript">
yam.connect.embedFeed({
container: "#embedded-feed",
network: "{rede}",
feedType: "{type}",
feedId: "{id}"
});
</script>

You may need to use angularJS or pure JS to send the pre-obtained token as a bearer token in the authorization header. Something like:
function YammerGetMsgCtrl($scope, $http ) {
$http.get('https://api.yammer.com/api/v1/messages.json', {headers: {'Authorization': 'Bearer TOKEN_VALUE'}}).
success(function(data) {
$scope.messages = data;
console.log($scope.messages)
});
}
See this blog post for details - http://blogs.technet.com/b/israelo/archive/2015/02/24/consuming-yammer-restful-api-with-angularjs-for-dummies.aspx

Related

How to allow Cors Headers in Google AppScript for making an XMLHttpRequest?

I have created a doGet and doPost endpoints in my appscript. When I hit the endpoint to make a post request from Python, it does work perfectly and as expected.
But when I try to hit the same url with my Flutter based mobile App, it throws me an XML error. (Which I suspect is related to CORSING).
When I hit the url with get request, I get the right response, but post request is failing. To ensure that my Post request is properly configured, I have made a post request to public API and it worked like charm.
Is it possible to add headers, where I could enable cors like this:
allowHeaders = {
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
"Access-Control-Allow-Credentials": true, // Required for cookies, authorization headers with HTTPS
"Access-Control-Allow-Headers": "Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,locale",
"Access-Control-Allow-Methods": "POST, OPTIONS"
}
Here is what my doPost request returns:
ContentService.createTextOutput(JSON.stringify(
{
data: isAuthenticated.data,
error: true,
//request: request,
msg: query.apiKey,
//paramters:request.parameters
})).setMimeType(ContentService.MimeType.JSON)
Here is my python script to get the post response:
requests.post("https://script.google.com/macros/s/AKfycbz7kTROol8u509M_p9pMZ9XRnL-myVjcRQKeb9Etp_OIMPnH640vHf_0Jp2dvvrbto7kOg/exec",
json = requestObject)
And here is my Flutter function:
Future<http.Response> createAlbum() async{
print("Trying to make a post request");
var result = await http.post(Uri.parse('https://script.google.com/macros/s/AKfycbz7kTROol8u509M_p9pMZ9XRnL-myVjcRQKeb9Etp_OIMPnH640vHf_0Jp2dvRIco7kOg/exec'),
headers: {"Content-Type": "application/json"},
body: jsonEncode(<String, dynamic>{
"apiKey":apiKey,
"operationType":"register_user",
"operationData": {
"email": "shivam#yoptima.com",
"otp": 318728
}
}),
);
print("Here is the result: " + result.body);
}
Just to clarify things:
Get Request works for both the platforms.
Post Request works with python for AppScript.
Post Request works for any other public API from flutter.
Post Request doesn't work for Flutter when Hitting AppScript API.
I suspect it to be something to do with CORS. (But not very sure).
Flutter http library makes request via XMLHttpRequest.

How to grab REST API data and display in a html page

Hi i am trying to get data from my LMS's rest API and then display it on a html page, I have a URL and an authorization bearer key
I was provided with some examples of how I should show my url and where to place my Authorization key see below
GET https://example.thoughtindustries.com/incoming/v2/ping
Example Request
CURL https://example.thoughtindustries.com/incoming/v2/ping -H 'Authorization: Bearer APIKEY'
I get a call back using the CURL in Visual Studio code so i know it can be pulled.
I found this method online which I thought would work
$.ajax({
url: "https://api.apiscience.com/v1/monitors/1572022",
headers: {
"Authorization": "Bearer NN_6xxxxx"
}
}).done(function(data) {
$('#monitor_data').append(JSON.stringify(data))
});
<h2>Response Data</h2>
<div id="monitor_data">
<!--location for Javascript to print data-->
</div>
I thought this would be the answer when replacing with my own URL and key but nothing happened. Do I need to include the -H somewhere and if so what might that look like?
It's easy as you have already done this. Write a get ajax call to your API and render your html part from the response you get from the API.
Take a sample example:
var getGamePeriod = function(){
$.ajax({
type: "GET",
url: "yourendpointhere?param=val",
contentType: "application/json",
dataType : 'json',
success : function(response){
if(response && response.isSuccess){
// do your stuffs here..
}
},
error : function(data,textStatus,errorMessage){
alert( textStatus + " " + errorMessage);
}
});
}
Of course you need to pass header or auth token if it is required to access the API. Place this method under document.ready method.

Github GraphQL API Authentication

I want to retrieve data from github's graphql api but I keep getting error message:
{ message: 'This endpoint requires you to be authenticated.', documentation_url: 'https://docs.github.com/v3/#authentication' }
Despite using a token, I even generated a new token to see if the other one was broken. The script to fetch the data can be found at https://repl.it/#DukeSanmi/AcrobaticModernLanguage#index.js
What could be the issue?
Okay you need to put a space between bearer and your variables.githubToken like so:
const headers = {
'Content-Type': 'application/json',
'Authorization': 'bearer ' + variables.githubToken
};
Furthermore, NEVER publish secrets/credentials like API tokens in public code!

Obtain an id token in the Gmail add-on for a backend service authentication

The background
I'm using the Google Apps Script to create a Gmail Add-on.
Via this plugin, I would like to connect to my backend server (a non-Google service) using a REST service request. The request has to be authorised. When authorised, I could then make requests to that server to receive data associated with that user in the database. I'm already using Google sign-in in my webapp to sign in to the backend service - at the front end, I receive the id_token inside of the GoogleUser object in the authorisation response.
The problem
I need this id_token to log in to my backend service when connecting to it via the Gmail plugin. However, I couldn't find a way how to access the token.
The research
I would assume the token must be available through the API in the Apps Script.
In the webapp, I receive the id_token using the Google Auth API like this:
Promise.resolve(this.auth2.signIn())
.then((googleUser) => {
let user_token = googleUser.getAuthResponse().id_token; // this is the id_token I need in the Gmail plugin, too
// send the id_token to the backend service
...
};
In the Google Apps Script API I could only find the OAuth token:
ScriptApp.getOAuthToken();
I assumed the token could also be stored in the session. The Google Apps Script API contains the Session class and that itself contains the getActiveUser method, which returns the User object. The User object, however, only contains the user's email address, no id token (or anything else for that matter):
Session.getActiveUser().getEmail();
The question(s)
Is there a way to obtain the id token?
Am I choosing the right approach to logging in to the backend server using the data of the signed-in user in the Gmail?
Method 1: use getIdentityToken()
Gets an OpenID Connect identity token for the effective user:
var idToken = ScriptApp.getIdentityToken();
var body = idToken.split('.')[1];
var decoded = Utilities.newBlob(Utilities.base64Decode(body)).getDataAsString();
var payload = JSON.parse(decoded);
var profileId = payload.sub;
Logger.log('Profile ID: ' + profileId);
Method 2: use Firebase and getOAuthToken()
Steps to get Google ID Token from Apps Script's OAuth token:
Enable Identity Toolkit API for your Apps Script project.
Add new Firebase project to your existing Google Cloud Platform project at https://console.firebase.google.com/
Create Firebase app for platform: Web.
You will get your config data: var firebaseConfig = {apiKey: YOUR_KEY, ...}.
Enable Google sign-in method for your Firebase project at https://console.firebase.google.com/project/PROJECT_ID/authentication/providers.
Use Apps Script function to get ID Token for current user:
function getGoogleIDToken()
{
// get your configuration from Firebase web app's settings
var firebaseConfig = {
apiKey: "***",
authDomain: "*.firebaseapp.com",
databaseURL: "https://*.firebaseio.com",
projectId: "***",
storageBucket: "***.appspot.com",
messagingSenderId: "*****",
appId: "***:web:***"
};
var res = UrlFetchApp.fetch('https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key='+firebaseConfig.apiKey, {
method: 'POST',
payload: JSON.stringify({
requestUri: 'https://'+firebaseConfig.authDomain,
postBody: 'access_token='+ScriptApp.getOAuthToken()+'&providerId=google.com',
returnSecureToken: true,
returnIdpCredential: true
}),
contentType: 'application/json',
muteHttpExceptions: true
});
var responseData = JSON.parse(res);
idToken = responseData.idToken;
Logger.log('Google ID Token: ');
Logger.log(idToken);
return idToken;
}
Kudos to Riƫl Notermans
You should enable oAuth scopes,
https://developers.google.com/apps-script/concepts/scopes

StackExchange API authentication in Google Apps Script

I'm trying to use the V2.2 of StackExchange API in Google Apps Script.
The problem comes in the last step of the explicit OAuth 2.0 flow, when I try to send the POST request to obtain the access token. I receive a 404 error, but making the same request manually (using postman extension) everything is ok.
To simplify the problem, if I send this POST request with no payload I receive the same 404
var response = UrlFetchApp.fetch("https://stackexchange.com/oauth/access_token", {
method: 'post',
muteHttpExceptions: true
});
Logger.log(response);
while in postman I receive this 400:
{
"error": {
"type": "invalid_request",
"message": "client_id not provided"
}
}
I guess this will be a problem with UrlFetchApp, but does anyone know how to solve it? Thanks!
The problem is related with the Origin header.
You cannot remove from the header directly but you can perform the call via a proxy :)
You need to provide the data for the post by adding an 'option' object to the call.
For example:
var options = { "method" : "post", "payload" : payload };
UrlFetchApp.fetch("https://stackexchange.com/oauth/access_token", options);
Btw, have you tried you use the OAuth that UrlFetch got: https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#addOAuthService(String) - It might be better way.