Google authorization oAuth 2.0 without popup and consent - javascript

I need to get auth code in JSON not in url after confirm popup google window. I try do it like in this google docs https://developers.google.com/identity/sign-in/web/server-side-flow
but this is doesnt work! What i do wrong ? Here is my code .
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
<script>
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: '0101010101-p5a3fgbkeso3loqg157001l4deajshot.apps.googleusercontent.com',
scope:'https://www.googleapis.com/auth/drive'
// Scopes to request in addition to 'profile' and 'email'
//scope: 'additional_scope'
});
});
}
</script>
</head>
<body>
<button id="signinButton">Sign in with Google</button>
<script>
$('#signinButton').click(function() {
// signInCallback defined in step 6.
auth2.grantOfflineAccess({'redirect_uri': 'postmessage'}).then(function(resp) {
var auth_code = resp.code;
});
});

Related

Why does my Webapp not work with Google's OAuth login system?

I am attempting to build a basic Webapp which has a login with Google button. When the user logs in, I want the web app to change the 'login' button to change to a 'logout' button and also display the user's basic information such as their name which it obtains from their Google profile.
My site successfully opens the Google login page. I am able to click on my Google profile to login and am successfully redirected back to my site. However, nothing changes on my website. The login button still remains a login button and no information is displayed.
I want my site to display the user's information and also change the "login" button to a "logout" button.
I have ensured that my Authorised JavaScript origin (http://localhost:8000) and my Authorised redirect URL (http://localhost:8000/callback) is set correctly. I have also added my CLIENT_ID to my index file. I have also ensured that my client ID is correct.
<html>
<head>
<script src="https://apis.google.com/js/platform.js"></script>
<script>
var googleUser;
var profile;
var auth2;
function onSignIn(googleUser) {
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());
// Change the sign-in button to display the user's details
document.getElementById("g-signin2").style.display = "none";
document.getElementById("user-details").style.display = "block";
document.getElementById("user-name").innerHTML = profile.getName();
document.getElementById("user-email").innerHTML = profile.getEmail();
document.getElementById("user-image").src = profile.getImageUrl();
}
function signOut() {
auth2.signOut().then(function () {
console.log('User signed out.');
// Change the sign-in button back to the original state
document.getElementById("g-signin2").style.display = "block";
document.getElementById("user-details").style.display = "none";
});
}
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: 'my-client-id is in here',
redirect_url: 'http://localhost:8000/callback',
scope: 'profile email'
}).then(function(auth) {
auth2 = auth;
// Check if user is already signed in
if (auth2.isSignedIn.get()) {
onSignIn(auth2.currentUser.get());
}
});
});
</script>
<style>
.g-signin2 {
width: auto;
margin: 0;
}
#user-details {
display: none;
}
</style>
</head>
<body>
</style>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" id="g-signin2"></div>
<div id="user-details">
<p id="user-name"></p>
<button onclick="signOut()">Sign Out</button>
</div>
</body>
</html>
If you check the debugger F12 most browsers you will find your code is throwing an error and a warning
"You have created a new client application that uses libraries for user authentication or authorization that will soon be deprecated. New clients must use the new libraries instead; existing clients must also migrate before these libraries are deprecated. See the Migration Guide for more information."
There is really no reason for you to bother fixing this code it will stop working very soon. You should use the new Web identity
code
<html>
<body>
<script src="https://accounts.google.com/gsi/client" async defer></script>
<script>
function handleCredentialResponse(response) {
console.log("Encoded JWT ID token: " + response.credential);
}
window.onload = function () {
google.accounts.id.initialize({
client_id: "[REDACTED]",
callback: handleCredentialResponse
});
google.accounts.id.renderButton(
document.getElementById("buttonDiv"),
{ theme: "outline", size: "large" } // customization attributes
);
google.accounts.id.prompt(); // also display the One Tap dialog
}
</script>
<div id="buttonDiv"></div>
</body>
</html>

Google Auth don't work in mobile popup_closed_by_user error

