I'm building an application that allows users to post message to their facebook from the application. To problem I'm having that I don't know how to get the user access_token for the publish_stream permission.
This is what I've got so far:
var fb = new FacebookClient();
dynamic result = fb.GetLoginUrl(new
{
client_id = AppID,
client_secret = AppSecret,
grant_type = "client_credentials",
scope = "publish_stream",
state = "http://localhost:17578/Facebook.aspx",
redirect_uri = "http://localhost:17578/Facebook.aspx"
});
That works fine and it returns a 'code' in the querystring. However, I'm not sure what to do with that code.
The 'old' Facebook C# sdk contained the FacebookOAuthClient class which had the ExchangeCodeForAccessToken() method, but I don't know what the replacement of this static method is in the new SDK.
So the question really is: How to exchange the code that is returned for an access_token?
After you get the code query string parameter you must make a call to the Facebook Graph API to get the access token.
https://developers.facebook.com/docs/howtos/login/server-side-login/
FacebookClient client = new FacebookClient();
dynamic result = client.Get("oauth/access_token", new { client_id = Settings.Social_Facebook_App_Id, client_secret = Settings.Social_Facebook_Secret_Key, code = Request.QueryString["code"], redirect_uri = Settings.Social_Facebook_Login_Redirect_URI });
if (result.error == null)
{
Session["AccessToken"] = client.AccessToken = result.access_token;
dynamic user = client.Get("me", new { fields = "name,username,email" });
string userName = user.username;
mu = Membership.GetUser(userName);
if (mu == null) // Register
{
RegisterModel rm = new RegisterModel();
rm.Email = user.email;
rm.UserName = userName;
return View("Register", rm);
}
else
{
FormsAuthentication.SetAuthCookie(userName, true);
return RedirectToAction(MVC.Home.Index());
}
}
Related
HI I am trying to use Microsoft graph api to send messages.
Previously, I was sending messages/emails with the graph api without attachment. Now I need to attach 10 attachment each.
So I looked for examples and got to the Microsoft document and it shows the following code
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var attachment = new FileAttachment
{
Name = "smile",
ContentBytes = Convert.FromBase64String("R0lGODdhEAYEAA7")
};
await graphClient.Me.Messages["{message-id}"].Attachments
.Request()
.AddAsync(attachment);
Link:
https://learn.microsoft.com/en-us/graph/api/message-post-attachments?view=graph-rest-1.0&tabs=csharp
My question is what it is showing is not clear I am not sure I would I use message-id. Also I dont see if the Message is created and how the attachment is created.
Can someone help please.
You may refer to this document to learn the example about how to send email with attachments. And the below is my test code, it worked for me, I used client credential flow to provide authentication..
using Azure.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Graph;
public class HomeController : Controller
{
private readonly IWebHostEnvironment _appEnvironment;
public HomeController(IWebHostEnvironment appEnvironment)
{
_appEnvironment = appEnvironment;
}
public async Task<string> sendMailAsync() {
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "your_tenant_name.onmicrosoft.com";
var clientId = "azure_ad_clientid";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var a = _appEnvironment.WebRootPath;//I have a file stored in my project
var file = a + "\\hellow.txt";
byte[] fileArray = System.IO.File.ReadAllBytes(#file);
//string base64string = Convert.ToBase64String(fileArray);
var message = new Message
{
Subject = "Meet for lunch?",
Body = new ItemBody
{
ContentType = BodyType.Text,
Content = "The new cafeteria is open."
},
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "xxx#outlook.com"
}
}
},
Attachments = new MessageAttachmentsCollectionPage()
{
new FileAttachment
{
Name = "attachment.txt",
ContentType = "text/plain",
ContentBytes = fileArray
}
}
};
await graphClient.Users["user_id"]
.SendMail(message, null)
.Request()
.PostAsync();
return "success";
}
}
Please help me. The API I created works fine when I launch it with Visual Studio but (the POST methods) has issues I deployed to IIS.
It returns wrong values and sometimes, null values. If i go back to test it in debug mode it works well.
THIS IS WHERE I'M CALLING THE API
try
{
string apiToken = "DEFAULTAPI";
EmployeeObject EmployeeObject = new EmployeeObject()
{
username = "John Doe"
password = "12345"
apiToken = apiToken
};
var emp = JsonConvert.SerializeObject(EmployeeObject);
string url = "http://localhost/PublishVersion/api/Company";
//the url variable holds the published version link
var response = client.PostAsync(url, new StringContent(emp, Encoding.UTF8, "application/json"));
response.Wait();
var result = response.Result;
if (result.IsSuccessStatusCode)
{
Uri employeeUrl = result.Headers.Location;
var statusMessage = result.Content.ReadAsStringAsync().Result;
if (statusMessage == "yes")
{
status = true;
}
else if (statusMessage == "no")
{
status = false;
}
}
return status;
}
AND THIS IS THE API
public string Post([FromBody] Employees employees)
{
string message = "no";
if (employees != null)
{
string emp = employees.username;
string password = employees.password
string apiToken = employees.apiToken
APIToken token = _dbContext.MyTable.Where(x => x.apitoken == apitoken).FirstOrDefault();
//APIToken is a table which has properties company and boss (both string)
if (token != null)
{
string company = token.company;
string boss = token.boss;
return message = "yes" + " " + company + "" + boss;
}
else
{
return message = "invalid token";
}
}
return message + employee.username;
}
The api returns "no John Doe" to the caller, which shouldn't be that way, since it displayed the username value which shows that the employee object is not null. Why doesn't it go into the block of code since it passed the null check? This issue only comes up when I deploy the API project to the IIS (version 10). Works fine in Visual Studio debug mode.
Also, the API and Winsform(where i'm calling it from) are on the same machine.
Thank you.
i am integrating my CRM application to Yammer for that i have create an App inside Yammer and by using ClientID, Client Secret and redirect URL i am authenticating an Yammer user to app.
Problem is, that whenever user changes password or any other user trying to login through app it asks to allow permission or not. I just dont want this if any user logging in to yammer by using my app it should automatically allow. please help me regarding this i am posting my code also
referalUrl = oauthUrl + clientId;
oauthUrl =oauthUrl+ clientId + "&redirect_uri=" + redirUrl; //For authentication to Yammer
//referalUrl = oauthUrl + clientId;
accessTokenUrl = accessTokenUrl + "client_id=" + clientId + "&client_secret=" + clientSecret + "&code=";
string qsCode = string.Empty;
string accessToken = "";
string postResults = string.Empty;
string response = string.Empty;
string firstName = string.Empty;
string lastName = string.Empty;
//string currentUser = string.Empty;
object yammerUserId = this.PrimaryDataRow[YammerUserTable.Field.YammerUserId];
object currentUserId = this.SystemClient.UserProfile.EmployeeId;
if (string.IsNullOrEmpty(accessToken))
{
while (string.IsNullOrEmpty(qsCode))
{
response = YammerAPIRequest.MakeGetRequest(oauthUrl, null, true);
//look for authenticity token
string authToken = YammerAPIRequest.GetAuthenticityToken(response);
if (!string.IsNullOrEmpty(authToken))
{
string f = System.Web.HttpUtility.UrlEncode(authToken);
userName = System.Web.HttpUtility.UrlEncode(userName);
//password = System.Web.HttpUtility.UrlEncode(password);
string postBody = "utf8=%E2%9C%93&authenticity_token=" + System.Web.HttpUtility.UrlEncode(authToken) + "&network_permalink=aptean.com&login=" +
userName + "&password=" + password + "&remember_me=on";
postResults = YammerAPIRequest.MakeLoginPostRequest(postBody, loginUrl, f, null, referalUrl);
}
qsCode = postResults;
if (qsCode.IndexOf("code") == -1 && qsCode.IndexOf("redirect_uri")==-1)
{
PivotalMessageBox.Show("Please enter Correct Username or Password");
return false;
}
else
{
PivotalMessageBox.Show("You have Logged in to Yammer");
string postreq = "utf8=%E2%9C%93&authenticity_token=" + System.Web.HttpUtility.UrlEncode(authToken) + "&allow=Allow";
string allowurl="https://www.yammer.com/aptean.com/oauth2/decision?client_id=BAUC8GdiEZ5ximkabWM9Q&redirect_uri=https%3A%2F%2Fwww.yammer.com%2Faptean.com%2F&response_type=code";
string allow = YammerAPIRequest.AllowtoApp(postreq, allowurl, authToken, null, null);
if (allow != "")
{
qsCode = allow;
}
I just dont want this if any user logging in to yammer by using my app
it should automatically allow
This is by design and can't be altered/bypassed from your code. Users must be given the option to Allow or Deny the use of yammer third party applications.
You may consider using the impersonation endpoint if it suits your use case - https://developer.yammer.com/docs/impersonation
I'm trying out the facebook api. I'm getting this error that i'm not authorized to perform this action. I have accepted all the pop-ups that came when i run the program. Anyone got a quick soulution for this?
sing Facebook;
public void CheckAutorization()
{
string app_Id = "xxxxxxxxxxxxxxx";
string app_secret = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
string scope = "publish_stream, manage_pages";
if (Request["code"] == null)
{
Response.Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_Id, Request.Url.AbsoluteUri, scope));
}
else
{
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}",
app_Id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
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('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
client.Post("/me/feed", new { message = "Is there anyone out there? :) Can i get a whoop whoop" });
}
}
}
}
Had to change the scope string scope = "publish_stream, manage_pages" to string scope = "publish_stream, publish_actions";
I'm using the facebook sdk api, in a class to return a public facebook pages posts. But it returns blank, it doesn't throw an error.
var client = new FacebookClient();
dynamic result = client.Get("oauth/access_token", new
{
client_id = facebook_AppID, //App Id
client_secret = facebook_AppSecret, //App Secret
grant_type = "client_credentials" //client_credentials
});
var AccessToken = result.access_token;
var facebookClient = new FacebookClient(AccessToken);
JsonObject pagePost = facebookClient.Get("/thepagename/posts") as JsonObject;
string html = "";
foreach (var account in (JsonArray)pagePost["data"])
{
html += (string)(((JsonObject)account)["message"]);
}
What am I missing?