Bing translator HTTP API throws bad request error, how to solve this? - bing-api

Whenever I call Bing Translation API [HTTP] to translate some text, first time it works fine, and second time onwards it gives me 'bad request' [status code 400] error. If I wait for 10 or so minutes and then try again, then first request is successful, but second one onwards same story. I have a free account [2million chars translation] with Bing Translation APIs, are there any other limitations calling this API?
Thanks, Madhu
Answer:
hi, i missed to subscribing to Microsoft Translator DATA set subscription. Once i get the same, then things have solved. i.e; once i have signed up for https://datamarket.azure.com/dataset/bing/microsofttranslator then things are working.
i was generating the access_token correctly, so that is not an issue.
thanks, madhu

i missed to subscribing to Microsoft Translator DATA set subscription. Once i get the same, then things have solved. i.e; once i have signed up for https://datamarket.azure.com/dataset/bing/microsofttranslator then things are working.
i was
thanks, madhu

As a note to anyone else having problems, I figured out that the service only allows the token to be used once when using the free subscription. You have to have a paid subscription to call the Translate service more than once with each token. This limitation is, of course, undocumented.
I don't know if you can simply keep getting new tokens -- I suspect not.
And regardless of subscription, the tokens do expire every 10 minutes, so ensure you track when you receive a token and get a new one if needed, e.g. (not thread-safe):
private string _headerValue;
private DateTime _headerValueCreated = DateTime.MinValue;
public string headerValue {
get {
if(_headerValueCreated < DateTime.Now.AddMinutes(-9)) {
var admAuth = new AdmAuthentication("myclientid", "mysecret");
_headerValue = "Bearer " + admAuth.GetAccessToken();
_headerValueCreated = DateTime.Now;
}
return _headerValue;
}
}

Related

Find a discord user just by username (no tag)

like title states I wanna find an old friend of mine, but the only thing I know it's his username, no tag number..
No mutual servers or anything unfortunally, and the discord search feature didn't helped.
So my idea was to send a friend request to all 9999 possible tags with that username.
But doing it manually, well it would take so long, I could try setup a macro, but I would like to know if there's a way I could make a program or discord bot using discord apis to accomplish this faster.
I would just need check the pending friends list in the end and should be done.
Weird nobody did yet such a thing, lots of people would benefit with such a software or whatever it could be.
What this code does is create range from 0 to 9999 and sends friend request to all usernames within range.
import requests
headers = {
'Authorization': 'YOUR_TOKEN_HERE',
}
data = {
'username': 'YOUR_FRIEND_USERNAME',
'discriminator': 0,
}
var link = 'https://discord.com/api/v9/users/#me/relationships'
for i in range(10000):
data[discriminator] = i
r = requests.post(link, headers=headers, json=data).text
print(str(i) + ":" + str(r))
But remember there's legal advice:
Self bots are illegal in Discord's terms of service.
You are not allowed to send such no. of friend requests. Off course Discord will restrict/expire/ban your token.

Google Service Account "Invalid JWT Signature"

I am attempting to write some code in webDNA to connect to the google drive api. Using the service account seems to be the best solution for the given problem. From what I have read the process is... create the JWT, send the JWT to google to get a token response, then send the taken response to call api methods.I believe my issue is with the private key.
I build and encrypt the header:
[text]header={"alg":"RS256","typ":"JWT"}[/text]
[text]header=[encrypt method=Base64][header][/encrypt][/text]
[text]header=[db_base64URL varName=header][/text][!]custom function to deal with special characters[/!]
Next build and encrypt the claim(added white space for readability):
[text]claim={
"iss":"xxx",
"scope":"https://www.googleapis.com/auth/drive",
"aud":"https://www.googleapis.com/oauth2/v4/token",
"exp":[Math][cTime]+3600[/Math],
"iat":[cTime]
}[/text]
[text]claim=[encrypt method=Base64][claim][/encrypt][/text]
[text]claim=[db_base64URL varName=claim][/text]
Those sections seem to be correct, now to build the signature:
[text]p_key=-----BEGIN PRIVATE KEY-----xxxx-----END PRIVATE KEY-----\n[/text]
[text]sig=[encrypt method=SHA256][header].[claim].[p_key][/encrypt][/text]
[text]sig=[encrypt method=Base64][sig][/encrypt][/text]
[text]sig=[db_base64URL varName=sig][/text]
I have tried moving the [p_key] around, outside the sha256 encryption and inside, with and without the '.', I don't get an error till I try to send it to google using [TCPConnect] and [TCPSend] here:
[text show=T]response=[!]
[/!][TCPconnect host=accounts.google.com&SSL=T&port=443][!]
[/!][TCPsend skipheader=T]POST /o/oauth2/token HTTP/1.1[crlf][!]
[/!]Host: accounts.google.com[crlf][!]
[/!]Content-Type: application/x-www-form-urlencoded[crlf][!]
[/!]Content-Length: [countchars][sendData][/countChars][crlf][!]
[/!]Connection: close[crlf][!]
[/!][crlf][!]
[/!][sendData][crlf][!]
[/!][/TCPsend][!]
[/!][/TCPconnect][/text]
When the response is shown it is displayed as:
{
"error": "invalid_grant",
"error_description": "Invalid JWT Signature."
}
This error message is less that helpful, from what I have read it could mean one(or more) of any number of things and google's documentation on this is not exactly helpful. If anyone has any experience using the google apis through webDNA I would appreciate any help you could give!