I created an web application (js) that connects with Google. It works on PC but not on mobile. The error indicated is popup_closed_by_user while I did not close the popup!! I would like some help please, here is an example:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://apis.google.com/js/api:client.js"></script>
<title>Document</title>
</head>
<body>
<h3>warning: there is Script Error bc client id is not entered. this example don't work in stackoverflow code snippet</h3>
<h1>name: <span id="namegoogle">not connected</span></h1>
<h1>image: <img id="img_google" alt="not connected"/></h1>
<button id="customBtn">GOOGLE: click to connect</button>
<p>ERROR: <span id="errorgoogle">[NO ERROR]</span></p><br><br><h3>WARNING: CLIENT ID IS NOT DECLARED</h3>
</body>
<script>var is_google_user_succed_942894 = false;
var google_getGivenName = "";var google_getFamilyName = "";var google_getAvatarUrl = "";
var googleUser = {};var startApp = function() {
gapi.load('auth2', function(){
// Retrieve the singleton for the GoogleAuth library and set up the client.
auth2 = gapi.auth2.init({
client_id: '################################################################################################.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
// Request scopes in addition to 'profile' and 'email'
//scope: 'additional_scope'
});
attachSignin(document.getElementById('customBtn'));
});
};
startApp();
function attachSignin(element) {
console.log(element.id);
auth2.attachClickHandler(element, {},
function(googleUser) {
document.getElementById("namegoogle").innerHTML = googleUser.getBasicProfile().getName();
document.getElementById("img_google").src = googleUser.getBasicProfile().getImageUrl();
}, function(error) {
var error_msg = error['error']; document.getElementById('errorgoogle').innerHTML = error_msg;
});
}
</script><script src="https://apis.google.com/js/platform.js?onload=renderButton" async defer></script>
</html>

How to Login with linkedin using javascript and display profile information

I want to integrate Linkedin login using javascript.
I searched for that and get relevant results. But lot of search results says that below code:
<script type="in/Login">
</script>
is used to create sign-in button. But i want to use my own custom button and call a function on "onClick" event in my HTML.
Help in correct direction.
My code :
function linkedinLogin(){
console.log('linkedinLogin called');
var src="http://platform.linkedin.com/in.js"
api_key: 'XXXXXXXXXXXXXXXX'
authorize: true
onLoad: OnLinkedInFrameworkLoad
}
function OnLinkedInFrameworkLoad()
{
IN.Event.on(IN, "auth", OnLinkedInAuth);
}
function OnLinkedInAuth() {
IN.API.Profile("me").result(ShowProfileData);
}
function ShowProfileData(profiles)
{
var member = profiles.values[0];
console.log(member);
var id=member.id;
var firstName=member.firstName;
var lastName=member.lastName;
var photo=member.pictureUrl;
var headline=member.headline;
//use information captured above
var str="<b>id</b> : "+id+"<br>";
str +="<b>firstName: </b>"+firstName+"<br>";
str +="<b>lastName: </b>"+lastName+"<br>";
str +="<b>photo: </b>"+photo+"<br>";
str +="<b>headline: </b>"+headline+"<br>";
str +="<input type='button' value='Logout' onclick='logout();'/>";
document.getElementById("status").innerHTML = str;
}
And this is my HTML snippet:
<li>
<a href="javascript:void(0);" onClick="linkedinLogin()">
<img src="images/icon_linkedIn.png" />
<span>LinkedIn</span>
</a>
</li>
<html>
<head>
<title>LinkedIn JavaScript API Hello World</title>
<!-- 1. Include the LinkedIn JavaScript API and define a onLoad callback function -->
<script type="text/javascript" src="https://platform.linkedin.com/in.js">
api_key: xxx
onLoad: onLinkedInLoad
authorize: true
</script>
<script type="text/javascript">
// 2. Runs when the JavaScript framework is loaded
function onLinkedInLoad() {
IN.Event.on(IN, "auth", onLinkedInAuth);
}
// 2. Runs when the viewer has authenticated
function onLinkedInAuth() {
IN.API.Profile("me").fields("id","first-name", "last-name", "email-address").result(displayProfiles);
}
// 2. Runs when the Profile() API call returns successfully
function displayProfiles(profiles) {
member = profiles.values[0];
document.getElementById("profiles").innerHTML =
"<p>"+member.id+"<br> " + member.firstName + "<br> " + member.lastName + "<br>"+member.emailAddress+"</p>";
}
</script>
</head>
<body>
<!-- 3. Displays a button to let the viewer authenticate -->
<script type="in/Login"></script>
<!-- 4. Placeholder for the greeting -->
<div id="profiles"></div>
</body>
</html>
Can you try this ?

Logout from LinkedIn API

