I've seen a lot of documentation about integration between ASP .NET web sites and Facebook, but I haven't found a simple working example, even using Facebook C# SDK.
All I want is a "login with Facebook" example, and to get basic user information (such as name, email and photo).
Can you guys help me please?
Thanks a lot!
as you say using Facebook C# SDK, then here is path and some code for canvas application:
1- Create your web application from visual studio
2- install nuget and get by nuget Facebook C# SDK
3- from https://developers.facebook.com/apps/ create and configure your app.
4- Your web config for facebook integration :
<configuration>
<configSections>
<section name="facebookSettings" type="Facebook.FacebookConfigurationSection" />
</configSections>
<facebookSettings appId="123..." appSecret="abc...." siteUrl="http://apps.facebook.com/myapp/" canvasPage="http://app.facebook.com/myapp" secureCanvasUrl="https://myapp.com/" canvasUrl="http://myapp.com/" cancelUrlPath="http://www.facebook.com/" />
...
By using sdk, you can parse signed request or cookie written by facebook js sdk
FacebookWebContext fbWebContext = new FacebookWebContext();
//Check if user auhtenticated
bool IsAuthenticated = fbWebContext.IsAuthenticated();
Here you can have friend count by:
FacebookWebClient fbWebClient = new FacebookWebClient();
dynamic result = fbWebClient.Get("me/friends");
var friends = result["data"];
int frienCount = friends.Count;
For the client side:
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: '123...',
status: true,
cookie: true,
xfbml: true,
oauth: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);
} ());
<!-- rest of your html -->
</body>
For login & asking permission from javascript
FB.getLoginStatus(function(response) {
console.log( response );
if ((response.status)&&(response.status=='connected')) {
//successs
} else {
//user declined
}, {scope:'user_likes, offline_access'}
});
I prefer in my project to client side login thus not yet registered user have landing page, if for example submit form then I call code block above.
Note: you have to set P3P header for Internet explorer to read/write cookie depending of your server. for IIS, global.asax:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("p3p", "CP=\"CAO PSA OUR\"");
}
Volià
Related
I'm currently in the learning phase for how the Google JS Client SDK works, since my boss needs me to learn how to integrate a Sign In button to his site to enable people to Authenticate via Google. I am testing the code for the custom Sign In button, with a touch of added functionality (like a Sign Out button), and in the process I've practically copy/pasted the code from their website. Let me show you the code first and then explain the issue, so that you can understand where the code is failing:
<script src="https://apis.google.com/js/client.js?onload=init"></script>
<script type="text/javascript">
var clientId = '{my client id here}'; // for web
var apiKey = '{my api key here}';
var scopes = 'profile email';
function SignOut() {
// I know, sloppy, but the signOut method from Google doesn't work.
window.location = 'https://accounts.google.com/logout';
// Additional code if necessary.
};
function makeApiCall() {
gapi.client.load('plus', 'v1', function () {
var request = gapi.client.plus.people.get({ 'userId': 'me' });
request.execute(function (response) {
var heading = document.createElement('h4');
var image = document.createElement('img');
image.src = response.image.url;
heading.appendChild(image);
heading.appendChild(document.createTextNode(response.displayName));
document.getElementById('name').appendChild(heading);
alert('User logged in. makeApiCall() has executed.');
})
})
};
function init() {
gapi.client.setApiKey(this.apiKey);
window.setTimeout(checkAuth, 1);
console.log('Up and ready to go.');
};
function checkAuth() {
// Triggers when the page and the SDK loads.
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: true }, handleAuthResult);
};
function handleAuthClick(event) {
// Triggers after a user click event to ensure no popup blockers interfere.
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: false }, handleAuthResult);
return false;
};
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('SignInBtn');
var signoutButton = document.getElementById('SignOutBtn');
if (authResult && !authResult.error) {
var V = JSON.stringify(authResult);
localStorage.setItem('GoogleAuthResult', V);
console.log(V); // Just for testing...
var authTimeout = (authResult.expires_in - 5 * 60) * 1000; setTimeout(checkAuth, authTimeout); // As recommended by a Google employee in a video, so that the token refreshes.
authorizeButton.style.display = 'none'; // Switching between Sign In and Out buttons.
signoutButton.style.display = 'inline-block';
makeApiCall();
} else {
// Immediate:true failed so user is NOT signed in.
// Make the Sign In button the one visible and prep it
// so that it executes the Immediate:false after user click:
authorizeButton.style.visibility = 'inline-block';
authorizeButton.onclick = handleAuthClick;
signoutButton.style.visibility = 'none';
}
};
</script>
The handleAuthClick function does run on the button click, but after taking the user to the Google Sign In page, when that page brings me back, the browser kinda flickers and the handleAuthResult function does not execute. Therefore, nothing changes in the page after the successful sign in; the button displayed is the Sign In button (Sign Out button not visible) and no information is displayed on the 'name' textNode. This happens on Internet Explorer (11), Firefox (39) and Chrome (44). Also, it happens at home on my laptop (straight connection to the web via Cable broadband) and at work (on Windows 8.1 behind an Active Directory).
I began wondering so I started refreshing the browser page and after a couple of refreshes, since the script runs from the beginning, the immediate:true fires again and voilá: user is connected and API call triggers.
So, on my laptop, I changed the function being called back, in the immediate:false line's callback parameter, to the init() function and that fixed the problem: everything runs smoothly from beginning to end. Yet, this is not the way it is supposed to work. I still don't know what is going on with that line.
This morning, on my computer at work (behind Active Directory), that fix didn't work. I have to refresh the page a couple of times so that the script runs from the beginning and the immediate:true triggers recognizing the user's Signed In state and displaying the proper button on screen.
Any ideas on why does this callback fail?
You need to define your apiKey in the first section of your code
var clientId = '{my client id here}'; // for web
var apiKey = '{my api key here}'
Maybe thats the problem.
Google ApiKeys
I'm developping a component to easily edit associations in document properties pages.
The visual part of the component is an IFRAME showing the myspaces webscript.
I'm having difficulties to transfer user authentication to the content of the IFRAME. The session is lost, so the browser ask for a new BasicAuthentication.
I can transfer the ticket using the alf_ticket url parameter, but it is not reused for other urls produced by the webscript.
How could I transfer the Alfresco authentication to the webscript included in the IFRAME ?
<script type="text/javascript">
var self = this;
var ticket;
var xmlHttpReq = false;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open("GET", "http://blrkec335927d:8080/alfresco/wcservice/api/login?u=admin&pw=admin", true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'json');
self.xmlHttpReq.setRequestHeader('X-Alfresco-Remote-User', 'admin');
xmlHttpReq.onreadystatechange = function() {//Call a function when the state changes.
alert(xmlHttpReq.status);
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
{
var xml = xmlHttpReq.responseXML;
var getticket = xml.getElementsByTagName("ticket");
ticket = getticket[0].childNodes[0].nodeValue
var url1 = "http://blrkec335927d:8080/alfresco/wcservice/ui/myspaces?f=0&p=%2FCompany%20Home&alf_ticket="+ticket;
var aa='<iframe bgcolor="#edf6fc" width="100%" height="100%" frameborder=0 src="'+url1+'" />';
document.getElementById('uploaddoc').innerHTML = aa;
}
}
self.xmlHttpReq.send();
</script>
<body>
<span id="pageTitle">${label['ALFRESCO_DOCUMENT']}</span>
<div id="uploaddoc">
</div>
</body>
<span id="footerButtons" style="vertical-align: bottom;"></span>
I am using above code . But still while loading page its asking for username and password. Please help me
First of all, don't use an iFrames for a simple webscript. You're not loading an entire new page which should have his own session.
Just use Client-Side JavaScript to get the JSON backend data en draw your own UI.
In any case you're compelled to use an iFrame, then just create your own myspaces webscript. Copy all the content, rename it and add your alf_ticket behind every generated url.
I have iframe facebook app but reload making infinite loop.
Yesterday work fine, but not to day.
I'm using javascript and php sdk 3.1.1 with this code:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
oauth: true, // turn oauth
appId : 'myappId',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Canvas.setAutoGrow();
</script>
FB.getLoginStatus(function(response) {
if (response.session) {
var query = FB.Data.query('select publish_stream from permissions where uid={0}', response.authResponse.userID);
........................
}
}
If I delete "<script src="http://connect.facebook.net/en_US/all.js"></script>" line, it does not infinite loop, but the app not work like i want.
Facebook migrated JavaScript SDK to support OAuth2, and requiere that all apps must migrate to OAuth 2.0 by October 1, 2011 (but last time was december 14 2011) therefore, I change:
FB.getLoginStatus(function(response) {
if (response.session) {
........................
}
by
FB.getLoginStatus(function(response) {
if (response.authResponse) {
........................
}
because the app was initialized with OAuth 2.0 enabled.
case closed.
I am developing a facebook application which required to get below information while load.
Facebook Fan Page URL / Id on which the application has been added.
If the user who is accessing this application from specific page is admin of that page or not.
I am developing this application in ASP.Net and I am using Facebook Graph API.
Any help is highly appreciated.
Let me share some insights
Firstly, I would strongly suggest that you use Microsoft's Facebook C# SDK instead of using plain calls in your .NET project.
Steps
With the current API, you can do this in your ADMIN Page
Ask the user to connect and ask for manage pages permission (manage_page)
with the permisions to manage the pages, you can easily fill up a dropdown with all pages that the user have
Ask the user to add your app to it's own page as a tab using http://facebook.com/add.php?api_key=[API_KEY]&pages=1&page=[PAGE_ID]
Now that you have your app running on the user page, you need a way to check if that page is running inside Facebook as a Tab or not, and what's the Page Id that is running from.
In your App Tab Url page that you specified, ask for the signed_request and verify the Data as it has the ["page"]["id"] that you need so you can check against the saves Page_Id that you should have saved on the ADMIN area when your user adds your app to it's facebook page.
I hope this helps.
Code
To login and request all user pages:
<select class="facebook-page-list" disabled="disabled">
<option>Facebook pages</option></select>
<script>
<!--
FB.init({
appId: 'API_KEY',
cookie: true,
status: true,
xfbml: true
});
FB.api('/me', function (user) {
if (user != null) {
if (user.error) {
$(".fb-login").show();
} else {
// example from Facebook
var image = document.getElementById('image');
image.src = 'https://graph.facebook.com/' + user.id + '/picture';
var name = document.getElementById('name');
name.innerHTML = user.name
// get all user Pages
facebookGetPages();
}
}
});
function facebookGetPages() {
FB.getLoginStatus(function (response) {
if (response.session) {
access_token = response.session.access_token;
FB.api(
{
method: 'fql.multiquery',
access_token: access_token,
queries: {
query1: 'select page_id from page_admin where type <> "APPLICATION" and uid = ' + response.session.uid,
query2: 'select page_id, name, page_url from page where page_id in (select page_id from #query1)'
}
}, function (queries) {
if (queries.error_msg)
alert(queries.error_msg);
else {
pages = queries[1].fql_result_set;
$(".facebook-page-list").empty();
for (i = 0; i < pages.length; i++)
$(".facebook-page-list").append("<option value='" + pages[i].page_id + "'>" + pages[i].name + "</option>");
$(".facebook-page-list").attr("disabled", false);
}
});
} else {
// no user session available, someone you dont know
}
});
}
//-->
</script>
To get the Page ID from your app:
ViewBag.signed_request = "can't get id";
dynamic signed_request = FacebookWebContext.Current.SignedRequest;
if(signed_request != null)
{
ViewBag.signed_request = signed_request.Data.page.id;
}
This is something I have been trying to figure out, but I am not sure exactly how to do it. I have a flex application that logs into facebook, but after that I can't access any of the facebook api. Right now I am using this HTML to log in:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<!-- Include support librarys first -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
//This example uses the javascript sdk to login before embedding the swf
var APP_ID = "[My App ID Here]";
var REDIRECT_URI = "http://apps.facebook.com/isotesthoskins/";
var PERMS = "publish_stream,offline_access"; //comma separated list of extended permissions
function init() {
FB.init({appId:APP_ID, status: true, cookie: true});
FB.getLoginStatus(handleLoginStatus);
}
function handleLoginStatus(response) {
if (response.session) { //Show the SWF
//A 'name' attribute with the same value as the 'id' is REQUIRED for Chrome/Mozilla browsers
swfobject.embedSWF("isotest.swf", "flashContent", "760", "500", "9.0", null, null, null, {name:"flashContent"});
} else { //ask the user to login
var params = window.location.toString().slice(window.location.toString().indexOf('?'));
top.location = 'https://graph.facebook.com/oauth/authorize?client_id='+APP_ID+'&scope='+PERMS+'&redirect_uri='+REDIRECT_URI+params;
}
}
$(init);
</script>
And everything logs in fine, but when I try this in the application after I am logged in, nothing happens.
Facebook.api("/me", function(response){
changeText.text = response.name;
});
I don't need to init because it was done by the javascript login, right? I might be wrong about that though.
Looks like you are calling the API using the Flex SDK.
That is not going to work, as the token is not shared between JS and Flex.
You should login on the Flex side or thunk into the JS to make the call.