Google+ API doesnt return access_token Javascript - javascript

We have an application that relies upon Google to authenticate its users against our google apps account and then do some serverside verification and group lookups.
Recently google changed the name of the object that held the access_token variable which we require to authenticate. In the docs (https://developers.google.com/identity/sign-in/web/reference#googleusergetbasicprofile) it says that access_token is available from the getAuthResponse() method, however when i use this it comes back as undefined. Inspecting the object after console.log() reveals all the other fields mentioned except access_token. I'm worried that Google will change the object again in the future and leave us without our application.
Here is the code.
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<meta name="google-signin-client_id" content="XXX.apps.googleusercontent.com">
<script>
//This happens after the user has authenticated with Google and has been passed
//back to the page
function onSignIn(googleUser) {
//Check to see whether the user is trying to sign out.
if (window.location.href.indexOf("signOut=1") !== -1) {
//Sign them out of the application.
signOut();
//redirect them to the same page, without the signOut query string so they can log back in if want
window.location.href='googlesigninform.html'
return false;
}
//Grab the token, access token and email.
var _id = googleUser.getAuthResponse().id_token; //This works
var _accessToken = googleUser.Ka.access_token; //This works but changed from googleUser.B.access_token
var profile = googleUser.getBasicProfile(); //Works
console.log(googleUser.access_token); //Undefined
console.log(googleUser.getAuthResponse().access_token);//Undefined
//Make a post request to the API
makePostRequest(_id, _accessToken, profile.getEmail());
}
What is the correct way to access the access_token variable?

If you need to use access token you are using the wrong type of google signin flow.
You should follow this page: https://developers.google.com/identity/sign-in/web/server-side-flow
What you did implement is google Sign-In to identify users (https://developers.google.com/identity/sign-in/web/)
Which only provides a unique id per user because it is meant to authenticate the user for your own service and not to give an access token to use for other Google services later on.

I believe your problem is that your application is lacking the necessary google-signin-scope.
To answer your question i created an app from the ground using the Google Developer Console. The application is very simple like the one this this tutorial.
The entire application consists of a simple HTML that loads the google API and has a callback called onSignIn (like yours).
Here's the entide code of the application:
<html lang="en">
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="PLACE_YOUR_ID_HERE.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<script>
function onSignIn(googleUser) {
var response = googleUser.getAuthResponse(),
idToken = response['id_token'],
accessToken = response['access_token'];
console.dir('id token: ' + idToken);
console.dir('access token: ' + accessToken);
}
</script>
</body>
</html>
As you can see, the difference between my app and yours is that yours is lacking the first META attribute.

Well i have a hack work around that gets the access_token from the variable.
function findAccessToken(googleUser) {
var returnValue;
Object.getOwnPropertyNames(googleUser).forEach(function (val, idx, array) {
console.log(val + ' -> ' + googleUser[val]);
Object.getOwnPropertyNames(googleUser[val]).forEach(function (vals, idxs, arrays) {
if (vals === "access_token") {
console.log("true");
returnValue = googleUser[val][vals];
}
});
});
return returnValue;
}
Surely this can't be the most elegant solution. If someone could point in the righter direction that would be good.

Here is the code for sign in using google.
<html lang="en">
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<script>
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId()); // Don't send this directly to your server!
console.log("Name: " + profile.getName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
console.log("ID Token: " + id_token);
};
</script>
</body>
</html>

Try this
var _access_token = GoogleUser.getAuthResponse().access_token

Related

Angular 5 Google Signin into component

I've implemented Client Google Signin using my API Key into my html page. When I insert all the necessay tags and functions into index.html it works perfectly, but when it comes to insert the Google Signin button into a component, it is not even shown.
So, if this is how it works in a simple html page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Google Signin out Demo</title>
<script src="https://apis.google.com/js/platform.js" async defer>
</script>
<meta name="google-signin-client_id" content="myprivateid.apps.googleusercontent.com">
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn"></div><br />
Sign out
<script>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
console.log(profile);
}
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
</script>
</body>
</html>
If I want to insert into an Angular component and leave the things as similar as I can I would left the meta-tag and the google script into the index.html and then insert the button in a component. It is not even shown. What am I getting wrong?
<!DOCTYPE html>
<html>
<head>
<script src="https://apis.google.com/js/platform.js" async defer>
</script>
<meta name="google-signin-client_id" content="myprivateid.apps.googleusercontent.com">
</head>
<body>
<app-root></app-root>
</body>
</html>
and in the specific template of the component in which I want the button to appear I insert:
<div class="g-signin2" data-onsuccess="onSignIn"></div><br />
Sign out
Apart from the little javascript code I must add, the button is not even shown.
How can I fix it without installing other npm components?

LinkedIn Javascript SDK Retrieve Profiles

I am trying to retrieve any Profile data with the LinkedIn SDK right now. I am only able to retrieve my own data. Is there a way to retrieve like any Profile data or search for profiles with xyz Name and Show the results? I can't find usefull Information about this, neither in the offical documentation or elsewhere.
<!DOCTYPE html>
<html>
<head>
<title>LinkedIn Javascript Api Hello World</title>
<meta charset="utf-8" />
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: xxxxxxxxxxxxxx
onLoad: onLinkedInLoad
authorize: true
</script>
<script type="text/javascript">
function onLinkedInLoad(){
IN.Event.on(IN, "auth", OnLinkedInAuth);
}
function OnLinkedInAuth() {
IN.API.Profile("me").result(ShowProfileData);
}
function ShowProfileData(profiles) {
var member = profiles.values[0];
//var id=member.id;
//var firstName=member.firstName;
//var lastName=member.lastName;
//var photo=member.pictureUrl;
//var headline=member.headline;
document.getElementById("profiles").innerHTML =
"<p id=\"" + member.id + "\">Hello " + member.firstName + " " + member.lastName + "</p>";
}
</script>
</head>
<body>
<script type="IN/Login"></script>
<div id="profiles"></div>
</body>
</html>
Thank you in advance.
There are only 2 ways to do:
Use Oauth2. This means you have to get access token before you search profile by API.
Refer to this, you must be one of Linkedin Partners.

