we are experiencing problems with API authentication of our project in asp-net core 3.1. Specifically we have integrated the text-to-speech service provided by Google. Locally everything works correctly, but this does not happen when the web-app is online.
try
{
var path = "C://GoogleVoice//food-safety-trainer-47a9337eda0f.json";
var credential = GoogleCredential.FromFile(path);
var storage = StorageClient.Create(credential);
TextToSpeechClient client = TextToSpeechClient.Create();
var test = client.GrpcClient;
// The input can be provided as text or SSML.
SynthesisInput input = new SynthesisInput
{
Text = text
};
VoiceSelectionParams voiceSelection = new VoiceSelectionParams();
voiceSelection.LanguageCode = "it-IT";
voiceSelection.Name = "it-IT-Wavenet-A";
voiceSelection.SsmlGender = SsmlVoiceGender.Female;
// The audio configuration determines the output format and speaking rate.
AudioConfig audioConfig = new AudioConfig
{
AudioEncoding = AudioEncoding.Mp3
};
SynthesizeSpeechResponse response = client.SynthesizeSpeech(input, voiceSelection, audioConfig);
var result = _mp3Helper.SaveFile(response);
if (result.Item1 == "Success")
return Json(new { Result = true, Value = result.Item2 });
else
return Json(new { Result = false, Error = result.ToString() });
}
catch(Exception ex)
{
return Json(new { Result = false, Error = ex.Message.ToString() });
}
The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
Assuming you want to use the same service account for both Speech and Storage, you need to specify the credentials for the text-to-speech client. Options:
Set the GOOGLE_APPLICATION_DEFAULT_CREDENTIALS environment variable to refer to the JSON file. Ideally, do that as part of deployment configuration rather than in your code, but you can set the environment variable in your code if you want to. At that point, you can remove any explicit loading/setting of the credential for the Storage client.
Specify the CredentialPath in TextToSpeechClientBuilder:
var client = new TextToSpeechClientBuilder { CredentialPath = path }.Build();
This will load a separate credential.
Specify the credential's token access method via the TokenAccessMethod property in TextToSpeechClientBuilder:
var client = new TextToSpeechClientBuilder
{
TokenAccessMethod = credential.GetAccessTokenForRequestAsync
}.Build();
I am trying to post to my own status on Facebook using WinForms and the Facebook .NET SDK. I am using the code below to post an image. I get this error:
"The user hasn't authorized the application to perform this action"
I looked at similar questions but they deal with posting from a web app to other user's page which need a manual authorization on a confirmation page.
I am not finding where I grant myself this permission on Facebook. I might be missing a setting in the code too.
Any ideas?
private bool PostImage(string UserToken, string Status, string ImagePath)
{
try
{
FacebookClient fb = new FacebookClient(UserToken);
//for testing. id & name have values -----
dynamic me = fb.Get("me");
var id = me.id;
var name = me.name;
// ----------------------------------------
var imgstream = File.OpenRead(ImagePath);
dynamic response = fb.Post("/me/feed", new
{
message = Status,
file = new FacebookMediaStream
{
ContentType = "image/jpg",
FileName = Path.GetFileName(ImagePath)
}.SetValue(imgstream)
});
return true;
}
catch (Exception ex)
{
return false;
}
}
You are trying to post status on behalf of user means your application need to get permission from user using "publish_actions".
Refer : https://developers.facebook.com/docs/facebook-login/permissions/v2.5#reference-publish_actions
I'm trying to write a windows service that will post to my Facebook Page with results when it runs.
I just downloaded Facebook C# SDK v6.0.10.0 and writing the windows application in .Net 4.0
I created a facebook application account and got the AppID and Secret code needed.
The end goal would be to have this windows service post on my facebook page wall as the page and not the application user.
I keep getting an error when I go to get the accounts for my facebook application.
string strAppID = "my app api id";
string strSecret = "my app secret code";
Facebook.FacebookClient fbClient = new Facebook.FacebookClient();
fbClient.AppId = strAppID;
fbClient.AppSecret = strSecret;
dynamic ac = fbClient.Get("oauth/access_token", new
{
client_id = strAppID,
client_secret = strSecret,
grant_type = "client_credentials"
});
string strAccessToken = String.Empty;
strAccessToken = ac.access_token;
if (!String.IsNullOrEmpty(strAccessToken))
{
fbClient = new Facebook.FacebookClient(strAccessToken);
fbClient.AccessToken = strAccessToken;
fbClient.AppId = strAppID;
fbClient.AppSecret = strSecret;
//Here is where it is bombing
dynamic fbAccounts = fbClient.Get("/me/accounts");
fbClient = new Facebook.FacebookClient(strAccessToken);
fbClient.AccessToken = strAccessToken;
fbClient.AppId = strAppID;
fbClient.AppSecret = strSecret;
dynamic me = fbClient.Get("**Name of the facebook page I am trying to post to**");
string strPageID = String.Empty;
strPageID = me.id;
string strPageAccessToken = String.Empty;
//Loop over the accounts looking for the ID that matches your destination ID (Fan Page ID)
foreach (dynamic account in fbAccounts.data)
{
if (account.id == strPageID)
{
//When you find it, grab the associated access token and put it in the Dictionary to pass in the FB Post, then break out.
strPageAccessToken = account.access_token;
break;
}
}
try
{
fbClient.AccessToken = strPageAccessToken;
var args = new Dictionary<string, object>();
args["message"] = "Testing 123";
fbClient.Post("/" + strPageID + "/feed", args);
}
catch (Facebook.FacebookOAuthException ex)
{
// oauth exception occurred
}
catch (Facebook.FacebookApiLimitException ex)
{
// api limit exception occurred.
}
catch (Facebook.FacebookApiException ex)
{
// other general facebook api exception
}
catch (Exception ex)
{
// non-facebook exception such as no internet connection.
}
}
The error I am getting is on the line:
dynamic fbAccounts = fbClient.Get("/me/accounts");
(OAuthException - #2500) An active access token must be used to query information about the current user.
see here: (OAuthException - #2500) An active access token must be used to query information about the current user
you are getting access token for the APPLICATION, not for a user.
Therefore, "me" does not make sense. You should supply ID there -
either your user ID, or your app ID, or any other ID your app has
permissions for.
dynamic ac = fbClient.Get("oauth/access_token", new
{
client_id = strAppID,
client_secret = strSecret,
grant_type = "client_credentials"
});
The above code may not work for version 6.0.
OAuth 2.0 - exchange code for access token
FacebookClient supports parsing only json responses. Due to this
reason “oauth/access_token” token will not work when using
FacebookClient.Get(“oauth/access_token”). Instead you will need to use
a method in FacebookOAuthClient.
You can find more details here: http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx
Hope this helps.
I am having a problem retrieving the user's access token after he/she has authorized my Facebook application to access their information and post for them, etc... Facebook returns a code query string to my website, so I can receive the access token for the user. I use the following code to get the access code.
string AppKey = "[REMOVED]";
string AppSecret = "[REMOVED]";
var oAuth = new Facebook.FacebookOAuthClient();
oAuth.AppId = AppKey;
oAuth.AppSecret = AppSecret;
oAuth.RedirectUri = new Uri("http://www.mywebsite.com");
Label3.Text = Request.QueryString["code"];
try
{
var accessToken = oAuth.ExchangeCodeForAccessToken(Request.QueryString["code"]);
string accessTokenString = accessToken.ToString();
HttpCookie aCookie = new HttpCookie("MyWebsite_FBAccessToken");
aCookie.Value = accessTokenString;
Response.Cookies.Add(aCookie);
Response.Redirect("~/Process/ProcessToken.aspx");
}
catch (Facebook.FacebookOAuthException error)
{
Label2.Text = error.Message;
}
My code gets held up here:
var accessToken = oAuth.ExchangeCodeForAccessToken(Request.QueryString["code"]);
And I receive the following error.
(OAuthException) Error validating verification code.
Does this seem like there is a problem with my code, or does it look like there may be a setting problem with my Facebook application? I know my App ID and Secret are correct.
Hi i'm developing an application in facebook with c# sdk and i want that the user whom liked my page can only use my application. (Like woobox)
I found some solutions in php in this link but there isn't any source about .net how can i get the liked info in ASP.NET
I find another examples in php in this link again but i can't find c# answer :\
Thanks
You get signed request when your web page is loaded within facebook canvas app; you should be able to parse signed request something similar to following:
if (Request.Params["signed_request"] != null)
{
string payload = Request.Params["signed_request"].Split('.')[1];
var encoding = new UTF8Encoding();
var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
var json = encoding.GetString(base64JsonArray);
var o = JObject.Parse(json);
var lPid = Convert.ToString(o.SelectToken("page.id")).Replace("\"", "");
var lLiked = Convert.ToString(o.SelectToken("page.liked")).Replace("\"", "");
var lUserId= Convert.ToString(o.SelectToken("user_id")).Replace("\"", "");
}
You need to add reference to json libraries in order to parse signed requestin C#, download from http://json.codeplex.com/
Also refere to How to decode OAuth 2.0 for Canvas signed_request in C#? if you are worndering about signed request.
This is only possible with the legacy APIs, or with the user_likes permission. As you want a solution without specific permissions I'll show you 2 methods. Use them in combination with AJAX to refresh the page when a user presses like.
Option 1) REST API
Using the legacy API, it's possible to use Pages.IsFan
https://api.facebook.com/method/pages.isFan?
page_id=...&
uid=...&
access_token=...
Do this in C# as follows.
var appID = "....";
var appSecret = "....";
var uid = "....";
var pageId = "....";
WebClient client = new WebClient();
var appAuthUri = string.Concat("https://graph.facebook.com/oauth/access_token?",
"client_id=", appID,
"&client_secret=", appSecret,
"&grant_type=", "client_credentials"
);
var response = client.DownloadString(appAuthUri);
var access_token = response.Split('=')[1];
var isFanUri = string.Concat("https://api.facebook.com/method/pages.isFan?",
"format=", "json",
"&page_id=", pageId,
"&uid=", uid,
"&access_token=", access_token
);
response = client.DownloadString(isFanUri);
bool isFan;
bool.TryParse(response, out isFan);
Option 2) Client side
The FBXML method. This is done with Javascript on the client, by subscribing to an event when the user clicks the like button. It's documented here.
How do I know when a user clicks a Like button?
If you are using the XFBML version of the button, you can subscribe to
the 'edge.create' event through FB.Event.subscribe.
Generate an FBXML like button here.
<div id="fb-root"></div>
<script>(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js#appId=132240610207590&xfbml=1";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));</script>
<div class="fb-like" data-href="http://www.thecodeking.co.uk" data-send="true" data-width="450" data-show-faces="false"></div>
Then subscribe to the edge.create event using the Javascript SDK. Place this code in the document BODY preferably just before the end.
<script type="text/javascript">
<!--
window.fbAsyncInit = function () {
FB.init({ appId: '245693305442004', status: true, cookie: true, xfbml: true });
FB.Event.subscribe('edge.create',
function (href, widget) {
// Do something here
alert('User just liked '+href);
});
(function () {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
} ());
};
//-->
</script>
this.canvasAuthorizer = new CanvasAuthorizer {
Permissions = new[] { "user_about_me", "publish_stream", "offline_access", "user_likes", "friends_about_me" }
};
this.canvasAuthorizer.Authorize();
if (FacebookWebContext.Current.IsAuthorized())
{
this.facebookWebClient = new FacebookWebClient(FacebookWebContext.Current);
string requested_Data = HttpContext.Current.Request.Form["signed_request"];
dynamic decodedSignedRequest = FacebookSignedRequest.Parse(this.facebookApplication, requested_Data);
if (decodedSignedRequest.Data.page != null)
{
// Funs Page
this.IsLike = decodedSignedRequest.Data.page.liked;
}
else
{
// Application Page
dynamic likes = this.facebookWebClient.Get("/me/likes");
foreach (dynamic like in likes.data)
{
if (like.id == this.FacebookFanPageID)
{
this.IsLike = true;
}
}
}
}
If your app is a canvas app, you could (should?) use the signed_request parameter to check if the user likes the page it's on:
# pseudocode
signed_request = decode_signed_request()
if signed_request['page']['liked']:
# user liked page, do something cool
else:
# user doesn't like page. redirect somewhere to tell them why they should
The signed_request is passed to your page as a POST variable; just as if there was a form field named signed_request and the form was submitted on the page previous to yours (in fact this is basically how facebook "runs" your app; the form is auto-submitted instead of waiting for a user to submit it). So in ASP.net you should be able to get it through the Request object:
Request["signed_request"]
This approach is useful if you're creating a "tab app" for a page; you can detect whether the user liked the page without them granting you extra permissions.
This can be done in PHP with the help of an SQL Query
`$result = $facebook->api(array( "method" => "fql.query",
"query" => "SELECT uid FROM page_fan WHERE uid=$uid AND page_id=$page_id"
));
Here $result variable can be used for segregating the Fan and non-Fan content