could not send the SMS message via Tropo

We are using the TropoSharp to send SMS message to my phone. The weird part is that I didn't get any SMS message, rather I get a phone call and it is very short and I could not figure out what the person is talking over the phone.
By looking at the code, we could not figure out what's wrong:
string voiceToken = "xxx";
string messagingToken = "xxx";
IDictionary<string, string> parameters = new Dictionary<String, String>();
parameters.Add("sendToNumber", "xxx");
parameters.Add("sendFromNumber", "+1 201-xxx-04xx");
string channel = Channel.Text;
parameters.Add("channel", channel);
string network = Network.SMS;
parameters.Add("network", network);
parameters.Add("msg", HttpUtility.UrlEncode("This is a test message from C#."));
Tropo tropo = new Tropo();
XmlDocument doc = new XmlDocument();
string token = channel == Channel.Text ? messagingToken : voiceToken;
doc.Load(tropo.CreateSession(token, parameters));
Console.WriteLine("Result: " + doc.SelectSingleNode("session/success").InnerText.ToUpper());
Console.WriteLine("Token: " + doc.SelectSingleNode("session/token").InnerText);
Console.ReadKey();
Here is the http request (removed some sensitive information)
GET http://api.tropo.com/1.0/sessions?action=create&token=xxxxx&sendToNumber=xxx&sendFromNumber=+1%20201-xxx-xxxx&channel=TEXT&network=SMS&msg=This+is+a+test+message+from+C%23.& HTTP/1.1
Host: api.tropo.com
Connection: Keep-Alive
here is the response (I guess it only means that request is submitted successful):
<session><success>true</success><token>xxxx</token><id>5c994e73ab85ff47fd1af4ffd4002e00
Any idea where we did wrong here? Thanks
You're using the scripting approach, not WebAPI, right? Can you post the script that your application is using? It's my understanding that when you create a session, you're just passing variables up to your script. Your script might be completely ignoring those variables, and just making a voice call.
I agree about your last point. That response just tells you that it succeeded in creating the session. It doesn't return any additional information about other steps of the process.
There are two tokens for your application, one for voice and one for messaging. Are you using the one for messaging? Also, outbound messaging is not turned on be default for your application. You have to contact Tropo support to turn it on for development. They may require you to put some money in your account to do this, but they will not charge you unless you start abusing this feature during development.

Google Spreadsheet API - returns remote 500 error

Has anyone battled 500 errors with the Google spreadsheet API for google domains?
I have copied the code in this post (2-legged OAuth): http://code.google.com/p/google-gdata/source/browse/trunk/clients/cs/samples/OAuth/Program.cs, substituted in my domain;s API id and secret and my own credentials, and it works.
So it appears my domain setup is fine (at least for the contacts/calendar apis).
However swapping the code out for a new Spreadsheet service / query instead, it reverts to type: remote server returned an internal server error (500).
var ssq = new SpreadsheetQuery();
ssq.Uri = new OAuthUri("https://spreadsheets.google.com/feeds/spreadsheets/private/full", "me", "mydomain.com");
ssq.OAuthRequestorId = "me#mydomain.com"; // can do this instead of using OAuthUri for queries
var feed = ssservice.Query(ssq); //boom 500
Console.WriteLine("ss:" + feed.Entries.Count);
I are befuddled
I had to make sure to use the "correct" class:
not
//using SpreadsheetQuery = Google.GData.Spreadsheets.SpreadsheetQuery;
but
using SpreadsheetQuery = Google.GData.Documents.SpreadsheetQuery;
stinky-malinky
Seems you need the gdocs api to query for spreadsheets, but the spreadsheet api to query inside of a spreadsheet but nowhere on the internet until now will you find this undeniably important tit-bit. Google sucks hard on that one.

Simple Claims Transformation for an RP-STS in Geneva Framework

After reading the MSDN article (http://msdn.microsoft.com/en-us/magazine/2009.01.genevests.aspx) on implementing a Custom STS using the Microsoft Geneva Framework I am a bit puzzled about one of the scenarios covered there. This scenario is shown in figure 13 of the above referenced article.
My questions are around how does the RP initiate the call to the RP-STS in order to pass on the already obtained claims from the IP-STS? How does the desired method DeleteOrder() get turned into a Claim Request for the Action claim from the RP-STS which responds with the Action claim with a value Delete which authorizes the call? I also think the figure is slightly incorrect in that the interaction between the RP-STS and the Policy Engine should have the Claims and arrows the other way around.
I can see the structure but it's not clear what is provided by Geneva/WCF and what has to be done in code inside the RP, which would seem a bit odd since we could not protect the DeleteOrder method with a PrincipalPermission demand for the Delete "permission" but would have to demand a Role first then obtain the fine-grained claim of the Delete Action after that point.
If I have missed the point (since I cannot find this case covered easily on the Web), then apologies!
Thanks in advance.
I asked the same question on the Geneva Forum at
http://social.msdn.microsoft.com/Forums/en/Geneva/thread/d10c556c-1ec5-409d-8c25-bee2933e85ea?prof=required
and got this reply:
Hi Dokie,
I wondered this same thing when I read that article. As I've pondered how such a scenario would be implemented, I've come up w/ two ideas:
The RP is actually configured to require claims from the RP-STS; the RP-STS requires a security token from the IP-STS. As a result, when the subject requests a resource of the RP, it bounces him to the RP-STS who bounces him to the IP-STS. After authenticating there, he is bounced back to the RP-STS, the identity-centric claims are transformed into those necessary to make an authorization decision and returned to the RP.
The RP is configured to have an interceptor (e.g., an AuthorizationPolicy if it's a WCF service) that grabs the call, sees the identity-centric claims, creates an RST (using the WSTrustClient), passes it to the RP-STS, that service expands the claims into new one that are returned to the RP, and the RP makes an authorization decision.
I've never implemented this, but, if I were going to, I would explore those two ideas further.
HTH!
Regards,
Travis Spencer
So I will try option 2 first and see if that works out then formulate an answer here.
I've got situation one working fine.
In my case AD FS is the Identity Service and a custom STS the Resource STS.
All webapp's use the same Resource STS, but after a user visits an other application the Identity releated claims are not addad again by the AD FS since the user is already authenticated. How can I force or request the basic claims from the AD FS again?
I've created a call to the AD FS with ActAs, now it returns my identification claims.
Remember to enable a Delegation allowed rule for the credentials used to call the AD FS.
string stsEndpoint = "https://<ADFS>/adfs/services/trust/2005/usernamemixed";
var trustChannelFactory = new WSTrustChannelFactory(new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), stsEndpoint);
trustChannelFactory.Credentials.UserName.UserName = #"DELEGATE";
trustChannelFactory.Credentials.UserName.Password = #"PASSWORD";
trustChannelFactory.TrustVersion = TrustVersion.WSTrustFeb2005;
//// Prepare the RST.
//var trustChannelFactory = new WSTrustChannelFactory(tokenParameters.IssuerBinding, tokenParameters.IssuerAddress);
var trustChannel = (WSTrustChannel)trustChannelFactory.CreateChannel();
var rst = new RequestSecurityToken(RequestTypes.Issue);
rst.AppliesTo = new EndpointAddress(#"https:<RPADDRESS>");
// If you're doing delegation, set the ActAs value.
var principal = Thread.CurrentPrincipal as IClaimsPrincipal;
var bootstrapToken = principal.Identities[0].BootstrapToken;
// The bootstraptoken is the token received from the AD FS after succesfull authentication, this can be reused to call the AD FS the the users credentials
if (bootstrapToken == null)
{
throw new Exception("Bootstraptoken is empty, make sure SaveBootstrapTokens = true at the RP");
}
rst.ActAs = new SecurityTokenElement(bootstrapToken);
// Beware, this mode make's sure that there is no certficiate needed for the RP -> AD FS communication
rst.KeyType = KeyTypes.Bearer;
// Disable the need for AD FS to crypt the data to R-STS
Scope.SymmetricKeyEncryptionRequired = false;
// Here's where you can look up claims requirements dynamically.
rst.Claims.Add(new RequestClaim(ClaimTypes.Name));
rst.Claims.Add(new RequestClaim(ClaimTypes.PrimarySid));
// Get the token and attach it to the channel before making a request.
RequestSecurityTokenResponse rstr = null;
var issuedToken = trustChannel.Issue(rst, out rstr);
var claims = GetClaimsFromToken((GenericXmlSecurityToken)issuedToken);
private static ClaimCollection GetClaimsFromToken(GenericXmlSecurityToken genericToken)
{
var handlers = FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers;
var token = handlers.ReadToken(new XmlTextReader(new StringReader(genericToken.TokenXml.OuterXml)));
return handlers.ValidateToken(token).First().Claims;
}

Resources