Facebook API: Where does this facebookredirect.axd come from? - facebook

So I've set up everything to invite users to the registration page on my site and track their invitation code, but now whenever a user accepts the invitation they end up getting the following error:
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
And here's the URL:
http://www.facebook.com/dialog/oauth/?state=eyJyIjoiaHR0cDovL2FwcHMuZmFjZWJvb2suY29tL2Zpc2hhcndlLz9yZXF1ZXN0X2lkcz0xMDE1MDYzNzQzNDI4NTQ4NCwxMDE1MDYzNzU3NjA0MDQ4NCwxMDE1MDYzNzU4MDQ1NTQ4NCwxMDE1MDYzNzU5NzQ2MDQ4NCwxMDE1MDYzNzYxNDUyMDQ4NCwxMDE1MDYzNzYzMDg0NTQ4NCZyZWY9bm90aWYmbm90aWZfdD1hcHBfcmVxdWVzdCJ9&client_id=217174461634478&redirect_uri=http://www.fisharwe.com/facebookredirect.axd
Why is the redirect_uri http://www.fisharwe.com/facebookredirect.axd and not what I've set in my code using top.location.href="whatever.com"?
UPDATE:
Seems like that problem has been resolved somehow. But it still does not redirect to the registration page of my site! Here's the source code of the landing page:
<html><head><script type="text/javascript">
top.location = "http://www.facebook.com/dialog/oauth/?state=eyJyIjoiaHR0cDovL2FwcHMuZmFjZWJvb2suY29tL2Zpc2hhcndlLz90eXBlPWRpc2NvdmVyeSJ9&client_id=217174461634478&redirect_uri=http://www.fisharwe.com/facebookredirect.axd";
</script></head><body></body></html>
UPDATE2:
This is my C# code:
[CanvasAuthorize]
public ActionResult Index()
{
var fb = new FacebookWebClient(FacebookWebContext.Current);
dynamic requestInfo = fb.Get("/me/apprequests/");
var b = requestInfo.Count;
if (requestInfo.data.Count > 0)
{
var a = requestInfo["data"][0]["data"];
//ViewData.Add("TrackingData", a);
return Redirect(redirectUrl + "?code=" + a);
}
return RedirectToAction("Index", "Home");
}

have you setup the http handler in web.config?
<httpHandlers>
<add verb="*" path="facebookredirect.axd" type="Facebook.Web.FacebookAppRedirectHttpHandler, Facebook.Web" />
</httpHandlers>

Related

Delphi: REST Request with BASIC authentication

I'm using TRESTClient/THTTPBasicAuthenticator/TRESTRequest/TRESTResponse to get data from a server.
With response Ok (200), instead of receiving JSON data, I get as content this:
<script type="text/javascript">
<!-- function redirectToIndex()
{
var adresse = window.location.pathname.split('/');
var httpURL = window.location.hostname + "/" + "app"; // redirect to root
var httpsURL = "https://" + httpURL;
window.location = httpsURL;
}
redirectToIndex(); //-->
This is when TRESTRequest.Accept is empty. If I change for TRESTRequest.Accept:= 'application/json', I get an error
406 - Not Acceptable
Could you tell me what's wrong with my request?
Thank you Peter.
I managed to clarify with the API support the BASIC Authentication using the correct login/password . The documentation was inaccurate.
Access is now working as expected.

How to manage contacts using Contacts API in our website correctly?

