Google service account open p12 for "access token" - oauth-2.0

I have this code (see end of question) and all I have to do is put in my access token, the thing is I've downloaded the p12 file and whenever I try to open it, I just get some Microsoft certificate program that doesn't tell me the stuff I need, how do I go about getting inside this p12 file to get the access token that its asking for?
Thanks.
<!doctype html>
<html lang="en">
<head>
<title>Google Charts</title>
<script>
(function(w,d,s,g,js,fs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
}(window,document,'script'));
</script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
gapi.analytics.ready(function() {
var ACCESS_TOKEN = '???'; // obtained from your service account
gapi.analytics.auth.authorize({
serverAuth: {
access_token: ACCESS_TOKEN
}
});
var data = new gapi.analytics.report.Data({
query: {
ids: 'ga:????????',
metrics: 'ga:users,ga:sessions,ga:bounceRate',
'start-date': '30daysAgo',
'end-date': 'yesterday',
'output': 'dataTable',
}
});
data.execute();
data.on('success', function(response) {
var data = new google.visualization.DataTable(response.dataTable);
var formatter = new google.visualization.NumberFormat({fractionDigits: 2});
formatter.format(data, 1);
var table = new google.visualization.Table(document.getElementById('test'));
table.draw(data);
});
});
google.load('visualization', '1', {'packages':['table']});
google.setOnLoadCallback(table);
</script>
</head>
<body>
<div>
<div id="embed-api-auth-container"></div>
<div id="test"></div>
</div>
</body>
</html>

Don't try and use a service account with the embed API. Use normal oauth 2 as shown in the documentation Embeded API Getting started
gapi.analytics.ready(function() {
// Step 3: Authorize the user.
var CLIENT_ID = 'Insert your client ID here';
gapi.analytics.auth.authorize({
container: 'auth-button',
clientid: CLIENT_ID,
});
// Step 4: Create the view selector.
var viewSelector = new gapi.analytics.ViewSelector({
container: 'view-selector'
});
If you must use a service account I suggest you drop the embedded API and use a scripting language like PHP directly with the reporting API.

Related

Token Generation for Botframework Webchat

I've been migrating my Direct Line Bot from Webchat v3 to v4.
The new version demands the use of tokens rather than the Direct Line secret in the calling page.
Here is the code (index.html) used to start the bot:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Full-featured bundle</title>
<script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>
<style>
html, body {
height: 100%
}
body {
margin: 0
}
#webchat,
#webchat > * {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
const res = await fetch('https://bellamspt.azurewebsites.net/Forms/Webchat/directline/token', { method: 'POST' });
const { token } = await res.json();
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token })
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>
Question:
What code do I need to write to generate the token in other to be called by https://bellamspt.azurewebsites.net/Forms/Webchat/directline/token ??
Realize it's got to be something like
POST https://directline.botframework.com/v3/directline/tokens/generate
Authorization: Bearer SECRET
but I don't know if it's got to be a php, js or other type of file to work.
Thanks in advance
I used php to solve this. You could give it a try.
<?php
$botSecret = '<your secret>';
$response = wp_remote_get( 'https://webchat.botframework.com/api/tokens', array( 'headers' => 'Authorization: BotConnector ' . $botSecret ) );
if( is_array($response) ) {
$header = $response['headers'];
$token = $response['body'];
}
?>
<script type="text/javascript">
var webChatToken = <?php echo $token; ?>;
</script>
I had the same issue yesterday, I just post it here in case it helps anyone in the future. If you change your code to this it should work:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Full-featured bundle</title>
<script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>
<style>
html, body {
height: 100%
}
body {
margin: 0
}
#webchat,
#webchat > * {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
const res = await fetch('https://bellamspt.azurewebsites.net/Forms/Webchat/directline/token',
{ method: 'POST', headers: { Authorization: 'write your direct line secret here' }});
const { token } = await res.json();
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token })
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>
You had to add the authorization in the header of the post request to generate the token in the async function. Unfortunately this might not be obvious from Microsoft's documentation on how the generate the token
What you need to do is implement some kind of server side logic using whatever technology you're most comfortable with that uses the secret, which is kept only on your server, to generate a new token by making an HTTP request to the DirectLine channel as you point out above. Then, in your web page's start up logic, you make a request to get that token and, with the token, initialize the direct line instance in the web page. Using this approach ensures that nobody external ever gets a hold of your secret.
So, there is no one type of file to "make it work". You will need to choose Node, PHP, ASP.NET or any other server technology and implement it in the way you would any other HTTP request handler.
This article will help in understanding the authentication concepts and APIs and here's a blog post that shows how you might do it with ASP.NET and Node.