I have worked with LinkedIn API and need guidance about logging out from Linkedin API once I click Logout in my application. I have tried the following code:
function closeSession(){
IN.User.logout();
}
Logout In LinkedIn
I have also tried:
$('logout-link').click(function() {
IN.Event.on(IN,'logout', function() {
window.location.href = [site-logout-url];
});
IN.User.logout();
});
I tried to destroy the session in a browser by calling session_destroy()
Finally, I tried the answer I got from Stack Overflow for this question. I didn't get any right solution. Can anyone tell me the solution?
Make sure that you have include
<script type="text/javascript" src="http://platform.linkedin.com/in.js"></script>
on your home page, i.e. where you are logging out.
Seems your onclick is not being called, try doing:
function closeSession(){
IN.User.logout();
return true;
}
Logout In LinkedIn
OR
<a href="#" class="myButton" onclick="closeSession()" id="logout-link">
Logout In LinkedIn
</a>
And js
function closeSession() {
if ( typeof IN === 'object' && typeof IN.User === 'object' && IN.User.isAuthorized() ) {
//user logged in linkedin
//call linkedin logout with websites logout function as callback
alert("I m inside linkedin object check.."); //do you see this
IN.User.logout(logout);
}
else {
logout();
}
}
function logout() {
window.location.href = "URL_TO_YOUR_LOGOUT.PHP";
}
I think you are redirected before your javascript gets executed, so try this way ?
JavaScript Code :
function closeSession(){
IN.User.logout();
location.href="logout.php";
}
HTML Code :
<span style="cursor:pointer" onclick="closeSession()">Logout In LinkedIn</span>
To make it work
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: <?php echo sfConfig::get('app_linkedin_api_key'); ?>
authorize: true
</script>
<script>
IN.Event.on(IN, "logout", function() {onLinkedInLogout();});
function onLinkedInLogout(){
// User is logged out
window.location.href='<?php echo url_for("#homepage");?>'
}
</script>
<?php echo __("Logout");?>
<div class="signin"><script type="in/Login" data-onAuth="onLinkedInAuth"></script>
<script type="text/javascript">
function onLinkedInAuth() {
IN.API.Profile("me")
.fields("id")
.result( function(me) {
var id = me.values[0].id;
//Do stuff like redirect...
})
}
</script>
There seems to be 2 different issues here. You can't logout of linked in from your server side script unless you call their function. When you land on logout.php you should have your session_destroy(); on top of the page. Make sure there isn't any session_start() on logout.php
You need to load the LinkedIn JavaScript platform before trying to call IN.User.logout(), you should run the code only after the javascript library has loaded completely.
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: mykey
authorize: true
onLoad: onLoad
</script>
<script type="text/javascript">
function onLoad() {
try {
IN.User.logout();
} catch (err) {
console.log(err);
}
location.href="index.php";
}
</script>
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: mykey
authorize: true
onLoad: onLoad
</script>
<script type="text/javascript">
function onLoad() {
try {
IN.User.logout();
} catch (err) {
console.log(err);
}
location.href="index.php";
}
</script>
use session_destroy() in the code.

Facebook Opengraph customize fb login button

I'm using facebook open graph, new api, and i can do this:
<fb:login-button show-faces="true" max-rows="9" perms="email" autologoutlink="true" onlogin="window.location = 'http://www.example.com/facebook/facebook_test/'"></fb:login-button>
but when i read the doc if i need more options in http://developers.facebook.com/docs/reference/javascript/FB.login says i can:
FB.login(function(response) {
if (response.session) {
if (response.perms) {
// user is logged in and granted some permissions.
// perms is a comma separated list of granted permissions
} else {
// user is logged in, but did not grant any permissions
}
} else {
// user is not logged in
}
}, {perms:'read_stream,publish_stream,offline_access'});
but if i need another image for fb button, and if i need another things, i can't find how do that, of in what part of html i can call FB.login, is between tags 'script'?
You need to use Javascript SDK for this. Just wrap that FB.login into some function and call it wherever you want. For example if you want to call it on image click:
<html>
<head>
</head>
<body>
<div id="fb-root"></div>
<script>
//initializing API
window.fbAsyncInit = function() {
FB.init({appId: 'your app id', status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
<!-- custom login button -->
<img src="images/my_login.png">
<script>
//your fb login function
function fblogin() {
FB.login(function(response) {
//...
}, {scope:'read_stream,publish_stream,offline_access'});
}
</script>
</body>
</html>

Categories

Resources