I was trying to integrate Google Contacts API to manage the contacts in my website.
I've done the following things:
I've created an application in google developer console and added http://localhost:4200 as URIs & Authorized redirect URIs.
Enabled 'Contacts API'.
I've added the following in my index.html (I've replaced {clientID} with my original client ID (of course):
<script>
function loadAuthClient() {
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: '{clientID}'
}).then(() => {
console.log("success");
}).catch(err => {
console.log(err);
});
});
}
</script>
<script src="https://apis.google.com/js/platform.js?onload=loadAuthClient" async defer></script>
<meta name="google-signin-client_id" content="{clientID}">
Signed in successfully using:
gapi.auth2.getAuthInstance().signIn().then(() => {
console.log("Logged in")
}).catch(err => {
console.log(err);
});
Tried fetching the contacts using the following:
var user = gapi.auth2.getAuthInstance().currentUser.get();
var idToken = user.getAuthResponse().id_token;
var endpoint = `https://www.google.com/m8/feeds/contacts/`;
var xhr = new XMLHttpRequest();
xhr.open('GET', endpoint + '?access_token=' + encodeURIComponent(idToken));
xhr.setRequestHeader("Gdata-Version", "3.0");
xhr.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
window.alert(xhr.responseText);
}
};
xhr.send();
But I'm getting the error:
Access to XMLHttpRequest at 'https://www.google.com/m8/feeds/contacts/?access_token={I removed the access token}' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Can someone please guide me where I'm going wrong?
My original response was off the mark. The actual answer is much simpler.
In step 4, try changing your endpoint:
var endpoint = `https://www.google.com/m8/feeds/contacts/default/full`;
In my local tests, this resulted in the expected response.
Another suggestion is to add alt=json to your query, so that you get easy to parse JSON payload. Otherwise you'll get a nasty XML payload in the response.
Here's the updated step 4 with these changes:
var endpoint = `https://www.google.com/m8/feeds/contacts/default/full`;
var xhr = new XMLHttpRequest();
xhr.open('GET', endpoint + '?access_token=' + encodeURIComponent(idToken) + '&alt=json');
xhr.setRequestHeader("Gdata-Version", "3.0");
xhr.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
window.alert(xhr.responseText);
}
};
xhr.send();
Here's my original response, just in case it helps someone else.
I suspect that you'll need to add http://localhost:4200 to your list of "Authorized JavaScript origins" for the OAuth Client that you are using.
Edit your OAuth 2.0 Client ID and add the URI to the Javascript origins as below:
The other section on that page, Authorized Redirect URIs, only permits the OAuth flow to be redirected back to your web app. Often your web app server will actually consume the APIs so Google doesn't automatically permit CORS access to these APIs to keep things secure.

Strophe session attachment -- 403 forbidden