Actions on Google account linking

Following documentation described here, I have account linking set up with implicit grants and find that it works well when testing with the browser / actions console, and also with the Google Home app for Android. Unfortunately on the iphone version of the app, user auth hangs most of the time. Feedback from actions on google support is that the problem is that google sign in flow is implemented in separate browser tab (window). On iphone you can't open 2 windows in SfariViewController, thus they are re-writing address of the first page and can’t finish sign in flow. This is known issue and they are not planning to change this. The solution is to implement sign in flow all in one browser window. I'm unclear how to do this and am looking for someone to share code behind the authorization URL you set up that works consistently on iphone. Below is the core of what I am using:
.html snippet:
<!DOCTYPE html>
<html>
<head>
<title>Authorization Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="google-signin-client_id" content="948762963734-2kbegoe3i9ieqc6vjmabh0rqqkmxxxxx.apps.googleusercontent.com">
<!-- <meta name="google-signin-ux_mode" content="redirect"> INCLUDING THIS META TAG BREAKS THE AUTH FLOW -->
<script src="js/googleAuth.js"></script>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<link rel="stylesheet" href="css/googleAuth.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<header class="bgimg-1 w3-display-container w3-grayscale-min" id="loginScreen">
<div class="w3-display-topleft w3-padding-xxlarge w3-text-yellow" style="top:5px">
<span class="w3-text-white">Google Sign In</span><br>
<span class="w3-large">Sign in with your Google account</span><br><br>
<div class="g-signin2" data-onsuccess="onSignIn"></div><br><br>
</div>
</header>
</body>
</html>
.js code snippet:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId()
var name = profile.getName()
var email = profile.getEmail()
var token = googleUser.getAuthResponse().id_token;
var client_id = getQueryVariable('client_id')
// vital-code-16xxx1 is the project ID of the google app
var redirect_uri = 'https://oauth-redirect.googleusercontent.com/r/vital-code-16xxx1'
var state = getQueryVariable('state')
var response_type = getQueryVariable('response_type')
// store the user's name, ID and access token and then sign out
storeOwnerID (email, name, id, token, function() {
// sign out
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('signed out')
});
// if this page was loaded by Actions On Google, redirect to complete authorization flow
typeof redirect_uri != 'undefined' ? window.location = redirectURL : void 0
})
}
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
#dana Have you tried adding meta tag?
<meta name="google-signin-ux_mode" content="redirect">
With help from Google support & engineering, this is now resolved:
As noted above, I had to include this meta tag: <meta name="google-signin-ux_mode" content="redirect">
I needed to have https://my-auth-endpoint.com/ in my project's authorized redirect URI. It is not enough to have it only in Authorized javascript origins. The other key thing is to include the trailing slash, I hadn't originally and it will not work without it.
Below is the simple code foundation you can use to get a working version of an authorization endpoint for actions on google account linking:
.html:
<!DOCTYPE html>
<html>
<head>
<title>Authorization Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="google-signin-client_id" content="948762963734-2kbegoe3i9ieqc6vjmabh0rqqkmxxxxx.apps.googleusercontent.com">
<meta name="google-signin-ux_mode" content="redirect">
<script src="js/googleAuth.js"></script>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<link rel="stylesheet" href="css/googleAuth.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script>
sessionStorage['jsonData'] == null ? storeQueryVariables() : void 0
</script>
</head>
<body>
<header class="bgimg-1 w3-display-container w3-grayscale-min" id="loginScreen">
<div class="w3-display-topleft w3-padding-xxlarge w3-text-yellow" style="top:5px">
<span class="w3-text-white">Google Sign In</span><br>
<span class="w3-large">Sign in with your Google account</span><br><br>
<div class="g-signin2" data-onsuccess="onSignIn"></div><br><br>
</div>
</header>
</body>
</html>
.js:
// Retrieve user data, store to DynamoDB and complete the redirect process to finish account linking
function onSignIn(googleUser) {
let profile = googleUser.getBasicProfile(),
id = profile.getId(),
name = profile.getName(),
email = profile.getEmail(),
token = googleUser.getAuthResponse().id_token,
redirect_uri = 'https://oauth-redirect.googleusercontent.com/r/vital-code-16xxxx',
jsonData = JSON.parse(sessionStorage['jsonData']),
redirectURL = redirect_uri + '#access_token=' + token + '&token_type=bearer&state=' + jsonData.state
// store the user's name, ID and access token
storeUserData(email, name, id, token, function() {
// sign out of google for this app
let auth2 = gapi.auth2.getAuthInstance();
auth2.signOut()
// if this page was loaded by Actions On Google, redirect to complete authorization flow
typeof redirect_uri != 'undefined' ? window.location = redirectURL : void 0
})
}
// Store the user data to db
function storeUserData (email, name, id, token, callback) {
// removed for simplicity
}
// Store URI query variable 'state' to browser cache
function storeQueryVariables() {
let qvar = {
'state': getQueryVariable('state')
}
storeLocally(qvar)
}
// Get any variable from incoming URI
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
// Store JSON object input to local browser cache
function storeLocally (jsonData) {
if (typeof(Storage) !== 'undefined') {
sessionStorage['jsonData'] = JSON.stringify(jsonData)
} else {
console.log('Problem: local web storage not available')
}
}

