authentication using yammer - rest

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

Related

Web API Returns Wrong Values after being Published to IIS

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.

Box.com API Usage - Get Folder Count as a service app

We are creating an app that is meant to be used with a Service Account in your system; another user (user-2) has authorized this app by adding our app key to their Custom Application list. How do I get this User-2's UserID, so we can impersonate him and access his files list and files, etc. We need their UserID, so we can pass the "AS-User: " Header. And can this header be set using some property from within the .NET SDK - a sample code will be appreciated.
This does it for all enterprise users but you can easily put an if statement to get the user you're looking for.
static async Task MainAsync()
{
// rename the private_key.pem.example to private_key.pem and put your JWT private key in the file
var privateKey = File.ReadAllText(PRIVATE_KEY_FILE);
var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, privateKey, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID);
var boxJWT = new BoxJWTAuth(boxConfig);
var adminToken = boxJWT.AdminToken();
Console.WriteLine("Admin Token: " + adminToken);
Console.WriteLine();
var adminClient = boxJWT.AdminClient(adminToken); // adminClient == serviceAccount
var userDetails = await adminClient.UsersManager.GetCurrentUserInformationAsync();
Console.WriteLine("\tAdmin User Details:");
Console.WriteLine("\tId: {0}", userDetails.Id);
Console.WriteLine("\tName: {0}", userDetails.Name);
Console.WriteLine("\tStatus: {0}", userDetails.Status);
Console.WriteLine();
var users = await adminClient.UsersManager.GetEnterpriseUsersAsync();
users.Entries.ForEach(i =>
{
Console.WriteLine("\t{0}", i.Name);
Console.WriteLine("\t{0}", i.Status);
if (i.Status == "active")
{
var userToken = boxJWT.UserToken(i.Id);
var userClient = boxJWT.UserClient(userToken, i.Id);
Task u = getUserItems(userClient, i.Id);
u.Wait();
}
});
}
static async Task getUserItems(BoxClient userClient, string id)
{
var userDetails = await userClient.UsersManager.GetCurrentUserInformationAsync();
Console.WriteLine("\nManaged User Details:");
Console.WriteLine("\tId: {0}", userDetails.Id);
Console.WriteLine("\tName: {0}", userDetails.Name);
Console.WriteLine("\tStatus: {0}", userDetails.Status);
Console.WriteLine();
Console.WriteLine("managed users older items");
var items = await userClient.FoldersManager.GetFolderItemsAsync("0", 500);
items.Entries.ForEach(i =>
{
Console.WriteLine("\t{0}", i.Name);
});
Console.WriteLine();
}

(OAuthException - #200) (#200) The user hasn't authorized the application to perform this action

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";

Getting user access_token from Facebook

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());
}
}

Facebook FQL page_user

Right i have a problem which i have done so much research for that i still cant be able to solve the problem. What i am trying to achieve is when a facebook user LIKES my page not an app, i want to be able to retrieve all the users that have liked the facebook page.
I am using FQL but having no luck at all, if i do an FQL based on the admins of the page it brings the data up.
SELECT first_name, last_name FROM user WHERE uid IN (SELECT uid FROM page_fan WHERE page_id = [your page id])
the above FQL should work. But nothing is being displayed, is this a facebook bug that has not been flagged or fixed?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCFacebookTestApp.Models;
using Facebook;
using Facebook.Web;
namespace MVCFacebookTestApp.Controllers
{
public class HomeController : Controller
{
public FacebookSession FacebookSession
{
get { return (FacebookWebContext.Current.Session); }
}
public ActionResult Index()
{
string request = Request.Form["signed_request"];
string accessToken = "";
if (Request.Form["access_token"] != null)
{
accessToken = Request.Form["access_token"];
}
FacebookApplication app = new FacebookApplication();
FacebookSignedRequest result = FacebookSignedRequest.Parse(app.InnerCurrent, request);
if (String.IsNullOrWhiteSpace(accessToken))
{
accessToken = result.AccessToken;
}
dynamic data = result.Data;
bool liked = data.page.liked;
//bool liked = true;
if (!liked)
{
Home h = Home.NotLiked();
return View(h);
}
else
{
Home h = Home.Liked();
FacebookWebClient fb = null;
if (String.IsNullOrWhiteSpace(accessToken))
{
var fbRequest = FacebookWebContext.Current;
if (fbRequest.IsAuthorized())
fb = new FacebookWebClient(fbRequest);
}
else
{
fb = new FacebookWebClient(accessToken);
}
if (fb != null)
{
dynamic r = fb.Get("/me");
h.TestString2 += " Ha! We captured this data about you!";
h.TestString2 += " Name: " + r.name;
h.TestString2 += " Location: " + r.location;
h.TestString2 += " Birthday: " + r.birthday;
h.TestString2 += " About Me: " + r.aboutme;
h.ImgUrl = "http://graph.facebook.com/" + r.id + "/picture?type=large";
string fqlResult = "";
var fbApp = new FacebookClient(accessToken);
//basic fql query execution
dynamic friends = fbApp.Query("SELECT uid FROM page_admin WHERE page_id='160828267335555'");
//SELECT uid FROM page_fan WHERE page_id = 160828267335555
//"SELECT uid FROM page_fan WHERE uid=me() AND page_id=<your page id>";
//loop through all friends and get their name and create response containing friends' name and profile picture
foreach (dynamic friend in friends)
{
fqlResult += friend.uid + "<br />";
//fqlResult += friend.name + "<img src='" + friend.pic_square + "' alt='" + friend.name + "' /><br />";
}
ViewBag.Likes = fqlResult;
}
else
{
//Display a message saying not authed....
}
return View(h);
}
}
}
}
is there a solution out there that actually works? Please do get back to me ASAP your help would be much appreciated, will save me from losing all my hair with the stress LOL
Thanks in advance.
You can make a GET request to /USER_ID/likes/PAGE_ID (replacing the caps part with the relevant IDs) to check if a particular user is a fan of your page. This is the replacement for the old 'pages.isFan' API method.
There's no way to retrieve a list of users that like your page.