I am working on an XMPP web application which need to include session attachment. I am using Openfire XMPP server. I have successfully implemented the server side attachments where the session is created and I get the sid and rid of a session. Unfortunately, I am stuck in the next part.
As I know, after getting the sid and rid, I need to use the Strophe.Connection.attach() to attach strphe to the existing session. After that I am making an IQ request which gets the correct response from the server. However, I am not getting any changes in the status i.e. the app is neither connected nor attached and hence I am not able to do anything.
After the IQ request, the server responds on time with the normal message and then in the next request, I get a 403 forbidden error and the connection is terminated.
Here is the code:
var BOSH_SERVICE = 'http://localhost/cosys-rtw/';
var connection = null;
var sid = "";
var rid = 0;
function notifyUser(msg)
{
if (msg.getAttribute('from') == "testuser1#ghost/pingstream") {
var elems = msg.getElementsByTagName('body');
var body = elems[0];
$('#notifications').append(Strophe.getText(body));
}
return true;
}
function onConnect(status)
{
console.log("Connect")
console.log(status)
if (status == Strophe.Status.ATTACHED) {
$('#notifications').html('<p class="welcome">Hello! Any new posts will appear below.</p>');
connection.addHandler(notifyUser, null, 'message', null, null, null);
connection.send($pres().tree());
}
}
$(document).ready(function () {
$.ajax({'url':'http://localhost/x',
'method':'get',
'success':function(response){
console.log(response);
console.log(jQuery.parseJSON(response));
resp = jQuery.parseJSON(response);
window.sid = resp.sid;
window.rid = resp.rid;
prepareStrophe();
}});
});
function prepareStrophe(){
console.log(BOSH_SERVICE);
jid = "testuser1#ghost";
connection = new Strophe.Connection(BOSH_SERVICE);
console.log(window.rid);
console.log(window.sid);
connection.attach( jid,window.sid,window.rid,null);
connection.sendIQ( $iq({to:Strophe.getDomainFromJid(jid),type:"get"})
.c('query',{xmlns:'http://jabber.org/protocol/disco#info'}),
function(){
if (status == Strophe.Status.ATTACHED) {
connection.send($pres().tree());}
});}
I get the follwoing response to the IQ request:
<body xmlns="http://jabber.org/protocol/httpbind">
<iq id="6173:sendIQ" xmlns="jabber:client" type="result" from="ghost" to="testuser1#ghost/6b8bfe07">
<query xmlns="http://jabber.org/protocol/disco#info">
<identity category="server" name="Openfire Server" type="im"></identity>
<identity category="pubsub" type="pep"></identity>
<feature var="http://jabber.org/protocol/pubsub#delete-nodes"></feature>
.
.
.
<feature var="http://jabber.org/protocol/pubsub#purge-nodes"></feature>
<feature var="http://jabber.org/protocol/disco#info"></feature>
<feature var="http://jabber.org/protocol/rsm"></feature>
</query>
</iq>
</body>
This response does say that the session is valid. Am I right?
I am not able to figure this thing so now I am handing this to the community.
By the way -- Merry Christmas
I think that I have got something here that I would like to share if anyone has the same problem. This thread on ignite realtime http://community.igniterealtime.org/thread/33004 discusses about this issue. The settings mentioned there did work for me.

What might cause errors validating verification code? (facebook oAuth from MVC3 issue)

