Let me put my code first
string strSigned = Request.Params["signed_request"];
// JSONObject obj = JSONObject.CreateFromString(strSigned);
Facebook.FacebookSignedRequest fb = FacebookSignedRequest.Parse(AppSecret, strSigned);
JsonObject jsonObj = fb.Data as JsonObject;
if (!jsonObj.ContainsKey("user_id"))
{
string appId = App_Id;
string redirectUrl = "http://127.0.0.1/Default.aspx"
string redirectstr = "https://www.facebook.com/dialog/oauth?client_id=" + appId + "&redirect_uri=" + redirectUrl + "&scope=email,read_stream";
Page.ClientScript.RegisterStartupScript(this.GetType(), "redirect", "<script>top.location.href='" +redirectstr +"'</script>");
Response.Clear();
}
else
{
Response.Write(jsonObj["user_id"].ToString());
}
Above code runs perfectly untill user press allow permissions.the application is actually redirecting to the mentioned redirect_uri http:... and not staying within facebook.
i am really bugged with this.let me know the solution.
It is made this way so that it can be used by external sites which accept facebook login.
The redirect_uri can be set to:
apps.facebook.com/myapp/
or
www.facebook.com/pageurl?sk=app_YOUR_APP_ID
along with external site url.
Related
I have been using facebook api to share post on facebook page as facebook app. I have created facebook app.
The post also gets shared but the problem is, it is not being posted as a facebook app. Instead it asks user for login and then it shares post as a user. Any help regarding how could I share a post as a Facebook App would be appreciated as I have been trying this for a long time.
Thanx in advance friends.
The code that I have been using is as follows.
using Facebook;
protected void CheckAuthorization()
{
string authorizationCode = Request.QueryString["code"];
string access_token = Facebook_GetAccessToken(authorizationCode);
FacebookShare(access_token);
}
private string Facebook_GetAccessToken(string pAuthorizationCode)
{
string urlGetAccessToken = "https://graph.facebook.com/oauth/access_token";
urlGetAccessToken += "?client_id=my app id";
urlGetAccessToken += "&client_secret=app secret";
urlGetAccessToken += "&redirect_uri=" + Facebook_GetRedirectUri();
urlGetAccessToken += "&code=" + pAuthorizationCode;
string responseData = RequestResponse(urlGetAccessToken);
if (responseData == "")
{
return "";
}
NameValueCollection qs = HttpUtility.ParseQueryString(responseData);
string access_token = qs["access_token"] == null ? "" : qs["access_token"];
return access_token;
}
protected void FacebookShare(string token)
{
if (token != null)
{
Int64 transactionid = Convert.ToInt64(Cache["transactionid"]);
string app_id = "my app id";
string app_secret = "app secret";
string scope = "offline_access,read_stream,publish_actions,publish_stream,manage_pages,status_update";
dynamic parameters = new ExpandoObject();
parameters.link = "my website link";
parameters.name = "my project name";
parameters.picture= "my website logo";
var client = new FacebookClient(token);
client.Post("/1374775846180409/feed", parameters); // this is my facebook page id where I want to share post.
Response.Cookies["transaction"].Expires = DateTime.Now;
}
else
{
}
}
Regarding above code, I am getting Facebook Authorization code successfully.
You can only ask your user who has logged into your app to post on facebook, apps as such are not allowed to post.
You will need a page access token to post as the page, which have permissions to modify the data belonging to a Facebook Page. To obtain a page access token you need to start by obtaining a user access token, for which your user has to be logged into your app and asking for the manage_pages permission scope. Next, you can GET /me/accounts, which will return a page access token for each page that you manage.
This can not be accomplished using offline access or without logging in.
After the great news about Facebook and Microsoft support Facebook SSO I have tried to implement this in a winrt/xaml/c# app for windows 8.1, however I cannot get it to work.
I have registered the app with facebook and set the app's SID in the app's settings.
This is the login code:
Uri sid = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
string callbackURL = sid.ToString();
String facebookURL = "https://www.facebook.com/dialog/oauth?client_id=" + Uri.EscapeDataString(AppId) + "&display=touch&response_type=token&scope=publish_stream&redirect_uri=" + Uri.EscapeDataString(callbackURL);
var startUri = new Uri(facebookURL);
WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri);
This will open the Facebook login dialog, I can log in, and the next dialog says "You have already authorized .
But clicking on the "Okay" or "Skip" buttons gives no response back to my app. AuthenticateAsync() never returns.
If I change the &display parameter to "touch" it works, but this is not what I want since it shows a mobile login web page not designed for this purpose.
What is wrong ?
this issue has been resolved. Can you please give this a try and let us know if you are still seeing the issue?
Yes, now it works :-)
This is the code I use, and it works fine:
Uri sid = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
string callbackURL = sid.ToString();
string facebookURL = "https://www.facebook.com/dialog/oauth?client_id=" + Uri.EscapeDataString(AppId) + "&display=popup&response_type=token&scope=publish_stream&redirect_uri=" + Uri.EscapeDataString(callbackURL);
var startUri = new Uri(facebookURL);
WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, new Uri(callbackURL));
if (result.ResponseStatus == WebAuthenticationStatus.Success && !result.ResponseData.Contains("&error="))
{
string resultString = result.ResponseData.Replace("#", "&");
AccessToken = GetQueryParameter(resultString, "access_token");
wasSuccess = true;
IsLoggedIn = true;
CurrentUser = await FacebookApi.GetCurrentUserId();
}
return wasSuccess;
I am having an issue with the Aweber C# api from: http://aweber.codeplex.com/
I am getting an unauthorized response from the following code. I was wondering if someone could help me see what I am missing please?
String consumerKey = "####";
String consumerSecret = "####";
API api = new API(consumerKey, consumerSecret);
api.OAuthToken = "####";
api.OAuthTokenSecret = "####";
api.OAuthVerifier = "##";
Aweber.Entity.Account account = api.getAccount();
I am assuming I am missing something important, but I cant figure out what is is.
Thanks in advance for your help.
D.
You need to add following code before api.getAccount();
// Set callback url (if not set will default to this page)
api.CallbackUrl = "http://" + Request.Url.Host + ":" + Request.Url.Port + "/Authorize.aspx";
// Get request token
api.get_request_token();
// Save the token and secret in session
HttpContext.Current.Session.Add("oauth_token", api.OAuthToken);
HttpContext.Current.Session.Add("oauth_token_secret", api.OAuthTokenSecret);
// Will redirect user to the Aweber authorize page
api.authorize();
I need some help.
I don't no what to do after the user allows my application. On my pageLoad I verify if the URL has code(generated by Facebook) and redirect again with the string code to get the access token.
Facebook redirect again with the access token and now I have the token.
What is the next step?
...on pageload...
..........................
if (Request.QueryString["code"] != null && !Page.IsPostBack)
{
string code = Request.QueryString["code"];
string urlFinal = "https://graph.facebook.com/oauth/access_token?" +
"client_id=" + appID +
"&redirect_uri=" + redirectURL +
"&client_secret=" + appSecret +
"&code=" + code;
Response.Redirect(urlFinal);
}
else if (Request.QueryString["access_token"] != null)
string token = Request.QueryString["access_token"];
//AND NOW??
and redirect again with the string code to get the access token.
Don’t redirect to that address – it contains your app secret!
You should make a server-side call to that endpoint instead – as described in the authentication docs.
What is the next step?
That highly depends on what you want to do, don’t you think?
Hi I am working on sending twitter updates from my asp.net website. I have the authorization down but I am stuck when it gets to sending the tweet here is my code behind:
protected void btnAuth_Click(object sender, EventArgs e)
{
// add these to web.config or your preferred location
var consumerKey = ConfigurationManager.AppSettings["consumerKey"];
var consumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
//If User is not valid user
if (Request.QueryString["oauth_token"] == null)
{
//Step 1: Get Request Token
OAuthTokenResponse RequestToken = OAuthUtility.GetRequestToken(consumerKey,consumerSecret);
//Step 2: Redirect User to Requested Token
Response.Redirect("http://twitter.com/oauth/authorize?oauth_token="+ RequestToken.Token);
}
else
{
//For Valid User
string Oauth_Token = Request.QueryString["oauth_token"].ToString();
var accessToken = OAuthUtility.GetAccessToken(consumerKey, consumerSecret, Oauth_Token, txtPIN.Text.Trim());
lblMessage.Text = "<b>Hello " + accessToken.ScreenName + ", Welcome to my Twitter App<b>";
lblMessage.Text += "<br/> Token: " + accessToken.Token;
lblMessage.Text += "<br/> TokenSecret: " + accessToken.TokenSecret;
lblMessage.Text += "<br/> UserId: " + accessToken.UserId;
lblMessage.Text += "<br/> VerificationString: " + accessToken.VerificationString;
}
}
protected void btnTweet_Click(object sender, EventArgs e)
{
// add these to web.config or your preferred location
var consumerKey = ConfigurationManager.AppSettings["consumerKey"];
var consumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
OAuthTokens accessToken = new OAuthTokens();
accessToken.AccessToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
accessToken.AccessTokenSecret = "xxxxxxxxxxxxxxxxxxxx";
accessToken.ConsumerKey = consumerKey;
accessToken.ConsumerSecret = consumerSecret;
TwitterStatus TweetStatus = new TwitterStatus();
TweetStatus.Update(accessTokens, txtTweet.Text);
}
I dont know how to get the AccessToken & AccessTokenSecret. Any help would be great thanks.
The access token and secret values are returned to your application from Twitter when you call the OAuthUtility.GetAccessToken method:
var accessToken = OAuthUtility.GetAccessToken(consumerKey, consumerSecret, Oauth_Token, Request.QueryString["oauth_verifier"]);
The one-time authorization process goes as follows:
1) Get a request token
2) Send the user to Twitter to login and grant access
3) Receive the user at the callback url, collect the oauth_token and oauth_verifier values from the querystring
4) Exchange the request token and verifier for the access token
After you have the access token, you should store it so that the user isn't required to go through the process again (the access token does not expire).
I noticed that you're collecting a PIN value from the user, but it appears as though your application is a website. The web flow (not pin-based authentication) will provide a much more pleasant user experience.
If you have more questions, please post them to the Twitterizer forums, http://forums.twitterizer.net.
After a successful login, you just have to set all four variables in your OAuthTokens (AccessToken & AccessTokenSecret are both return on successful OAuthUtility.GetAccessToken)
I suggest you store you AccessToken and AccessToken in a Cookie once Authenticated.
Create a Static Class where you can return all four tokens and do a check if all four values are supplied ELSE logged-out.