I want to create a C# console application to create a post on my FaceBook account wall.
I tried to search how to get this but all i get is information about get access_token in web application where we can add redirect URL : http://localhost.
I am using below code to get an access_token in Console application.
But i get output from this below code is :
{
"access_token": "*****|*************",
"token_type": "bearer"
}
Which App_ID|App_Secret..where user Access_token should be of very big length.
Is this possible to post on facebook account wall using console application??
private const string FacebookApiId = "************";
private const string FacebookApiSecret = "**************************";
private const string AuthenticationUrlFormat =
"https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials&scope=manage_pages,offline_access,publish_stream";
static void Main(string[] args)
{
string accessToken = GetAccessToken(FacebookApiId, FacebookApiSecret);
PostMessage(accessToken, "My message");
}
static string GetAccessToken(string apiId, string apiSecret)
{
string accessToken = string.Empty;
string url = string.Format(AuthenticationUrlFormat, apiId, apiSecret, "manage_pages,offline_access,publish_stream");
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
NameValueCollection query = HttpUtility.ParseQueryString(responseString);
accessToken = query["access_token"];
}
if (accessToken.Trim().Length == 0)
throw new Exception("There is no Access Token");
return accessToken;
}
Related
I have a c# asp.net web application.
I am using the facebook login through their javascript sdk and it does the login.
Now I have a Simple WYSIWYG Editor in which whatever is added should be posted on the facebook page of that logged in user.
Following is the code:
string FacebookApiId = "952214336368241";
string FacebookApiSecret = "fb2213d66523c8cb0bc99306f46ee457";
string accessToken = GetAccessToken(FacebookApiId, FacebookApiSecret);
PostMessage(accessToken, "My message");
private string GetAccessToken(string apiId, string apiSecret)
{
string AuthenticationUrlFormat = "https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials&scope=manage_pages,offline_access,publish_stream";
string accessToken = string.Empty;
string url = string.Format(AuthenticationUrlFormat, apiId, apiSecret);
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
String responseString = reader.ReadToEnd(); // this gives me {"access_token":"952214336368241|McqSGYIMU1eYBZ1zGydWj9hu6Bt","token_type":"bearer"}
NameValueCollection query = HttpUtility.ParseQueryString(responseString);
accessToken = query["access_token"]; // This line throws error
}
//if (accessToken.Trim().Length == 0)
//throw new Exception("There is no Access Token");
return "952214336368241|McqSGYIMU1eYBZ1zGydWj9hu6B"; // hard-coded to get it working;
}
private void PostMessage(string accessToken, string v)
{
try
{
FacebookClient facebookClient = new FacebookClient(accessToken);
dynamic messagePost = new ExpandoObject();
messagePost.access_token = accessToken;
messagePost.message = v;
var result = facebookClient.Post("/[user id]/feed", messagePost);
}
catch (FacebookOAuthException ex)
{
//handle something
}
catch (Exception ex)
{
//handle something else
}
}
This throws error:
{"(OAuthException - #803) (#803) Some of the aliases you requested do not exist: [user id]"}
I even wrote my facebook emailid instead of [user id] but it still does not work and gives me error:
Message: "(OAuthException - #2500) An active access token must be used to query information about the current user."
Can anyone please advise how can I remove this error.
The code is VERY old, offline_access and publish_stream do not exist anymore since many years.
You have to use a Page Token with the publish_pages permission in order to post to your Page with the API.
You can use "me/feed" or "page-id/feed", but not an Email.
Information about Tokens and how to generate them:
https://developers.facebook.com/docs/facebook-login/access-tokens/
https://www.devils-heaven.com/facebook-access-tokens/
Try stuff in the API Explorer before programming: https://developers.facebook.com/tools/explorer/
I have looked up all the questions regarding basic authorization in web api using httpweb request and none of them solved my problem. I have a web api (written in C#) and I want to establish basic authorization for the api. I also have a web page that I am using to call the api. However, it keeps returning "(401)Unauthorized" and I don't know what I'm doing wrong. Right now I'm using the username and password in the code but I want there to be a pop up asking for credentials.
This is the code for my web page, calling the api:
string url = String.Format("http://example.com");
HttpWebRequest requestObj = (HttpWebRequest)WebRequest.Create(url);
requestObj.Method = "Get";
requestObj.Credentials = new NetworkCredential("testing", "123456");
HttpWebResponse responseObj = null;
responseObj = (HttpWebResponse)requestObj.GetResponse();
string strresult = null;
using (Stream stream = responseObj.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
strresult = sr.ReadToEnd();
sr.Close();
}
In my api, I opened a class called BasicAuthenticationAttribute and wrote this:
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
public static bool IsAuthorizedUser(string Username, string Password)
{
return Username == "testing" && Password == "123456";
}
public override void OnAuthorization(HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
if (actionContext.Request.Headers.Authorization != null)
{
var authToken = actionContext.Request.Headers.Authorization.Parameter;
var decodeauthToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
var arrUserNameandPassword = decodeauthToken.Split(':');
if (IsAuthorizedUser(arrUserNameandPassword[0], arrUserNameandPassword[1]))
{
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(arrUserNameandPassword[0]), null);
}
else
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
else
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
}
And in my controller, I have this:
[BasicAuthentication]
public class EventsController : ApiController
{
}
This is the error I'm receiving:
The remote server returned an error: (401) Unauthorized.
Try adding credentials to credential cache with type of authorization and instead of using credentials directly use cache.
string url = String.Format("http://example.com");
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri(url), "Basic", new NetworkCredential("testing", "123456"));
HttpWebRequest requestObj = (HttpWebRequest)WebRequest.Create(url);
requestObj.PreAuthenticate = true;
requestObj.Method = "Get";
requestObj.Credentials = **credentialCache**;
HttpWebResponse responseObj = null;
responseObj = (HttpWebResponse)requestObj.GetResponse();
string strresult = null;
using (Stream stream = responseObj.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
strresult = sr.ReadToEnd();
sr.Close();
}
As mentioned in the messages above, I believe the issue is because you are not removing "Basic" from the authentication header. https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/basic-authentication
What I'd do...
string authToken = actionContext.Request.Headers.Authorization.Parameter;
authToken = authToken.Replace("Basic", string.Empty);
var decodeauthToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
And try this when you split. About the only thing different in your implementation than what I've done multiple times.
var arrUserNameandPassword = decodeauthToken.Split(':'c);
I'm trying to access JIRA data (get project) using JIRA REST API. Here is how I'm making it:
public enum JiraResource
{
project
}
public class JiraService : IJiraService
{
#region JiraService member functions
/* public void DoWork()
{
}*/
private const string str_baseURL = "https://jira.atlassian.com/rest/api/latest/issue/JRA-9";
private string str_Username;
private string str_Password;
public JiraService(string username,string password)
{
str_Username = username;
str_Password = password;
}
public string runQuery(
JiraResource resource,
string argument = null,
string data = null,
string method = "GET")
{
string url = string.Format("{0}{1}/",str_baseURL,resource.ToString());
// string url = string.Format("{0}{1}/", str_baseURL);
if(argument != null)
{
url = string.Format("{0}{1}/",url,argument);
}
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = method;
if (data != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}
}
string base64Credentials = GetEncodedCredentials();
request.Headers.Add("Authorization", "Basic " + base64Credentials);
HttpWebResponse response = request.GetResponse() as HttpWebResponse; //Getting error here.
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{ result = reader.ReadToEnd(); }
return result;
}
private string GetEncodedCredentials()
{
string mergedCredentials = string.Format("{0}:{1}", str_Username, str_Password);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
return Convert.ToBase64String(byteCredentials);
}
I'm using username and password as admin and admin (I think this is default). Please note that, this url ("https://jira.atlassian.com/rest/api/latest/issue/JRA-9") showing me json objects from the browser. However, from my code, I'm getting exception "Remote server returned error (407) proxy authentication required ".
As per this post(The remote server returned an error: (407) Proxy Authentication Required) I used useDefaultCredentials="true". But this is not working.
Is there anything that I'm missing? Please guide me.
I have a website write (.net 4) and i am tring to create some facebook login.
After i download Facebook sdk for c#, i am tring to get user info using the access token.
It seems to me that i am doing something wrong, all the examples i examined, were little bit diffrent from mine. instead of getting me paramethers by :
me["id"] // mine
me.id // examples
when i try to get values like the examples i got errors.
also i am having problem with get the email address of user, already add email to scope:
This method responsible for get the access token:
public string GetAccessToken()
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
strAppId, Request.Url.AbsoluteUri, strScope, Request["code"].ToString(), strAppSecret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
return access_token;
}
This method responsible for get user information:
public string GetUserInfo(string strToken)
{
var client = new FacebookClient(strToken);
dynamic me = client.Get("me");
User user = new User();
try
{
string user_id = me["id"];
string user_first_name = me["first_name"];
string user_last_name = me["last_name"];
string user_name = me["username"];
string user_location = me["location"]["name"];
string user_city = me["hometown"]["name"];
//user_mail = me.email; }
catch(Exception ex)
{
}
return string.Empty;
}
when try to run on me.email or me["email"] i get this error:
'me.email' threw an exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' dynamic {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException}
I suggest you to use Microsoft.AspNet.Mvc.Facebook. It's easy to use and has all these properties already done.
http://www.asp.net/mvc/tutorials/mvc-4/aspnet-mvc-facebook-birthday-app
c# login Google App Engine (GAE) returns http 500
c# google-app-engine http-status-code-500
I want to retrive user specific data form the app engine with a c# client. The Client uses the following code to authenticate:
private const string GoogleLoginUri = "https://www.google.com/accounts/ClientLogin";
private const string AppBaseUri = "http://sphinx-online.appspot.com/";
private const string AppLoginUri = AppBaseUri + "_ah/login";
private const string AppMyStarredQuestionnaireUri = AppBaseUri + "res/MyStarredQuestionnaires";
[...]
private static void RetrieveAuthToken(SyncStorage syncStorage)
{
// Request
HttpWebRequest authRequest = (HttpWebRequest)HttpWebRequest.Create(GoogleLoginUri);
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.AllowAutoRedirect = false;
String postData = string.Format("Email={0}&Passwd={1}&service={2}&source={3}&accountType={4}",
Uri.EscapeUriString(syncStorage.Username),
Uri.EscapeUriString(syncStorage.Password),
Uri.EscapeUriString("apps"),
Uri.EscapeUriString("lippodesign-sphinx-1.0"),
Uri.EscapeUriString("GOOGLE"));
byte[] buffer = Encoding.ASCII.GetBytes(postData);
authRequest.ContentLength = buffer.Length;
using (Stream postDataStr = authRequest.GetRequestStream())
{
postDataStr.Write(buffer, 0, buffer.Length);
postDataStr.Flush();
}
// Response
HttpWebResponse authResponse = (HttpWebResponse)authRequest.GetResponse();
using (StreamReader responseReader = new StreamReader(authResponse.GetResponseStream()))
{
while (true)
{
String line = responseReader.ReadLine();
if (line == null)
{
break;
}
else if (line.StartsWith("Auth="))
{
syncStorage.AuthToken = line.Substring(5);
break;
}
}
}
}
private static void RetrieveCookie(SyncStorage syncStorage)
{
Uri cookieRequestUrl = new Uri(string.Format("{0}?auth={1}", AppLoginUri, syncStorage.AuthToken));
HttpWebRequest cookieRequest = (HttpWebRequest)WebRequest.Create(cookieRequestUrl);
cookieRequest.Method = "GET";
cookieRequest.ContentType = "application/x-www-form-urlencoded";
cookieRequest.AllowAutoRedirect = false;
using (HttpWebResponse cookieResponse = (HttpWebResponse)cookieRequest.GetResponse())
{
syncStorage.Cookie = cookieResponse.Headers["Set-Cookie"];
}
}
private static void RetrieveData(SyncStorage syncStorage)
{
Uri dataRequestUrl = new Uri(AppMyStarredQuestionnaireUri);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(dataRequestUrl);
request.Headers["Cookie"] = syncStorage.Cookie;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
syncStorage.JsonData = streamReader.ReadToEnd();
}
}
}
All works fine for a while, but since I try it before two days I always get an http-error-code 500 (Internal Error) when I want to get the cookie (RetrieveCookie-Method). I think it does not work since I activate 2-Step-Authentication. The Google ClientLogin for Installed Applications says:
Important: If any of your customers are having trouble with ClientLogin, their account may not be compatible with it for a variety of possible reasons. For example, accounts that use 2-step verification, SAML, or Open ID are not compatible with ClientLogin. One workaround is to tell users to generate a single-use password, provided by access codes, which allows them to log in to their account in a web browser and generate a long password that they can type into the password field of any application using ClientLogin. A better solution is to convert your app to use OAuth 2.0, which is compatible with all existing Google accounts.
I use an Application-specific password for login. Before I get a http-error 403 "Authentication failed" while getting the auth-token.
I have no idea why I can't retrieve the cookie. Getting the auth-token works fine.
And the Webservice has no problem, I can call it over a browser without having trouble if I am loggend in.