TypeError: gapi.auth2 undefined

I went exactly by the instructions for integrating google sign-in:
https://developers.google.com/identity/sign-in/web/sign-in#specify_your_apps_client_id
sign-in works, but sign-out gives a javascript error in the line:
var auth2 = gapi.auth2.getAuthInstance();
The error is:
gapi.auth2 undefined
I include the google platform library as instructed:
<script type='text/javascript' src='https://apis.google.com/js/platform.js' async defer></script>
Why does it not work?
Are signIn and signOut used on the same page?
Div g-signin2 loads and inits gapi.auth2 so it should work as long as those are on the same page.
In case signOut is on separate page, you should manually load and init gapi.auth2 library.
Full example (you have to replace YOUR_CLIENT_ID with your actual client_id):
<html>
<head>
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID">
</head>
<body>
<script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
function onLoad() {
gapi.load('auth2', function() {
gapi.auth2.init();
});
}
</script>
Sign out
<script src="https://apis.google.com/js/platform.js?onload=onLoad" async defer></script>
</body>
</html>

update Google fusiontable using oauth token?

I already have the token and can access my token whose scopes are till fusiontable.
http://www.udayan2k12.com/token.html
<script type="text/javascript">
(function() {
var GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
var GOOGLE_CLIENT_ID = "365219651081-7onk7h52kas6cs5m17t1api72ur5tcrh.apps.googleusercontent.com";
var PLUS_ME_SCOPE = "https://www.googleapis.com/auth/fusiontables";
var button = document.createElement("button");
button.innerText = "Authenticate with Google";
button.onclick = function() {
var req = {
"authUrl" : GOOGLE_AUTH_URL,
"clientId" : GOOGLE_CLIENT_ID,
"scopes" : [ PLUS_ME_SCOPE ],
};
oauth2.login(req, function(token) {
alert("Got an OAuth token:\n" + token + "\n"
+ "Token expires in " + oauth2.expiresIn(req) + " ms\n");
document.getElementById('token').innerHTML = token;
}, function(error) {
alert("Error:\n" + error);
});
};
document.body.appendChild(button);
var clearTokens = document.createElement("button");
clearTokens.innerText = "Clear all tokens";
clearTokens.onclick = oauth2.clearAllTokens;
document.body.appendChild(clearTokens);
})();
</script>
But the problem is that i am unable to use that token to update the fusion table.
I want to update it specifically by using JavaScript.
can some one provide me the code to use this token to update fusiontable using the fusion table sql
You should use the JavaScript Google API client, then it is very easy to make authenticated requests to a Google API (see their "Samples" page):
gapi.client.setApiKey('YOUR API KEY');
var query = "INSERT INTO tableId (id, name) VALUES (1, 'test')";
gapi.client.load('fusiontables', 'v1', function(){
gapi.client.fusiontables.query.sql({sql:query}).execute(function(response){console.log(response);});
});
I know most of you are suffering for google auth and inserting and updating fusion table.
I am providing the entire code how to use the gauth lib to insert in a simple manner
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Authorization Request</title>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
function auth() {
var config = {
'client_id': '365219651081-7onk7h52kas6cs5m17t1api72ur5tcrh.apps.googleusercontent.com',
'scope': 'https://www.googleapis.com/auth/fusiontables'
};
gapi.auth.authorize(config, function() {
console.log('login complete');
console.log(gapi.auth.getToken());
});
}
function insert_row(){
alert("insert called");
gapi.client.setApiKey('AIzaSyA0FVy-lEr_MPGk1p_lHSrxGZDcxy6wH4o');
var query = "INSERT INTO 1T_qE-o-EtX24VZASFDn6p3mMoPcWQ_GyErJpPIc(Name, Age) VALUES ('Trial', 100)";
gapi.client.load('fusiontables', 'v1', function(){
gapi.client.fusiontables.query.sql({sql:query}).execute(function(response){console.log(response);});
});
}
</script>
</head>
<body>
<button onclick="auth();">Authorize</button>
<p> </p>
<button onclick="insert_row();">Insert Data</button>
</body>
</html>

