Facebook send dialogue authentication - facebook

I’m creating a custom share to facebook functionality, which has been more complicated than I originally thought.
I’ve had to create a facebook app and then use It’s ID to get it going.
If you try to share the page on facebook, it gets you login to facebook(if not logged in), then it requests access to your profile(only on your first share), and then proceeds to share dialogue to let you share it.
However I’ve noticed that other sites including youtube and BBC, that they don’t request access to share on facebook, It will take you straight to the share dialogue instead.
Is there a way to achieve this?
Code using is below:
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : '*APP_ID*', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
link : '*LINK*'
});
$('.share-print .facebook > a').click(function(e){
e.preventDefault();
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
facebookSend();
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
FB.login(function(response) {
if (response.authResponse) {
console.log('Logged in');
facebookSend();
} else {
console.log('Not logged in');
}
});
} else {
// the user isn't logged in to Facebook.
FB.login(function(response) {
if (response.authResponse) {
console.log('Logged in');
facebookSend();
} else {
console.log('Not logged in');
}
});
}
});
});
var facebookSend = function() {
console.log('facebookSend started');
FB.ui({
method: 'feed',
display: 'iframe',
link: '*PAGE_LINK*'
});
}
</script>

Related

Facebook getLoginStatus gets status: "unknown" even when logged into Facebook

I am trying to ascertain whether a user is logged into Facebook using the JS SDK.
The call to FB.getLoginStatus always returns status="unknown", even when I know
I am logged into Facebook - literally, I have my Facebook home page open in the
next browser tab.
I am loading the API like this:
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script>
And in my JS code:
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
});
}
function statusChangeCallback( response )
{
console.log("login status change callback: ", response);
if (response.status === 'connected')
{
testAPI();
}
else if (response.status === 'not_authorized')
{
// Not authorized, so show the login button
show_block( ".loginScreen" );
}
else
{
// nothing doing
show_block( ".loginScreen" );
}
} // end statusChangeCallback()
window.fbAsyncInit = function() {
FB.init({
appId : <my app id>,
cookie : true,
xfbml : true,
status : true,
version : 'v12.0'
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
My console window shows:
login status change callback: {authResponse: null, status: 'unknown'}
Why would I be getting a "unknown" status here? I have Facebook open in the next browser tab, so I know that I'm logged in.

FB share after login

When popup for access closed, browser blocking new popup for share. It is possible to give the right and open the window share? (without blocked popup)
$.ajaxSetup({ cache: true });
$.getScript('//connect.facebook.net/en_US/sdk/debug.js', function(){
FB.init({
appId : '856902511027949',
status : true,
cookie : true,
xfbml : true,
oauth : true,
version : 'v2.2'
});
});
function shareViaFbApp() {
FB.ui({
method: 'share',
href: 'https://developers.facebook.com/docs/',
display: 'popup'
}, function(response){
console.log(response);
});
}
$(".init").on('click', function(event) {
event.preventDefault();
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
shareViaFbApp();
} else {
FB.login(function(response) {
console.log(response);
if (response.authResponse) {
shareViaFbApp();
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'publish_actions'});
}
});
});
I see only one way to get around this problem, create a block like fb popup share after FB.login(), and make share via FB.api().
You should not use FB.login in the asynchronous callback of FB.getLoginStatus. I know that it´s in an example in the Facebook docs, but it´s wrong and modern browsers block it. Use FB.getLoginStatus on page load (to refresh a user session and to check if a user is logged in) and FB.login directly on user interaction (mouse click).
You should not use FB.ui automatically either, only on direct user interaction like FB.login.
Btw, you don´t need to authorize a user for FB.ui, it will work without FB.login too.
So, i find workaround, if you need show share dialog after providing access to your fb app, use display: 'iframe' for this.
function shareViaFbApp(afterAccess) {
var display;
if (afterAccess) {
display = 'iframe';
} else {
display = 'popup';
}
FB.ui({
method: 'share',
href: 'https://developers.facebook.com/docs/',
display: display
}, function(response){
console.log(response);
});
}
$(".init").on('click', function(event) {
event.preventDefault();
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
shareViaFbApp();
} else {
FB.login(function(response) {
console.log(response);
if (response.authResponse) {
shareViaFbApp(true);
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'publish_actions'});
}
});
});

Facebook xd_arbiter.php JSON.parse