Initiating the Google+ Sign-In flow with JavaScript not working

I'm following the current tutorial and for some reason when ever I click on the Sign in with Google button nothing seems to happen and I'm not entirely sure why. Here is the code:
<html>
<head>
<title></title>
<script src="https://apis.google.com/js/client:platform.js" async defer></script>
</head>
<body>
<meta name="google-signin-clientid" content="782332402251-os0n348u3v5vaq5kff87f5pc65ib6i19.apps.googleusercontent.com" />
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/plus.login" />
<meta name="google-signin-requestvisibleactions" content="http://schema.org/AddAction" />
<meta name="google-signin-cookiepolicy" content="single_host_origin" />
<script src="https://apis.google.com/js/client:platform.js?onload=render" async defer>
/* Executed when the APIs finish loading */
function render()
{
// Additional params including the callback, the rest of the params will
// come from the page-level configuration.
var additionalParams = {
'callback': signinCallback
};
// Attach a click listener to a button to trigger the flow.
var signinButton = document.getElementById('signinButton');
signinButton.addEventListener('click', function() {
gapi.auth.signIn(additionalParams); // Will use page level configuration
});
}
function signinCallback(authResult)
{
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}
</script>
<button id="signinButton">Sign in with Google</button>
</body>
</html>
Any idea where I'm going wrong?
Looks like a mistake in the tutorial. Emedding Javascript within a script tag with a src attribute is not valid in HTML5. You need to move your code into a separate script tag.
<script type="text/javascript">
// your code here
</script>
See here - http://jsfiddle.net/7umb41z2/

How do I set this.location.href to a specific subdomain location

This is a version of Gatekeeper, I'm trying to get this to go to a subdomain of my website but it only goes to specific files on my main domain. Basically I enter 404 and it takes me to: http://mysite.com/404.html and I want it to go to: http://subdomain.mysite.com/404.html I'm kinda new to this but I think I need to change
if (password) { this.location.href = password + ".html"; }
to where the this.location.href doesn't read my current url but the url I specifically want.
Here is the full example code:
<HTML>
<HTML>
<HEAD>
<TITLE>My Page</TITLE>
<SCRIPT language="JavaScript"><!--
/*********************************************************
GateKeeper v2.3 - by Joe Barta
http://www.pagetutor.com/keeper/
Permission is granted to freely use this script.
**********************************************************/
function GateKeeper() {
var password = prompt("Password required:", "");
if (password) { this.location.href = password + ".html"; }}
//--></SCRIPT>
</HEAD>
<BODY>
Click here for my secret page!
</BODY>
</HTML>
Any ideas or suggestions? Thanks in advance!

how to create contact in iphone using phonegap

I am new to iPhone development and phonegap also. Now i want to create contact in iPhone using phonegap. I got the link to create contact in iPhone with coding. But there one HTML coding with JavaScript. But when i run the coding the simulator and device show's only the HTML tag contents.
I followed this below link only:
"http://docs.phonegap.com/en/2.0.0/cordova_contacts_contacts.md.html#Contacts"
I have attach the coding and Screen Short:
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
var myContact = navigator.contacts.create({"displayName": "Test User"});
myContact.note = "This contact has a note.";
navigator.contacts.save(myContact); //HERE
console.log("The contact, " + myContact.displayName + ", note: " + myContact.note);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Create Contact</p>
</body>
</html>
Screen Short:
Please help me to solve the issue. I have followed all the instruction from that above link. But I didn't get the solution. Thanks in advance.
You need to save your contact.
The documentation states :
contacts.create is a synchronous function that returns a new Contact object.
This method does not persist the Contact object to the device contacts database. To persist the Contact object to the device, invoke the Contact.save method.
function onDeviceReady() {
var myContact = navigator.contacts.create({"displayName": "Test User"});
myContact.note = "This contact has a note.";
navigator.contacts.save(myContact); //HERE
console.log("The contact, " + myContact.displayName + ", note: " + myContact.note);
}
var myContact = navigator.contacts.create({"displayName": "Test User"});
Full Example
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
try {
var contact = navigator.contacts.create();
contact.displayName = "Plumber";
contact.nickname = "Plumber"; //specify both to support all devices
// populate some fields
var name = new ContactName();
name.givenName = "Jane";
name.familyName = "Doe";
contact.name = name;
// save to device
contact.save(function(){
alert("Save Success");
},function(){
alert("Error...");
});
} catch(_err) {
alert(_err)
}
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Create Contact</p>
</body>
</html>
OR You can find more option for contact api.
I think you have not read document. i have also edited my answers please check once again.
Description :
contacts.create is a synchronous function that returns a new Contact object.
This method does not persist the Contact object to the device contacts database. To persist the Contact object to the device, invoke the Contact.save method.
http://docs.phonegap.com/en/1.0.0/phonegap_contacts_contacts.md.html#contacts.create

Categories