How to process backend coldfusion processing script response

I have implemented plupload using a ColdFusion backend script (available at https://gist.github.com/1116037).
The url attribute in the uploading page is url : '../upload.cfc?method=upload',
This simply calls a function within the cfc script. It works fine. This script also creates a variable called 'response' to hold information uploaded files.
The problem I am having is accessing the information held in the 'response' variable.
I would like to display that information in a table after the all the files have been uploaded to the server.
I am using the queue_widget for my needs’ think that an event (onComplete) needs to be triggered to call a function to process the information in variable, but I don't know how to do this.
I need to access the information held in the 'response' variable, preferably in ColdFusion code. Has anyone managed to get plupload working with ColdFusion yet?
Any help, guidance or coding would be appreciated.
Here is the full code I have used:
This is the main page - queue_widget.cfm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Plupload - Queue widget example</title>
<link rel="stylesheet" href="../../js/jquery.plupload.queue/css/jquery.plupload.queue.css" type="text/css" media="screen" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="../../js/plupload.js"></script>
<script type="text/javascript" src="../../js/plupload.flash.js"></script>
<script type="text/javascript" src="../../js/jquery.plupload.queue/jquery.plupload.queue.js"></script>
</head>
<body>
<h1>Queue widget example</h1>
<p>Shows the jQuery Plupload Queue widget and under different runtimes.</p>
<div style="float: left; margin-right: 20px">
<h3>Flash runtime</h3>
<div id="flash_uploader" style="width: 700px;">Your browser does not have Flash installed!</div>
</div>
<br style="clear: both" />
<cfoutput><cfset mnum=6></cfoutput>
<script type="text/javascript">
$(function() {
// Setup flash version
$("#flash_uploader").pluploadQueue({
// General settings
runtimes : 'flash',
url : '../upload.cfc?method=upload',
max_file_size : '1mb',
max_file_count: <cfoutput>#mnum#</cfoutput>, // You can limit the num of files that can be uploaded by manipulating the mnum variable above
unique_names : false,
multiple_queues : true,
multi_selection: true,
filters : [
{title : "Image files", extensions : "jpg,gif,png"}
],
init : {
FilesAdded: function(up, files) {
plupload.each(files, function(file) {
if (up.files.length > <cfoutput>#mnum#</cfoutput>) {
up.removeFile(file);
}
});
if (up.files.length >= <cfoutput>#mnum#</cfoutput>) {
$('#pickfiles').hide('slow');
}
},
FilesRemoved: function(up, files) {
if (up.files.length < 1) {
$('#pickfiles').fadeIn('slow');
}
}
},
resize : {width : 300, height : 10000, quality : 90}, // forces images to be resized to a width of 300px if wider than 300px
preinit: attachCallbacks,
UploadComplete: function(up, file, response) {
if ($("#result").length > 0){
$("#results").prepend(info.response);
} else {
$("#flash_uploader").after("<div id='results'>"+info.response+"</div>");
}
},
flash_swf_url : '../../js/plupload.flash.swf'
});
});
// Where should we go after upload
function attachCallbacks(Uploader){
Uploader.bind('FileUploaded', function(Up, File, response){
function IsJson(response) {
alert('Response from server: ' + response.file); // for testing only
counter++
var newRow = '<tr><td><input type="hidden" name="file_'+counter+'" value="'+response.file+'">'
newRow += 'Label the file: '+response.file+' <input type="text" name="filename_'+counter+'"></td></tr>'
$("#detail").append(newRow)
}});
};
</script>
<div id="results"></div>
<table id="detail">
</table>
<cfif IsDefined('response')><cfdump var="#response#"></cfif>
</body>
</html>
This the backend processing page - upload.cfc
<cfcomponent>
<cffunction name="upload" access="remote" returntype="struct" returnformat="json" output="false">
<cfscript>
var uploadDir = expandPath('/uploads/'); // should be a temp directory that you clear periodically to flush orphaned files
var uploadFile = uploadDir & arguments.NAME;
var response = {'result' = arguments.NAME, 'id' = 0};
var result = {};
</cfscript>
<!--- save file data from multi-part form.FILE --->
<cffile action="upload" result="result" filefield="FILE" destination="#uploadFile#" nameconflict="overwrite"/>
<cfscript>
// Example: you can return uploaded file data to client
response['size'] = result.fileSize;
response['type'] = result.contentType;
response['saved'] = result.fileWasSaved;
return response;
</cfscript>
</cffunction>
</cfcomponent>
You can try the above example here: [url] www.turn2cash.co.uk/plupload/examples/jquery/queue_widget.cfm [/url]
As mentioned above, the script works well with uploading (in this case) upto 6 images as determined by the mnum variable. What I need help with is with how to access the uploaded files (with page refresh) and be able to manipulate them.
I have setup an example (using cffileupload) of what I am after here [url] www turn2cash.co.uk/a/index.cfm [/url]
Although this works fine, it requires a page refresh, which is what I am trying to avoid.
Please provide any help you can.
Added 7 september 2012
I have tried both methods suggested by Miguel but did not achieve any positive outcomes. They actually caused the UI not to sow at all. However I found this and tried it:
preinit: attachCallbacks,
UploadComplete: function(up, file, response) {
if ($("#result").length > 0){
$("#results").prepend(info.response);
} else {
$("#flash_uploader").after("<div id='results'>"+info.response+"</div>");
}
},
flash_swf_url : '../../js/plupload.flash.swf'
});
});
// Where should we go after upload
function attachCallbacks(Uploader){
Uploader.bind('FileUploaded', function(Up, File, Response){
alert('Response from server: ' + Response.response);
});
};
</script>
I now get an alert displaying:
Response from server: {"saved":true,"result":"home.png","id":"0","size":"5988","type":"image"}
This at least prooves that the cfc script is working and the 'response' varialable is being returned. I still have no idea how to make use of this information as I have no knowledge of jquery, ajax or javascript. Please help if you can.
The link that I posted before has the example code. Sorry to post this as an answer but since I have no rep I cannot comment.
I think part of your confusion is in the request processing. You have this line of code at the bottom of your example.
<cfif IsDefined('response')><cfdump var="#response#"></cfif>
That will never fire because the coldfusion page is processed before you make the javascript ajax call to the server for the file upload. You will need to handle the response in javascript.
Are you seeing this alert from the attachCallbacks function?
alert('Response from server: ' + response.file); // for testing only

Resources