I've put together a test site to try and get facebook login working with the following code, but I get two errors showing up in FireBug which doesn't seem to effect the functionality of the web page when I just ignore them and carry on.
HTML:
<div class="fb-login-button" show-faces="true" autologoutlink="true" width="200" max-rows="1"></div>
<div id="FBLogin"><a id="FBLoginLnk" href="#" title="Login with Facebook"><img src="./login-button.png" /></a></div>
Javascript:
$(document).ready(function(){
$.ajaxSetup({ cache: true });
$.getScript('//connect.facebook.net/en_UK/all.js', function(){
FB.init({
appId: "012345678901234",
status: true, // check login status
channelUrl : '//website.co.uk/bla/channel.php', // Channel File
cookie: true,
xfbml: true, // parse XFBML
oauth: true
});
FB.Event.subscribe('auth.statusChange', function() {
console.timeStamp("Login even")
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
console.log("Connected Event");
// Good to go
} else if (response.status === 'not_authorized') {
console.log("Not Authorized Event");
NotLoggedIn();
}else{
console.log("Not Logged In Event");
NotLoggedIn();
}
});
});
FB.getLoginStatus(function (response) {
console.timeStamp("getLoginStatus")
if (response.status === 'connected') {
console.log("Connected");
} else if (response.status === 'not_authorized') {
console.log("Not authorised");
NotLoggedIn();
window.location = 'https://graph.facebook.com/oauth/authorize?client_id=012345678901234&scope=publish_stream&redirect_uri=http://www.website.co.uk/bla';
} else {
console.log("User not logged in status unknown");
NotLoggedIn();
window.location = 'https://graph.facebook.com/oauth/authorize?client_id=012345678901234&scope=publish_stream&redirect_uri=http://www.website.co.uk/bla';
}
});
});
$('div#FBLogin').click(function(){
window.location = 'https://graph.facebook.com/oauth/authorize?client_id=012345678901234&scope=publish_stream&redirect_uri=http://www.danthegeek.co.uk/bla';
});
});
function NotLoggedIn(){
console.timeStamp("notLoggedIn Called");
// Reset Website
}
The two errors I'm getting are with xd_arbiter.php?version=27 which seems to get called.
JSON.parse: bad control character in string literal
Line 13
JSON.parse: unexpected non-whitespace character after JSON data
Line 13
As a overview, The intention is to have the page auto-redirect to Facebooks login page (not a pop-up window as this doesn't display correctly on mobile devices). If logged in already, no re-direction happens but user can Log Out which will cause a Login button to be displayed which when clicked goes to the Facebook login page, again no pop-up. This all seems to work fine, but I'm not sure if the code structure is exactly how it should be. I don't believe this to be part of the fault. I really wanted to use the facebook social button to login but couldn't get this to work redirecting to the facebook login page, it only seems to cause a pop-up window which is why I show my own Login with Facebook button.
If it wasn't for firebug halting the code all the time saying there was a error I wouldn't even know there was a problem.
The javascript on my test page is quite complicated but even with everything stripped out and running as above I get this problem.
Any help greatly appreciated.

FB.getLoginStatus() needs page refreshed

I am using FB.getLoginStatus() and FB.Login() to log the user into my website using facebook. I first check for the status on page load using FB.getLoginStatus() and save the state in a hidden variable. When the user clicks on my facebook login button, I first check the value in the hidden variable and call FB.Login() only if FB.getLoginStatus() is not connected. If FB.getLoginStatus() returns 'Connected', then I just log the user into my website without FB.Login().
My scenario with issue
*user logs into my accont using facebook
*user logs out of my website
*my website is open in the logged out state
*in another tab, the current facebook user logs out of facebook and a new user logs into facebook
*user comes back to my website and clicks on facebook login button without refreshing the page
*the old facebook user (not the one currently logged into facebook) is logged into my account
How can I identify the most current user in facebook when user clicks the facebook login button?
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div id="fb-root">
</div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
// initialize the library with your Facebook API key
var AppID = '<%=AppID%>';
window.fbAsyncInit = function() {
FB.init({
appId: AppID,
status: true,
cookie: true,
xfbml: true,
channelUrl: 'http://<%=Request.ServerVariables("HTTP_HOST")%>/channel.html'
});
FB.Event.subscribe('auth.login', function(response) {
//alert('logged in');
});
FB.Event.subscribe('auth.logout', function(response) {
//alert('logged out');
});
FB.getLoginStatus(function(response) {
if (response.status === "connected") {
var uid = response.authResponse.userID;
document.getElementById('hdnFBConnected').value = uid;
}
else if (response.status === "not_authorized") {
//alert("Not authorized");
document.getElementById('hdnFBConnected').value = '';
}
else {
//alert("user not logged in to facebook");
document.getElementById('hdnFBConnected').value = '';
}
});
};
</script>
<img src="<%=global_language & "/images/FacebookSmall.gif"%>" />
<script type="text/javascript" language="javascript">
function WindowOpen() {
if (document.getElementById('hdnFBConnected').value != '') //user is connected
{
FB.api('/me', { fields: 'first_name, last_name, locale, email' }, function(result) {
var uid = document.getElementById('hdnFBConnected').value;
//log the user into my site
})
}
else { //user is not connected, so calling FB.Login()
FB.login(function(response) {
if (response.authResponse) {
var access_token = response.authResponse.accessToken;
FB.api('/me', { fields: 'first_name, last_name, locale, email' }, function(result) {
var uid = response.authResponse.userID;
var globalLang = '<%=global_language%>';
//log the user into my site })
}
else {
//alert('User cancelled login or did not fully authorize.');
}
}, { scope: 'email' }
);
}
}
</script>
</body>
What you're describing is normal behavior. The JS SDK is sending the old user's signed_request object which allows the new user to access her account. Since this concerns you, include a logout button on your app's page and let the user know that it's important she clicks that button when she's done using your app. The logout button should call FB.logout like so:
FB.logout(function(response) {
// user is now logged out
});
For extra security, you can create an activity timer that prompts the user to click a button after X minutes of inactivity. If the user doesn't click within, say 1 minute, she is logged out automatically. This is how most banking sites deal with session security.

Facebook authorization in C#

How do I implement a Facebook authorization? I have no idea where to start. I have seen numerous examples in PHP but none in C#.
Start here: http://developers.facebook.com
If you can use the Facebook javascript sdk (Much easier IMO, and you have asp.net as a tag so i am making assumptions) you could try something like this:
//Facebook iFrame include
window.fbAsyncInit = function () {
FB.init({ appId: YourID, status: true, cookie: true, xfbml: true });
FB.Canvas.setAutoResize();
authorize();
}
/*
* Facebook Authorization
*/
function authorize (){
FB.getLoginStatus(function (response) {
if (response.session) {
// logged in and connected user, carry on
} else {
// no user session available, Lets ask for perms
FB.ui(
{
method: 'permissions.request',
perms: your permissions
},
function (response) {
if (response && response.session != null) {
//User accepted permissions
} else {
//User did not accept permissions
}
});
}
});
}