I am trying to use Oauth 2.0 to authenticate users signing in their google accounts. I will need access to their names and email addresses for this. I am using phonegap's InAppBrowser to do this.
So far I have this:
function openPage() {
var login_url = "https://accounts.google.com/o/oauth2/auth" + '?' + $.param({ client_id: "(not shown)", redirect_uri: "http://www.google.com", response_type: "token", scope: "openid profile email" });
var loginWindow = window.open(login_url, '_blank', 'location=yes');
loginWindow.addEventListener('loadstop', function(e) {
var url = e.url;
var access_token = url.split("access_token=")[1];
validateToken(access_token);
});
function validateToken(token) {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' + token,
data: null,
success: function(responseText){
alert("Validation Success!");
getUserInfo(token);
},
dataType: "jsonp"
});
}
function getUserInfo(token) {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + token,
data: null,
success: function(resp) {
user = resp;
alert(JSON.stringify(user));
},
dataType: "jsonp"
});
}
}
The validation of the token works everytime, but once it calls getUserInfo() the JSON returned is filled with errors and invalid credential strings. What am I doing wrong? Thanks!
I guess you need to set the token in Authorization header as per the documentation for Userinfo endpoint found here
Related
Hi i tried following this tutorial to use authentication with google plus https://stackoverflow.com/questions/23930744/how-to-use-google-login-api-with-cordova-phonegap but the prolem is when i click to login button it open browser and load google plus from browser. What i want is when i click the login button its pop up the google plus app like other native app ? The question is can i achive that with cordova ? and if yes how do i do that ? thanks
here is how to login with google based on that stacoverflow answer above
var googleapi = {
authorize: function(options) {
var deferred = $.Deferred();
//Build the OAuth consent page URL
var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
client_id: options.client_id,
redirect_uri: options.redirect_uri,
response_type: 'code',
scope: options.scope
});
//Open the OAuth consent page in the InAppBrowser
var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=no');
//The recommendation is to use the redirect_uri "urn:ietf:wg:oauth:2.0:oob"
//which sets the authorization code in the browser's title. However, we can't
//access the title of the InAppBrowser.
//
//Instead, we pass a bogus redirect_uri of "http://localhost", which means the
//authorization code will get set in the url. We can access the url in the
//loadstart and loadstop events. So if we bind the loadstart event, we can
//find the authorization code and close the InAppBrowser after the user
//has granted us access to their data.
$(authWindow).on('loadstart', function(e) {
var url = e.originalEvent.url;
var code = /\?code=(.+)$/.exec(url);
var error = /\?error=(.+)$/.exec(url);
if (code || error) {
//Always close the browser when match is found
authWindow.close();
}
if (code) {
//Exchange the authorization code for an access token
$.post('https://accounts.google.com/o/oauth2/token', {
code: code[1],
client_id: options.client_id,
client_secret: options.client_secret,
redirect_uri: options.redirect_uri,
grant_type: 'authorization_code'
}).done(function(data) {
deferred.resolve(data);
$("#loginStatus").html('Name: ' + data.given_name);
}).fail(function(response) {
deferred.reject(response.responseJSON);
});
} else if (error) {
//The user denied access to the app
deferred.reject({
error: error[1]
});
}
});
return deferred.promise();
}
};
var accessToken;
var UserData = null;
function callGoogle() {
// alert('starting');
googleapi.authorize({
client_id: 'client_id',
client_secret: 'Client_Secret',
redirect_uri: 'http://localhost',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
}).done(function(data) {
accessToken = data.access_token;
// alert(accessToken);
// $loginStatus.html('Access Token: ' + data.access_token);
console.log(data.access_token);
console.log(JSON.stringify(data));
getDataProfile();
});
}
// This function gets data of user.
function getDataProfile() {
var term = null;
// alert("getting user data="+accessToken);
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + accessToken,
type: 'GET',
data: term,
dataType: 'json',
error: function(jqXHR, text_status, strError) {},
success: function(data) {
var item;
console.log(JSON.stringify(data));
// Save the userprofile data in your localStorage.
localStorage.gmailLogin = "true";
localStorage.gmailID = data.id;
localStorage.gmailEmail = data.email;
localStorage.gmailFirstName = data.given_name;
localStorage.gmailLastName = data.family_name;
localStorage.gmailProfilePicture = data.picture;
localStorage.gmailGender = data.gender;
}
});
disconnectUser();
}
function disconnectUser() {
var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' + accessToken;
// Perform an asynchronous GET request.
$.ajax({
type: 'GET',
url: revokeUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function(nullResponse) {
// Do something now that user is disconnected
// The response is always undefined.
accessToken = null;
console.log(JSON.stringify(nullResponse));
console.log("-----signed out..!!----" + accessToken);
},
error: function(e) {
// Handle the error
// console.log(e);
// You could point users to manually disconnect if unsuccessful
// https://plus.google.com/apps
}
});
}
Below code is working with the help of InApp browser plugin but after getting permission from user to get his details, I am not able to show/get his name after browser window closed.
I am getting result - name : undefined
Please help me to get this.Thanks in advance.
Note: I got this code from How to use Google Login API with Cordova/Phonegap
var googleapi = {
authorize: function(options) {
var deferred = $.Deferred();
//Build the OAuth consent page URL
var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
client_id: options.client_id,
redirect_uri: options.redirect_uri,
response_type: 'code',
scope: options.scope
});
//Open the OAuth consent page in the InAppBrowser
var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=no');
//The recommendation is to use the redirect_uri "urn:ietf:wg:oauth:2.0:oob"
//which sets the authorization code in the browser's title. However, we can't
//access the title of the InAppBrowser.
//
//Instead, we pass a bogus redirect_uri of "http://localhost", which means the
//authorization code will get set in the url. We can access the url in the
//loadstart and loadstop events. So if we bind the loadstart event, we can
//find the authorization code and close the InAppBrowser after the user
//has granted us access to their data.
$(authWindow).on('loadstart', function(e) {
var url = e.originalEvent.url;
var code = /\?code=(.+)$/.exec(url);
var error = /\?error=(.+)$/.exec(url);
if (code || error) {
//Always close the browser when match is found
authWindow.close();
}
if (code) {
//Exchange the authorization code for an access token
$.post('https://accounts.google.com/o/oauth2/token', {
code: code[1],
client_id: options.client_id,
client_secret: options.client_secret,
redirect_uri: options.redirect_uri,
grant_type: 'authorization_code'
}).done(function(data) {
deferred.resolve(data);
$("#loginStatus").html('Name: ' + data.given_name);
}).fail(function(response) {
deferred.reject(response.responseJSON);
});
} else if (error) {
//The user denied access to the app
deferred.reject({
error: error[1]
});
}
});
return deferred.promise();
}
};
var accessToken;
var UserData = null;
function callGoogle() {
// alert('starting');
googleapi.authorize({
client_id: 'Myclientid',
client_secret: 'secret id',
redirect_uri: 'http://localhost',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
}).done(function(data) {
accessToken = data.access_token;
// alert(accessToken);
// $loginStatus.html('Access Token: ' + data.access_token);
console.log(data.access_token);
console.log(JSON.stringify(data));
getDataProfile();
});
}
// This function gets data of user.
function getDataProfile() {
var term = null;
// alert("getting user data="+accessToken);
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + accessToken,
type: 'GET',
data: term,
dataType: 'json',
error: function(jqXHR, text_status, strError) {},
success: function(data) {
var item;
console.log(JSON.stringify(data));
// Save the userprofile data in your localStorage.
localStorage.gmailLogin = "true";
localStorage.gmailID = data.id;
localStorage.gmailEmail = data.email;
localStorage.gmailFirstName = data.given_name;
localStorage.gmailLastName = data.family_name;
localStorage.gmailProfilePicture = data.picture;
localStorage.gmailGender = data.gender;
}
});
disconnectUser();
}
function disconnectUser() {
var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' + accessToken;
// Perform an asynchronous GET request.
$.ajax({
type: 'GET',
url: revokeUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function(nullResponse) {
// Do something now that user is disconnected
// The response is always undefined.
accessToken = null;
console.log(JSON.stringify(nullResponse));
console.log("-----signed out..!!----" + accessToken);
},
error: function(e) {
// Handle the error
// console.log(e);
// You could point users to manually disconnect if unsuccessful
// https://plus.google.com/apps
}
});
}
<div data-role="page">
<div data-role="header">
<h1>Welcome To My Homepage</h1>
</div>
<div data-role="main" class="ui-content">
<p onclick="callGoogle();">Google Login</p>
<p><span id="loginStatus"></span></p>
</div>
<div data-role="footer">
<h1>Footer Text</h1>
</div>
</div>
I try to post in fan page as admin but it does not work:
it works but not as admin
var wallPost = {
access_token: token,
message: 'asdasdasd'
};
FB.api('/xxxxx/feed', 'post', wallPost, function(response) {
console.log(response);
});
This has an error:
FB.api('/' + page_id, {fields: 'access_token'}, function(resp) {
if(resp.access_token) {
FB.api('/' + page_id + '/feed',
'post',
{ message: "I'm a Page!", access_token: resp.access_token }
,function(response) {
console.log(response);
});
}else{
console.log(resp);
}
});
the error is:
"(#200) The user hasn't authorized the application to perform this action"
My scope: 'manage_pages,publish_actions,read_stream,user_groups'
Since v2.3, you need permission publish_pages (in addition to manage_pages) to post as a page.
They separated this from publish_actions, which is now for posting as a user only.
(See also: https://developers.facebook.com/docs/apps/changelog#v2_3_changes)
I'm trying to request the URL to get Circles List for user in an app using JavaScript:
my code is
var scopes = ['https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/plus.circles.read',
'https://www.googleapis.com/auth/plus.media.upload',
'https://www.googleapis.com/auth/plus.profiles.read',
'https://www.googleapis.com/auth/plus.stream.read',
'https://www.googleapis.com/auth/plus.stream.write',
'https://www.googleapis.com/auth/plus.circles.write',
'https://www.googleapis.com/auth/paymentssandbox.make_payments',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.google.com/m8/feeds/contacts/default/full'];
function getCircles() {
$.ajax({
type: 'GET',
url: 'https://www.googleapis.com/plusDomains/v1/people/me/circles?access_token=' + access_token,
dataType: 'jsonp',
success: function (response) {
console.log(response);
},
error: function (e) {
console.log(e);
}
});
}
and I turned on permissions in my app
Google+ API
Google+ Domains API
But this request retrieved
error
Object { errors=[1], code=403, message="Forbidden"}
code
403
errors
[Object { domain="global", reason="forbidden", message="Forbidden"}]
0
Object { domain="global", reason="forbidden", message="Forbidden"}
domain
"global"
message
"Forbidden"
reason
"forbidden"
message "Forbidden"
Friends,
I know you have been facing these kind of question a lot.I was unable to find an answer even after a lot of google search.Well, lets come to the issue.
Requirement: Call a WCF Service GET API with basic authentication enabled using jquery ajax request.
Client side code:
<script src="Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="Scripts/Base64.js" type="text/javascript"></script>
<%--<script src="Scripts/jquery.base64.js" type="text/javascript"></script>--%>
<script type="text/javascript">
function make_base_auth(user, pass) {
var tok = user + ':' + pass;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
$(document).ready(function () {
var username = 'user';
var password = 'ppp';
var auth = make_base_auth(username, password);
$.ajax({
type: "GET",
dataType: "jsonp",
contentType: "application/javascript",
xhrFields: {
withCredentials: true
},
cache: false,
crossDomain: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authentication", auth)
},
data: { 'inputData': "{PatientID:'12',FromDateTime:'05/21/2013 1:28:15 PM',ToDateTime:'05/21/2013 1:28:15 PM',ResponseType:'json',CompressResponse:'false'}" },
url:"http://192.168.15.160/RestAPI/Service.svc/GetMedicationValues",
success: function (jsonData) {
console.log(jsonData);
},
error: function (request, textStatus, errorThrown) {
console.log(request.responseText);
console.log(textStatus);
console.log(errorThrown);
}
});
});
</script>
Problem : I am getting login pop up when running the client application.I get the output only when i provide correct credentials on the pop up, irrespective of what credentials i pass in the request header.I have come through people asking this question a lot.Have anyone been able to solve this issue ? Thank You.
JSONP doesn't work with basic authentication.
If you don't need cross-domain request, use json as datatype.
Alos note that since JQuery 1.7, there are now two options for authentication : userName and password.
If the server performs HTTP authentication before providing a
response, the user name and password pair can be sent via the username
and password options.