I am using The Facebook-C#-Sdk v5.0.3 to create a non-canvas webforms app in vb.net and i am having trouble exchanging the returned facebook code for the access_token. Does anyone have an example (C# or vb.net) that I can look at?
Thanks awesome Stackoverflow community!
Try this:
var app = new FacebookClient(FacebookContext.Current.AppId, FacebookContext.Current.AppSecret);
var accessToken = app.AccessToken
or this:
var app = new FacebookClient(new Authorizer().Session.AccessToken);
var accessToken = app.AccessToken
You can use the appId and appSecret as the app accesstoken.
For instance you can do this when debugging an user token to see if it's valid
var client = new FacebookClient();
dynamic result = client.Get("debug_token", new
{
input_token = user.AccessToken,
access_token = string.Format("{0}|{1}", appId, appSecret)
});
Later you can check result.data.is_valid to see if the user token is still valid.
If you need the access_token of a user, you first need to set the scope correctly, later you can do this:
if (Request["code"] == null)
{
Response.Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
appId, Request.Url.AbsoluteUri, scope));
}
else
{
var 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}",
appId, Request.Url.AbsoluteUri, scope, Request["code"], appSecret);
var request = WebRequest.Create(url) as HttpWebRequest;
using (var response = request.GetResponse() as HttpWebResponse)
{
var 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));
}
}
// Get access token from tokens
var accessToken = tokens["access_token"];
}
This will redirect the user to Facebook asking for permission. Then Facebook will return to the return URL with code in the querystring, use that code to retreive the user's access_token.
Keep in mind this will be a short-lived access_token, you will probably have to expand it.
Related
I need to read the gmail inbox feed using Oauth2.0. Simulating in the postman,
Auth URL : https://accounts.google.com/o/oauth2/auth
Access Token URL : https://accounts.google.com/o/oauth2/token
Client ID : XXXXX.apps.googleusercontent.com
Client Secret : XXXXX
Scope : https://mail.google.com/mail/feed/atom
GrantType: Authorization Code
I requested the token and used it on the header
Authorization - Bearer XXXXXXXXXX.
And I made the request via GET right in my scope and got my email feeds. Works!!!
The postman generates a code in C #, but the token expires.
var client = new RestClient("https://mail.google.com/mail/feed/atom/");
var request = new RestRequest(Method.GET);
request.AddHeader("postman-token", "d48cac24-bd3e-07b5-c616-XXXXXXXX");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Bearer ya29.a0AfH6SMDZlUmw0xLHAoYIJuIfTkXXXXXXXXQSPP17GmXT26fJEfWB9w8UiwQ2YF32-nOp6zY9H_lwJEEXXXXXXXXXXXYK4e0tcZkieGbBl5Eow2M-7Gxp20kfDtXXXXXVjiXymLXyMkYEI");
IRestResponse response = client.Execute(request);
I'm trying to do it via Google.Api, using GoogleAuthorizationCodeFlow and already using token refresh.
With the code below, I got authorization from the application, but I can't read the xml atom feed
GoogleAuthorizationCodeFlow flow;
var assembly = Assembly.GetExecutingAssembly();
var clientfile = #"client_secrets.json";
using (var stream = new FileStream(clientfile, FileMode.Open, FileAccess.Read))
{
flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
DataStore = new FileDataStore("StoreTest"),
ClientSecretsStream = stream,
Scopes = new[] { "https://mail.google.com/mail/feed/atom/" }
});
}
var uri = Request.Url.ToString();
var code = Request["code"];
if (code != null)
{
var token = flow.ExchangeCodeForTokenAsync(UserId, code,
uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;
// Extract the right state.
var oauthState = AuthWebUtility.ExtracRedirectFromState(
flow.DataStore, UserId, Request["state"]).Result;
Response.Redirect(oauthState);
}
else
{
var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(UserId,
CancellationToken.None).Result;
if (result.RedirectUri != null)
{
// Redirect the user to the authorization server.
Response.Redirect(result.RedirectUri);
}
else
{
// The data store contains the user credential, so the user has been already authenticated.
var gmailfeed = new GmailService(new BaseClientService.Initializer
{
HttpClientInitializer = result.Credential,
ApplicationName = "GetFeed",
});
var inboxlistRequest = gmailfeed.Users.Messages.List("me");
inboxlistRequest.LabelIds = "Label_19780355190759038";
inboxlistRequest.IncludeSpamTrash = false;
var emailListResponse = inboxlistRequest.Execute();
foreach (var mail in emailListResponse.Messages)
{
var mailId = mail.Id;
var threadId = mail.ThreadId;
Message message = gmailfeed.Users.Messages.Get("me", mailId).Execute();
Console.WriteLine((message.Snippet));
}
}
}
I got to read the email, but I need the xml atom feed.
Could someone help me how I make this call to get the atom feed, using the granted token. If there is an easier way to do it too, it would be cool to share.
Thank you
Resolved using respsharp, restclient!!
tks
I have a web app running in Azure which has azure Active Directory authentication enabled. This is given below (I have configured this correctly there is no issue with this): -
Now I want to call one of the API of this web app. Code for getting access token based on the client credentials: -
public static string GetAccessToken()
{
string authContextURL = "https://login.microsoftonline.com/" + "TENANT_ID";
var authenticationContext = new AuthenticationContext(authContextURL);
var credential = new ClientCredential("CLIENT_ID", "CLIENT_SECRET");
var result = authenticationContext.AcquireTokenAsync("URL_FOR_MY_WEBAPP", credential).Result;
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the token");
}
string token = result.AccessToken;
return token;
}
Code for calling the desired API: -
private static string GET(string URI, string token)
{
Uri uri = new Uri(string.Format(URI));
// Create the request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
// Get the response
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (Exception ex)
{
return ex.Message;
}
string result = null;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
I am getting an unauthorized error while getting the response. Could anyone tell what is wrong here? The same service principal is working with graph client. Any help or suggestion will be appreciated.
The resource to acquire access token is not correct. You should use the same client id of your AD app.
var result = authenticationContext.AcquireTokenAsync("{CLIENT_ID}", credential).Result;
After quite searching i was able to post on Facebook Page as myself. but my target was to post on the Page i manage as the page. I did some more research and i was able to get the access token of the page i manage. when i tried to POST on it, sdk gave me the error that
The user hasn't authorized the application to perform this action
here is my code for your reference :
string app_id = "xxxxx";
string app_secret = "yyyyyyy";
string scope = "publish_actions,manage_pages";
if (Request["code"] == null)
{
string url = string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope);
Response.Redirect(url, false);
}
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 = System.Net.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"];
var client = new FacebookClient(access_token);
dynamic parameters = new ExpandoObject();
parameters.message = "Check out this funny article";
parameters.link = "http://www.natiska.com/article.html";
parameters.picture = "http://www.natiska.com/dav.png";
parameters.name = "Article Title";
parameters.caption = "Caption for the link";
//zzzzzzz is my fan page
string pageAccessToken = "";
JsonObject jsonResponse = client.Get("me/accounts") as JsonObject;
foreach (var account in (JsonArray)jsonResponse["data"])
{
string accountName = (string)(((JsonObject)account)["name"]);
if (accountName == MY_PAGE_NAME)
{
pageAccessToken = (string)(((JsonObject)account)["access_token"]);
break;
}
}
client = new FacebookClient(pageAccessToken);
client.Post("/zzzzzzz/feed", parameters);
You need the publish_pages permission to post as pages.
https://developers.facebook.com/docs/graph-api/reference/v2.3/page/feed#publish
Your Facebook App Dosn't have manage_page & publish_page permission, instead of this you can create test application and from that u can create test users for your testing .
From there u can manage all the pages posts and data.
I am trying to post a message to a Facebook page from a C# web application. I am getting the following exception thrown on calling FacebookClient.Post(...):
FacebookOAuthException (OAuthException - #200) (#200) The user hasn't
authorized the application to perform this action
Code:
var facebookClient = new FacebookClient();
facebookClient.AppId = appId;
facebookClient.AppSecret = appSecret;
if (Request["code"] == null)
{
var authUrl = facebookClient.GetLoginUrl(new
{
client_id = appId,
client_secret = appSecret,
scope = "publish_stream",
redirect_uri = Request.Url.AbsoluteUri
});
Response.Redirect(authUrl.AbsoluteUri);
}
else
{
dynamic result = facebookClient.Get("oauth/access_token", new
{
client_id = appId,
client_secret = appSecret,
grant_type = "client_credentials",
redirect_uri = Request.Url.AbsoluteUri,
code = Request["code"]
});
facebookClient.AccessToken = result.access_token;
// Store access token
}
Sending a message:
protected void PublishMessage(string message)
{
FacebookClient client = new FacebookClient(AccessToken);
client.AppId = ApplicationId;
client.AppSecret = ApplicationSecret;
dynamic parameters = new ExpandoObject();
parameters.message = message;
client.Post(PageName + "/feed", parameters);
}
I accept the following Facebook prompts to ensure that the app has access:
And in my Facebook profile settings, the app looks like this:
I am using the Facebook SDK for .NET v6.4.2 (the latest).
This may seem a silly question, but aren't you missing the Request code from your access token request? Shouldn't it be like this?
dynamic result = facebookClient.Get("oauth/access_token", new
{
client_id = appId,
client_secret = appSecret,
grant_type = "authorization_code"
redirect_uri = Request.Url.AbsoluteUri,
code = Request["code"]
});
Edit Just realized, you have to use a different grant_type when using the request code :)
I am developing social networks integration for my asp.net mvc4 application.
Twitter and Facebook were very easy for me but I am seriously stuck with LinkedIn.
Here is my code.
public ActionResult LinkedInTest(string text)
{
var client = new RestClient
{
Authority = "https://api.linkedin.com/uas/oauth",
Credentials = LinkedInSocialHelper.GetCredentials()
};
var request = new RestRequest {Path = "requestToken"};
RestResponse response = client.Request(request);
token = response.Content.Split('&')[0].Split('=')[1];
tokenSecret = response.Content.Split('&')[1].Split('=')[1];
textToPost = text;
Response.Redirect("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token + "&scope=r_basicprofile+r_emailaddress+r_network+r_contactinfo+rw_nus");
return null;
textToPost = text;
return RedirectToAction("LinkedInCallback");
}
public ActionResult LinkedInCallback()
{
verifier = Request["oauth_verifier"];
var client = new RestClient
{
Authority = "https://api.linkedin.com/uas/oauth",
Credentials = LinkedInSocialHelper.GetCredentials(token, tokenSecret, verifier),
Method = WebMethod.Post
};
var request = new RestRequest {Path = "accessToken"};
RestResponse response = client.Request(request);
token = response.Content.Split('&')[0].Split('=')[1];
tokenSecret = response.Content.Split('&')[1].Split('=')[1];
LinkedInSocialHelper.Post(textToPost, token, tokenSecret);
return RedirectToAction("Calendar");
}
public static void Post(string text, string accessToken, string accessTokenSecret)
{
var tokenManager = new TokenManager(ApiKey, ApiSecret);
tokenManager.ExpireRequestTokenAndStoreNewAccessToken(null, null, accessToken, accessTokenSecret);
var authorization = new WebOAuthAuthorization(tokenManager, UserToken);
LinkedInService service = new LinkedInService(authorization);
//var user = service.GetCurrentUser(ProfileType.Public); - IT IS GIVING ME THE SAME ERROR - Access denied
service.CreateShare(text, VisibilityCode.ConnectionsOnly);
}
Everything works fine except last thing - posting shares - I get Access to posting shares denied exception despite the fact that I generate token using all the necessary permissions:
"https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token + "&scope=r_basicprofile+r_emailaddress+r_network+r_contactinfo+rw_nus"
Hope you good guys help me.
See the last post here - it describes how to solve it
https://developer.linkedin.com/forum/permission-scope-request-token-query-not-working?page=1