I've recently started having trouble logging into my site using Facebook. I keep seeing this error message:
Facebook.FacebookOAuthException: (OAuthException) Error validating verification code.
There have been significant changes to the site and software; before I dig in to the changes, I'd like to eliminate some of the simple, common causes.
Could this be a firewall issue (the site is behind a firewall and not accessible from outside our network)? What are the most common causes for this error message?
Make sure your redirectUri parameter is the same as the redirecturi you used on https://www.facebook.com/dialog/oauth call.
For example, given an initial authentication request
using Facebook;
public ActionResult fbLogOn( string token, string returnUrl )
{
var oAuthClient = new FacebookOAuthClient( FacebookApplication.Current );
oAuthClient.RedirectUri =
new Uri( "http://" + "localhost:3434" + "/Home/fbOAuth" );
<... etc ...>
Make sure the handler for the facebook response sets the redirect URI to the exact same URI:
using Facebook;
public ActionResult fbOAuth(string code, string state )
{
FacebookOAuthResult oauthResult;
if (FacebookOAuthResult.TryParse( Request.Url, out oauthResult ))
{
string token = HttpUtility.UrlDecode( state );
if (oauthResult.IsSuccess)
{
var oAuthClient = new FacebookOAuthClient( FacebookApplication.Current );
oAuthClient.RedirectUri =
new Uri( "http://" + "localhost:3434" + "/Home/fbOAuth" );
dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken( code );
string accessToken = tokenResult.access_token;
<... etc ...>

Facebook Login and Iframe redirection

I am building an Facebook IFrame App. I am using the below javascript code to request user to login and allow permissions for the application, after which they are supposed to be redirected to the iframe app. The code works correctly. But, I have two issues with it.
a. as soon as the app loads in IFrame, it redirects to a page (http://www.facebook.com/connect/uiserver.php?app_id=......) and displays a large facebook icon. When I click this icon it redirects to facebook login page. I want my app to redirect to the login page directly instead of showing the inbetween facebook icon page.
b. When the user clicks 'Allow' button for the requested permission in facebook, the page redirects to my main site (http://www.mysite.com) instead of the iframe application(http://apps.facebook.com/myapp).
I have pasted my javascript below, this works with above quirks.
var api_key = 'xxxxxxxxxxxxxxx';
var channel_path = 'xd_receiver.htm';
FB_RequireFeatures(["Api"], function () {
FB.Facebook.init(api_key, channel_path);
var api = FB.Facebook.apiClient;
// require user to login
api.requireLogin(function (exception) {
FB.Connect.showPermissionDialog("publish_stream");
});
});
Help much appreciated.
I have remembered something!
You must use target="_top" in all your links and redirections in a iframe application!
Hope I help you.
Thanks for your answers.
I used the solution posted by McKAMEY(Facebook API: FB.Connect.requireSession issues) with few changes, and it works as intended, without showing the intermediate facebook icon page, and also it redirects after authentication to the iframe app correctly.
I have posted below the working solution in case someone needs it.
var api_key = 'xxxxxxxxxxxx';
var channel_path = './xd_receiver.htm';
var canvas_url = "http://apps.facebook.com/myappxxxx/"// ensure your canvasurl has a '/' at the end!
function Initialize() {
FB_RequireFeatures(["Api"], function () {
FB.Facebook.init(api_key, channel_path);
FB.ensureInit(function () {
FB.Connect.ifUserConnected(
function () {
var uid = FB.Connect.get_loggedInUser();
if (!uid) {
authRedirect();
return;
}
},
authRedirect);
});
});
}
function authRedirect() {
//This is the Sample URL Structure for redirecting to facebook
//http://www.facebook.com/connect/uiserver.php?
//app_id=XXXXXXXXXXXXX&
//next=xxxxxxxxxx_success_url_here_XXXXXXX&
//display=page&
//perms=XXXXXX_comma_seperated_permissions_list_hereXXXXXX&
//fbconnect=1&
//method=permissions.request
window.top.location.href = "http://www.facebook.com/connect/uiserver.php?app_id=" + encodeURIComponent(api_key) + "&next=" + encodeURIComponent(canvas_url) + "&display=page&perms=publish_stream&fbconnect=1&method=permissions.request";
}
Initialize();
Note on redirecting within a frame to the Facebook login page. You have to use javascript to redirect the entire page since the login page passed the X-Frame-Options:DENY header and modern browsers will prevent you from sending the user to the URL if that header is present. Solution is to use javascript::window.top.location = ''; to redirect the whole page
I'm not sure on the middle page between redirection but what does your apps canvas and connect url point to?
The redirection after login should go to that page unless you have this overridden somewhere in your code.
Change the urls in the settings on fb to apps.facebook.com/myapp if that's not what its set to.
You may use the new Facebook Graph API (http://developers.facebook.com/docs/api) to handle authentication. First, you must check if you have the access_token:
$access_token = $_REQUEST['access_token'];
if($access_token != NULL) {
...
}
else {
// the following javascript
}
And the javascript is:
<script type="text/javascript">
top.location.href = '<?= "https://graph.facebook.com/oauth/authorize?client_id=".$appid."&redirect_uri=".$appurl."oauth_redirect" ?>'
</script>
You must have a file oauth_redirect.php like this:
<?php
$code=$_REQUEST['code'];
$url = "http://graph.facebook.com/oauth/access_token?client_id=".$appid."&redirect_uri=".$appurl."oauth_redirect&client_secret=".$appsecret."&code=$code";
$curl = curl_init();
// SET URL FOR THE POST FORM LOGIN
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CUPROPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CUPROPT_SSL_VERIFYHOST, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION ,1);
curl_setopt($curl, CURLOPT_HEADER ,0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER ,1);
// EXECUTE 1st REQUEST (LOGIN)
$response = curl_exec ($curl);
?>
<script type="text/javascript">
top.location.href = '<?= $appurl."?".$response ?>';
</script>
Finally, you can return to your index page (the $appurl variable) and test if the user has permission testing access_token presence.
Hope it helps!