I am stuck into a problem for which I have not found any solution or documentation.
I am building an app using Facebook API in which user will create an app and will give their APP ID & APP SECRET to the application in order to create pages or post to pages.
Now the problem is they will only login into my application not in facebook nor login using FB.
I am getting APP ACCESS TOKEN from APP ID & APP SECRET.
Using https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=APP_SECRET&grant_type=client_credentials
But how could i use it to get pages for that account or generate USER ACCESS TOKEN from it?
Please help me with your expert guidance.
Thanks.
You cannot create Apps nor Pages by using the Graph API! See https://developers.facebook.com/docs/graph-api/reference/v2.0/page
If you want to publish to a Page the logged-in User administrers, you can request the respective Page Access Token (with publish_actions and manage_pages permissions!) via
GET /me/accounts
See
https://developers.facebook.com/docs/graph-api/reference/v2.0/user/accounts/
https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens
first of create developer apps and get token give some permission
public ActionResult Index()
{
var url = "http://www.facebook.com/v2.0/dialog/oauth/?scope=user_friends,read_friendlists,read_stream,read_insights,manage_pages,user_checkins,user_photos,read_mailbox,manage_notifications,read_page_mailboxes,email,user_videos,user_groups,offline_access,publish_actions,manage_pages&client_id=" + ConfigurationManager.AppSettings["ClientId"] + "&redirect_uri=" + ConfigurationManager.AppSettings["RedirectUrl"] + "&response_type=code";
return Redirect(url);
}
that automatic redirect call back url for example
public ActionResult AddFacebookAccount(string code)
{
string ret = string.Empty;
string client_id = ConfigurationManager.AppSettings["ClientId"];
string redirect_uri = ConfigurationManager.AppSettings["RedirectUrl"];
string client_secret = ConfigurationManager.AppSettings["ClientSecretKey"];
long friendscount = 0;
try
{
FacebookClient fb = new FacebookClient();
string profileId = string.Empty;
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("client_id", client_id);
parameters.Add("redirect_uri", redirect_uri);
parameters.Add("client_secret", client_secret);
parameters.Add("code", code);
JsonObject fbaccess_token = null;
try
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
fbaccess_token = (JsonObject)fb.Get("/oauth/access_token", parameters);
}
catch (Exception ex)
{
try
{
fbaccess_token = (JsonObject)fb.Get("/oauth/access_token", parameters);
}
catch (Exception ex1)
{
ViewBag.acc_tkn= "issue_access_token";
}
}
string accessToken = fbaccess_token["access_token"].ToString();
Session["AccessToken"] = accessToken;
if (accessToken != null)
{
fb.AccessToken = accessToken;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
dynamic profile = fb.Get("v2.2/me");
dynamic friends = fb.Get("v2.2/me/friends");
try
{
Session["uid"] = profile.id;
friendscount = Convert.ToInt16(friends["summary"]["total_count"].ToString());
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
ViewBag.acc_tkn = accessToken;
ViewBag.Uid = profile.id;
}
return View();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
ViewBag.acc_tkn= "Something Went Wrong";
return View();
}
}
you will get access Token when post data on page refer Bellow Code
public void FacebookPostonPage(string file, string message, string tokenid)
{
JsonObject fbaccess_token = null;
FacebookClient fb = new FacebookClient();
fb.AccessToken = tokenid;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
fbaccess_token = (JsonObject)fb.Get("v2.0/me/accounts");
dynamic Result = fbaccess_token["data"];
foreach (var obj in Result)
{
string result = FacebookComposeMessage(obj.access_token, obj.id, message, file);
}
}
public string FacebookComposeMessage(string tokenid,string userid ,String message,string imagepath)
{
FacebookClient fb = new FacebookClient();
string ret = "";
fb.AccessToken = tokenid;
fb.AppId = ConfigurationManager.AppSettings["ClientId"];
fb.AppSecret = ConfigurationManager.AppSettings["ClientSecretKey"];
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
var args = new Dictionary<string, object>();
args["message"] = message;
if (!string.IsNullOrEmpty(imagepath))
{
var media = new FacebookMediaObject
{
FileName = "filename",
ContentType = "image/jpeg"
};
byte[] img = System.IO.File.ReadAllBytes(imagepath);
media.SetValue(img);
args["source"] = media;
ret = fb.Post("v2.0/" + userid + "/photos", args).ToString();
}
else
{
ret = fb.Post("v2.0/" + userid + "/feed", args).ToString();
// ret = fb.Post("/" + objFacebookAccount.FbUserId + "/photos", args).ToString();
// var data = fb.Get("v2.2" + ret);
}
return ret;
}
You will post Successfully try now
Related
I have created a native app in Azure using App Registration and added required permissions for VSTS Agent
Now, I am able to login using oauth authentication with "ADAL" and able to get the token but when trying to access the web api request it gives Http 403 Response
Here is the code example below
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(vstsCollectionUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-TFS-FedAuthRedirect", "Suppress");
client.DefaultRequestHeaders.Authorization = authHeader;
HttpResponseMessage res = client.GetAsync(webapiURL).Result;
}
Please let me know what i am missing
thanks in advance
Seems it's an authentication issue, Just check the value of authHeader.
You can reference below samples for the authentication with header:
Sample 1- auth-samples here ;
Sample 2 - REST API
Post the auth sample as reference here:
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
namespace DeviceProfileSample
{
public class Program
{
//============= Config [Edit these with your settings] =====================
internal const string vstsCollectionUrl = "https://myaccount.visualstudio.com"; //change to the URL of your VSTS account; NOTE: This must use HTTPS
internal const string clientId = "872cd9fa-d31f-45e0-9eab-6e460a02d1f1"; //update this with your Application ID from step 2.6 (do not change this if you have an MSA backed account)
//==========================================================================
internal const string VSTSResourceId = "499b84ac-1321-427f-aa17-267ca6975798"; //Static value to target VSTS. Do not change
public static void Main(string[] args)
{
AuthenticationContext ctx = GetAuthenticationContext(null);
AuthenticationResult result = null;
try
{
DeviceCodeResult codeResult = ctx.AcquireDeviceCodeAsync(VSTSResourceId, clientId).Result;
Console.WriteLine("You need to sign in.");
Console.WriteLine("Message: " + codeResult.Message + "\n");
result = ctx.AcquireTokenByDeviceCodeAsync(codeResult).Result;
var bearerAuthHeader = new AuthenticationHeaderValue("Bearer", result.AccessToken);
ListProjects(bearerAuthHeader);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Something went wrong.");
Console.WriteLine("Message: " + ex.Message + "\n");
}
}
private static AuthenticationContext GetAuthenticationContext(string tenant)
{
AuthenticationContext ctx = null;
if (tenant != null)
ctx = new AuthenticationContext("https://login.microsoftonline.com/" + tenant);
else
{
ctx = new AuthenticationContext("https://login.windows.net/common");
if (ctx.TokenCache.Count > 0)
{
string homeTenant = ctx.TokenCache.ReadItems().First().TenantId;
ctx = new AuthenticationContext("https://login.microsoftonline.com/" + homeTenant);
}
}
return ctx;
}
private static void ListProjects(AuthenticationHeaderValue authHeader)
{
// use the httpclient
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(vstsCollectionUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("User-Agent", "VstsRestApiSamples");
client.DefaultRequestHeaders.Add("X-TFS-FedAuthRedirect", "Suppress");
client.DefaultRequestHeaders.Authorization = authHeader;
// connect to the REST endpoint
HttpResponseMessage response = client.GetAsync("_apis/projects?stateFilter=All&api-version=2.2").Result;
// check to see if we have a succesfull respond
if (response.IsSuccessStatusCode)
{
Console.WriteLine("\tSuccesful REST call");
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
Console.WriteLine("{0}:{1}", response.StatusCode, response.ReasonPhrase);
}
}
}
}
}
Aren't you missing what authentication,
string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", token)));
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(vstsCollectionUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials)
HttpResponseMessage response = client.GetAsync(uri).Result;
response.EnsureSuccessStatusCode();
var responseStream = await response.Content.ReadAsStreamAsync();
}
I hope this helps.
I am new to facebook c# sdk. I followed the tutorial in this link.
I created an application that displays the user name after log in. Here is my code:
public partial class MainWindow : Window
{
private string appId = "appid";
private string extenededPermissions = "offline_access,publish_stream";
private Uri loginUrl = null;
private string accessToken = null;
private string userName = null;
public MainWindow()
{
InitializeComponent();
}
/// <summary>
/// Function to get the login url
/// with the requested permissions
/// </summary>
private void GetLoginUrl()
{
dynamic parameters = new ExpandoObject();
// add the client id
parameters.client_id = appId;
// add the redirect uri
parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
// requested response
parameters.response_type = "token";
// type of display
parameters.display = "popup";
// If extended permissions are present
if (!string.IsNullOrWhiteSpace(extenededPermissions))
parameters.scope = extenededPermissions;
// Create the login url
Facebook fc = new FacebookClient();
loginUrl = fc.GetLoginUrl(parameters);
}
private void WindowLoaded(object sender, RoutedEventArgs e)
{
// get the login url
GetLoginUrl();
// Navigate to that page
webBrowser.Navigate(loginUrl);
}
private void webBrowser_Navigated(object sender, NavigationEventArgs e)
{
var fc = new FacebookClient();
FacebookOAuthResult fr;
// Check the returned url
if (fc.TryParseOAuthCallbackUrl(e.Uri, out fr))
{
// check if authentication is success or not
if (fr.IsSuccess)
{
getUserName(out userName);
}
else
{
var errorDes = fr.ErrorDescription;
var errorReason = fr.ErrorReason;
}
}
else
{
}
}
private void getUserName(out string name)
{
var fb = new FacebookClient(accessToken);
// Get the user details
dynamic result = fb.Get("me");
// Get the user name
name = result.name;
MessageBox.Show("Hai " + name + ",Welcome to my App");
}
}
My Problem is with the FacebookOAuthResult.
private void webBrowser_Navigated(object sender, NavigationEventArgs e)
{
var fc = new FacebookClient();
FacebookOAuthResult fr;
// Check the returned url
if (fc.TryParseOAuthCallbackUrl(e.Uri, out fr))
{
// check if authentication is success or not
if (fr.IsSuccess)
{
getUserName(out userName);
}
else
{
var errorDes = fr.ErrorDescription;
var errorReason = fr.ErrorReason;
}
}
else
{
}
}
After I logged in it is redirecting to redirect_uri. But the fc.TryParseOAuthCallbackUrl(e.Uri, out fr) fails though the webbrowser redirects to the Authentication successful page.
So I couldn't get the access token. What could the problem in my code be?
This doesn't answer the question, but I see you are asking for an offline_access permission. Facebook removed offline_access sometime ago. Instead you need an Extended Access Token. You get it by exchanging the access token you are trying to get, for an extended one. They last for about 2-3 months after which you have to get a new one.
Nevermind i have found out the solution..Thanks to the answers for the question!
I have added the Winforms web browser control to the wpf and the authentication is working.The problem is with WPF web browser. It simply omits the url after # token So the parseurl won't able to authenticate it.
Here's the modified code..
private void WindowLoaded(object sender, RoutedEventArgs e)
{
// create the windows form host
System.Windows.Forms.Integration.WindowsFormsHost sample =
new System.Windows.Forms.Integration.WindowsFormsHost();
// create a new web browser
webBrowser = new System.Windows.Forms.WebBrowser();
// add it to winforms
sample.Child = webBrowser;
// add it to wpf
canvas1.Children.Add(sample);
webBrowser.Navigated += webBrowser_Navigated;
webBrowser.Navigate(loginURL);
}
void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
// do the authentication
var fc = new FacebookClient();
FacebookOAuthResult fr;
// Check the returned url
if (fc.TryParseOAuthCallbackUrl(e.Url, out fr))
{
// check if authentication is success or not
if (fr.IsSuccess)
{
accessToken = fr.AccessToken;
// Actions to do
}
else
{
var errordes = fr.ErrorDescription;
var errorreason = fr.ErrorReason;
}
}
else
{
//Not a valid url
}
}
The problem is solved!!
In my app I authorization through facebook, all was ok. But now I try login through FB and get error: An error occurred. Please try again later. I update my Facebook, but It doesn't help
This is my code
private const string ExtendedPermissions = "user_about_me";
private FacebookClient _fb = new FacebookClient();
public MainPage()
{
InitializeComponent();
var parameters = new Dictionary<string, object>();
parameters["client_id"] = FacebookSettings.AppID;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "page";
parameters["scope"] = ExtendedPermissions;
Uri ur = _fb.GetLoginUrl(parameters);
webBrowser1.Navigate(ur);
}
private void Browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs l)
{
if (!_fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
if (oauthResult.IsSuccess)
{
var accessToken = oauthResult.AccessToken;
LoginSucceded(accessToken);
}
else
{
MessageBox.Show(oauthResult.ErrorDescription);
}
}
I have a problem logging out of Facebook on Windows Phone. I have the code to login, but I can't log out of it. Can someone show me how to log out of Facebook on a Windows Phone?
Here's the login code:
private FacebookClient _asyncFbClient;
private string _appID = "";
private string _appSecret = "";
private void StartFacebookLogin(object sender, RoutedEventArgs e)
{
string[] extendedPermissions = new[] { "user_about_me", "publish_stream", "email" };
FacebookClient fb = new FacebookClient();
var oauth = new FacebookOAuthClient { AppId = _appID, AppSecret = _appSecret };
var logout = new FacebookUser();
var parameters = new Dictionary<string, object>
{
{"response_type", "token"},
{"display", "touch"}
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
var loginUrl = oauth.GetLoginUrl(parameters);
webBrowser.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(CheckForAuth);
webBrowser.Navigate(loginUrl);
}
private void CheckForAuth(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(e.Uri, out result))
{
if (result.IsSuccess)
{
IsolatedStorageSettings Settings = IsolatedStorageSettings.ApplicationSettings;
MessageBox.Show(result.AccessToken);
access = result.AccessToken;
if (Settings.Contains("MyFacebookAccessToken1"))
Settings["MyFacebookAccessToken1"] = result.AccessToken;
else
Settings.Add("MyFacebookAccessToken1", result.AccessToken);
Settings.Save();
_asyncFbClient = new FacebookClient(result.AccessToken);
_asyncFbClient.GetCompleted += new EventHandler<FacebookApiEventArgs>(_asyncFbClient_GetCompleted);
_asyncFbClient.GetAsync("/me");
}
}
}
Here's the logout code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(linkUrl);
request.Method = "GET";
request.BeginGetResponse(new AsyncCallback(LogoutResponse), request);
private void LogoutResponse(IAsyncResult result)
{
string responseData = "";
try
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse;
if (response != null && response.StatusCode == HttpStatusCode.OK)
{
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
responseData = reader.ReadToEnd();
//responseData = true
}
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() => { MessageBox.Show(ex.Message); });
}
}
I have tried to use Facebook's logout API and get a successful result, but the next time I open the web browser it's already automatically logged in to Facebook again. How can I get it to log out?
I tried quite a few hacks to get this to work... and then Facebook finally updated their documentation with a good answer:
Logout
You can log a user out of their Facebook session by directing them to
the following URL:
https://www.facebook.com/logout.php?next=YOUR_URL&access_token=ACCESS_TOKEN
YOUR_URL must be a URL in your site domain, as defined in the
Developer App.
From http://developers.facebook.com/docs/authentication/
there is no FB Logout, it has been removed.
your best bet is to forget your credentials.
Facebook PHP SDK uses a function like this:
public function getLogoutUrl($params=array()) {
return $this->getUrl(
'www',
'logout.php',
array_merge(array(
'next' => $this->getCurrentUrl(),
'access_token' => $this->getAccessToken(),
), $params)
);
}
Which creates a URL like:
https://www.facebook.com/logout.php?next={YOUR_ENCODED_URL}&access_token={YOUR_ACCESS_TOKEN}
I believe the encoded URL must be owned by the application to whom the access_token belongs.
If you get that URL right, it'll work (just tried for one of my applications).
I'm not 100% sure if it works on windows-phone, but you can give it a try.
Hi Im writing an app that allows users to post status updates from within the application, I believe that ive got the authentication working correctly for the login, I just dont know how to go about posting a status update. Any code/examples/tutorials of how to go about doing this would be fantastic, here is the code that I have so far for the authentication.
public partial class FacebookAuth : PhoneApplicationPage
{
private string _accessToken;
private WebBrowser _webBrowser;
public FacebookAuth()
{
InitializeComponent();
_webBrowser = new WebBrowser();
this.Loaded += new RoutedEventHandler(FacebookAuthPage_Loaded);
}
void FacebookAuthPage_Loaded(object sender, RoutedEventArgs e)
{
//Get this from the facebook
string appId = "XXXXXXXXXXXXXXX";
string[] extendedPermissions = new[] { "publish_stream", "offline_access", "user_groups" };
var oauth = new FacebookOAuthClient { AppId = appId };
//Telling the Facebook that we want token as response
//and we are using touch enabled device
var parameters = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "display", "touch" }
};
//If there's extended permissions build the string and set it up
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
//Create the login url
var loginUrl = oauth.GetLoginUrl(parameters);
//Add webBrowser to the contentPanel
ContentPanel.Children.Add(_webBrowser);
_webBrowser.Navigated += webBrowser_Navigated;
//Open the facebook login page into the browser
_webBrowser.Navigate(loginUrl);
}
void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
//Try because there might be cases when user input wrong password
if (FacebookOAuthResult.TryParse(e.Uri.AbsoluteUri, out result))
{
if (result.IsSuccess)
{
_accessToken = result.AccessToken;
MessageBox.Show(_accessToken);
//Hide the browser controller
_webBrowser.Visibility = System.Windows.Visibility.Collapsed;
}
else
{
var errorDescription = result.ErrorDescription;
var errorReason = result.ErrorReason;
MessageBox.Show(errorReason + " " + errorDescription);
}
}
}
private void PostBtn_Click(object sender, RoutedEventArgs e)
{
}
}
}
To publish a status, do an HTTP Post to /me/feed with a post parameter called "message" and it's value being what the authenticate user posted.
Using FacebookClient
var client = new FacebookClient(user_access_token);
dynamic parameters = new ExpandoObject();
parameters.message = "Hello World!"
dynamic post_id = client.Post("/me/feed", parameters);
See also: http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx