I am trying to implement SignIn with Google with redirect approach. I am following this link
My code looks like below
<script src="https://apis.google.com/js/platform.js?onload=startGoogleApp" async defer></script>
<script>
var startGoogleApp = function () {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: '#googleClientId',
ux_mode: 'redirect',
redirect_uri: '#googleRedirectUri',
fetch_basic_profile: true
});
auth2.signIn();
});
}
</script>
But issue is in Google's id_token is not having the name even though I have passed fetch_basic_profile: true I also tried with scope: 'profile'.
I want to fetch name along with email. don't know what am I doing wrong here.
I want it in part of token as it is mentioned in documentation I am following. I don't want fetch name with additional api call. Is it possible?
id_token looks like this
{
"iss": "accounts.google.com",
"azp": "*********",
"aud": "***********",
"sub": "*********",
"hd": "***.com",
"email": "*****#***.com",
"email_verified": true,
"iat": 1599717107,
"exp": 1599720707,
"jti": "*******"
}
Googles Id token is not guaranteed to return all of the profile claims on ever response.
If you want the users profile information then you should go though the Google People API. people.get
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.people.people.get({
"resourceName": "people/me",
"requestMask.includeField": "addresses",
"sources": [
"READ_SOURCE_TYPE_PROFILE"
]
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "YOUR_CLIENT_ID"});
});
Code ripped from the try me found on people.get
I'm trying to use drive to save data from chrome extension.
First, I set needed options to manifest.json
"oauth2": {
"client_id": "999999.apps.googleusercontent.com",
"scopes": [
"https://www.googleapis.com/auth/drive.appdata"
]
},
Then try to get list of files:
$.getScript("https://apis.google.com/js/client.js", function () {
gapi.load('client', function () {
console.log("gapi.client is loaded")
gapi.client.load('drive', 'v3', function () {
console.log("gapi.client.drive is loaded");
chrome.identity.getAuthToken({'interactive': true}, function (token) {
gapi.client.setToken({access_token: token});
console.log("token :", token);
gapi.client.drive.files.list().then(function (list) {
console.log(list)
})
});
});
});
});
Console said:
gapi.client is loaded
gapi.client.drive is loaded
token : [TOKEN]
And the error is like that:
"code": 403,
"message": "The granted scopes do not give access to all of the requested spaces."
The error indicates that you are trying to access unauthorized spaces. Your scope only allows you to use the "appDataFolder" space. Therefore, you have to change
gapi.client.drive.files.list()
for
gapi.client.drive.files.list({spaces:"appDataFolder"}).
The project is on Google Appengine cloud endpoints framework.
Python in the backend.
I'm also using endpoints_proto_datastore (not sure if that makes a difference)
Here is my html file -
<html>
<body>
<script>
clientId = 'myclientid-something-something-something.apps.googleusercontent.com'
loginScope = 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/admin.directory.user.readonly https://www.googleapis.com/auth/admin.directory.customer.readonly https://www.googleapis.com/auth/gmail.settings.basic';
apiKey = 'my-api-key-from-cloud-console';
doSignIn = function() {
console.log("calling doSignIn");
gapi.client.init({apiKey: apiKey, clientId: clientId,scope: loginScope}).then(renderSignIn);
}
renderSignIn = function(){
gapi.signin2.render('my-signin', {
'scope': loginScope,
'width': 'inherit',
'height': 50,
'longtitle': true,
'theme': 'light',
'onsuccess': getOfflineAccess,
'onfailure': function(){console.log("error")}
});
};
getOfflineAccess =function(){
console.log("calling getOfflineAccess");
gapi.auth2.getAuthInstance().grantOfflineAccess({'redirect_uri': 'postmessage'}).then(getApiAuthorization);
}
getApiAuthorization = function(){
console.log("calling getApiAuthorization");
gapi.auth.authorize({client_id: clientId,scope: loginScope, immediate: false},singedInCallback);
};
singedInCallback = function(authResponse) {
console.log("calling signInCallback");
gapi.client.endpointsapp.userOfflineAccessCode.insert({'auth_code':authResponse.code})
.then( function(){console.log("success");},
function(){console.log("error");}
);
};
init = function() {
console.log("calling init");
var apisToLoad;
var callback = function() {
if (--apisToLoad == 0) {
doSignIn();
}
}
apisToLoad = 2;
gapi.client.load('endpointsapp','v1',callback,"https://endpointsapp.appspot.com/_ah/api"); //dummy name for app
gapi.load('client:auth2', callback);
};
</script>
<div id="my-signin"></div>
<script src="https://apis.google.com/js/api.js?onload=init"></script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>
<script src="https://apis.google.com/js/platform.js"></script>
</body>
</html>
Everything goes smooth at first.
I get a google signing button.
I click on it and then all required permissions are granted.
When the actual API hit is made. That gives me a 401.
The response that I get from the API (gapi.client.endpointsapp.userOfflineAccessCode.insert) is :
{
"error": {
"code": 401,
"errors": [
{
"domain": "global",
"message": "Invalid token.",
"reason": "required"
}
],
"message": "Invalid token."
}
}
When I try the same api endpoint using the google api explorer, if I'm authenticated, everything works, without any issue.
I've been trying to debug this for an entire day but just can't figure out what I'm doing wrong.
Any help is highly appreciated.
ok found the issue. Very basic mistake.
According to https://cloud.google.com/endpoints/docs/frameworks/python/create_api allowed_client_ids is a required field if the API uses authentication. I was not providing this parameter and expecting the API to be available to all client_ids by default.
I have a big problem, I hope somebody can help me solve. I am trying to make a Linkedin sharing function from the API. The content there is in the JSON is postet perfectly on LinkedIn. But the problem is that a person cannot see what there is posted in the posting box. I uploaded my share button to my domain, if somebody wants to test it:
http://www.vouzalis.com/wwwroot/stackTest.html
As I see it, I did everything the API ask:
https://developer.linkedin.com/docs/share-on-linkedin
I cannot see what else I am missing? Does anybody have a clue of what there could be wrong?
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: myAPIKey
authorize: true
onLoad: onLinkedInLoad
lang : da_DK
</script>
</head>
<body>
<script type="in/Share">
</script>
<script>
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", shareContent);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to share content on LinkedIn
function shareContent() {
// Build the JSON payload containing the content to be shared
var payload = {
"comment": "Check this awesome website out",
"content": {
"title": "Hello",
"description": "StackOverflow",
"submitted-url": "https://www.stackoverflow.com",
"submitted-image-url": "http://i.telegraph.co.uk/multimedia/archive/03597/POTD_chick_3597497k.jpg"
},
"visibility": {
"code": "anyone"
}
}
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
};
</script>
</body>
</html>
Hi I am trying to load local JSON file using JQuery to show data but i am getting some weird error. May i know how to solve this.
<html>
<head>
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$.getJSON( "priorities.json" , function( result ){
alert(result.start.count);
});
});
</script></head>
</html>
I am just alerting the count of JSON data. My JSON file is in the same directory where this html file is and JSON string format is shown below.
{
"start": {
"count": "5",
"title": "start",
"priorities": [
{
"txt": "Work"
},
{
"txt": "Time Sense"
},
{
"txt": "Dicipline"
},
{
"txt": "Confidence"
},
{
"txt": "CrossFunctional"
}
]
}
}
JSON file name priorities.json and error is
Uncaught Referenceerror priorities is not defined
You can simply include a Javascript file in your HTML that declares your JSON object as a variable. Then you can access your JSON data from your global Javascript scope using data.employees, for example.
index.html:
<html>
<head>
</head>
<body>
<script src="data.js"></script>
</body>
</html>
data.js:
var data = {
"start": {
"count": "5",
"title": "start",
"priorities": [{
"txt": "Work"
}, {
"txt": "Time Sense"
}, {
"txt": "Dicipline"
}, {
"txt": "Confidence"
}, {
"txt": "CrossFunctional"
}]
}
}
Due to security issues (same origin policy), javascript access to local files is restricted if without user interaction.
According to https://developer.mozilla.org/en-US/docs/Same-origin_policy_for_file:_URIs:
A file can read another file only if the parent directory of the
originating file is an ancestor directory of the target file.
Imagine a situation when javascript from a website tries to steal your files anywhere in your system without you being aware of. You have to deploy it to a web server. Or try to load it with a script tag. Like this:
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript" language="javascript" src="priorities.json"></script>
<script type="text/javascript">
$(document).ready(function(e) {
alert(jsonObject.start.count);
});
</script>
Your priorities.json file:
var jsonObject = {
"start": {
"count": "5",
"title": "start",
"priorities": [
{
"txt": "Work"
},
{
"txt": "Time Sense"
},
{
"txt": "Dicipline"
},
{
"txt": "Confidence"
},
{
"txt": "CrossFunctional"
}
]
}
}
Or declare a callback function on your page and wrap it like jsonp technique:
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(e) {
});
function jsonCallback(jsonObject){
alert(jsonObject.start.count);
}
</script>
<script type="text/javascript" language="javascript" src="priorities.json"></script>
Your priorities.json file:
jsonCallback({
"start": {
"count": "5",
"title": "start",
"priorities": [
{
"txt": "Work"
},
{
"txt": "Time Sense"
},
{
"txt": "Dicipline"
},
{
"txt": "Confidence"
},
{
"txt": "CrossFunctional"
}
]
}
})
Using script tag is a similar technique to JSONP, but with this approach it's not so flexible. I recommend deploying it on a web server.
With user interaction, javascript is allowed access to files. That's the case of File API. Using file api, javascript can access files selected by the user from <input type="file"/> or dropped from the desktop to the browser.
As the jQuery API says: "Load JSON-encoded data from the server using a GET HTTP request."
http://api.jquery.com/jQuery.getJSON/
So you cannot load a local file with that function. But as you browse the web then you will see that loading a file from filesystem is really difficult in javascript as the following thread says:
Local file access with javascript
app.js
$("button").click( function() {
$.getJSON( "article.json", function(obj) {
$.each(obj, function(key, value) {
$("ul").append("<li>"+value.name+"'s age is : "+value.age+"</li>");
});
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tax Calulator</title>
<script src="jquery-3.2.0.min.js" type="text/javascript"></script>
</head>
<body>
<ul></ul>
<button>Users</button>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
article.json
{
"a": {
"name": "Abra",
"age": 125,
"company": "Dabra"
},
"b": {
"name": "Tudak tudak",
"age": 228,
"company": "Dhidak dhidak"
}
}
server.js
var http = require('http');
var fs = require('fs');
function onRequest(request,response){
if(request.method == 'GET' && request.url == '/') {
response.writeHead(200,{"Content-Type":"text/html"});
fs.createReadStream("./index.html").pipe(response);
} else if(request.method == 'GET' && request.url == '/jquery-3.2.0.min.js') {
response.writeHead(200,{"Content-Type":"text/javascript"});
fs.createReadStream("./jquery-3.2.0.min.js").pipe(response);
} else if(request.method == 'GET' && request.url == '/app.js') {
response.writeHead(200,{"Content-Type":"text/javascript"});
fs.createReadStream("./app.js").pipe(response);
}
else if(request.method == 'GET' && request.url == '/article.json') {
response.writeHead(200,{"Content-Type":"text/json"});
fs.createReadStream("./article.json").pipe(response);
}
}
http.createServer(onRequest).listen(2341);
console.log("Server is running ....");
Server.js will run a simple node http server in your local to process the data.
Note don't forget toa dd jQuery library in your folder structure and change the version number accordingly in server.js and index.html
This is my running one https://github.com/surya4/jquery-json.
The d3.js visualization examples I've been replicating on my local machine.. which import .JSON data.. all work fine on Mozilla Firefox browser; and on Chrome I get the cross-origins restrictions error.
It's a weird thing how there's no issue with importing a local javascript file, but try loading a JSON and the browser gets nervous. There should at least be some setting to let the user over-ride it, the way pop-ups are blocked but I get to see an indication and a choice to unblock them.. no reason to be so Orwellian about the matter. Users shouldn't be treated as too naive to know what's best for them.
So I suggest using Firefox browser if you're working locally. And I hope people don't freak out over this and start bombing Mozilla to enforce cross-origin restrictions for local files.
I have Used Following Methods But non of them worked:
// 2 Method Failed
$.get(
'http://www.corsproxy.com/' +
'en.github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
function (response) {
console.log("> ", response);
$("#viewer").html(response);
});
// 3 Method Failed
var jqxhr = $.getJSON( "./json/movies-coming-soon.json", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
console.log( "second complete" );
});
// 4 Method Failed
$.ajax({
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
success: function(jsondata){
console.log(jsondata)
}
})
// 5 Method Failed
$.ajax({
url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
headers: { 'Access-Control-Allow-Origin': 'htt://site allowed to access' },
dataType: 'jsonp',
/* etc */
success: function(jsondata){
}
})
What worked For me to simply download chrome extension called "200 OK!" or Web server for chrome and write my code like this:
// Worked After local Web Server
$(document).ready(function () {
$.getJSON('./json/movies-coming-soon.json', function (data) {
var movie_name = '';
var movie_year = '';
$.each(data,function(i,item){
console.log(item.title,item.year,item.poster)
movie_name += item.title + " " + item.year + "<br> <br>"
$('#movie_name').html(movie_name)
})
})
})
Its because you can not access local file without running local web server as per CORS policy so in order to running it you must have some host server.
I would try to save my object as .txt file and then fetch it like this:
$.get('yourJsonFileAsString.txt', function(data) {
console.log( $.parseJSON( data ) );
});