Android C2DM getting (401) Unauthorized - asp.net

I have an Android application with an ASP.NET backend. I have the registration_id for the phone as well as an auth token from google for the application server that is performing a push.
When I make the http post request to C2DM so that the phone gets a message I keep getting the 401 Unauthorized. Here is how I'm making the request in .NET:
WebRequest myRequest = WebRequest.Create("https://android.apis.google.com/c2dm/send");
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.Method = "POST";
myRequest.Headers.Add("Authorization", "GoogleLogin auth=" + authId);
// buiold the post string
StringBuilder myPost = new StringBuilder();
myPost.AppendFormat("registration_id={0}", regId);
myPost.AppendFormat("&data.payload={0}", msg);
myPost.AppendFormat("&collapse_key={0}", colKey);
// write the post-string as a byte array
byte[] myData = ASCIIEncoding.ASCII.GetBytes(myPost.ToString());
myRequest.ContentLength = myData.Length;
Stream myStream = myRequest.GetRequestStream();
myStream.Write(myData, 0, myData.Length);
myStream.Close();
// Do the actual request and read the response stream
WebResponse myResponse = myRequest.GetResponse();
Stream myResponseStream = myResponse.GetResponseStream();
StreamReader myResponseReader = new StreamReader(myResponseStream);
string strResponse = myResponseReader.ReadToEnd();
myResponseReader.Close();
myResponseStream.Close();
Any help would be much appreciated.

Advice corner: Have some confidence in your code every once and a while! And, even Google messes up sometimes.
After spending about nine hours reading every blog post and article about Google OAuth and C2DM and trying different things in my code, I emailed Google. I'm excited to say that not only did I receive a response very quickly, but also that my account was messed up. Something went wrong while I was registering on their site and although it appeared that everything was working from the registration success email I received, it wasn't. I re-registered and everything works!

I have encountered a similar problem: error 401 "Unauthorized" while trying a google c2dm (cloud to device messaging) code sample. It looks like the example used to work as is, but now Google has changed its conditions. Before running code examples, you have to sign-up:
http://code.google.com/android/c2dm/signup.html
I signed up, and the stuff began to work in minutes.

I've got the same problem, i.e. suddenly my C2DM_ACCOUNT_EMAIL stopped working.
To solve the problem, just fill the registration again with same info and the same C2DM_ACCOUNT_EMAIL.
HTH

Related

REST API Getting 401 UnAuthorized

I am using .NET Core Web API to make call and getting back
401, unauthorized ? I am using a REST API key.
var ApiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var _Http = new HttpClient();
var response = await _Http.GetAsync($"https://geocode.search.hereapi.com/v1/geocode?q={address},{city},{state},{postalCode},{country}&apikey={ApiKey}");
What am I missing ?
I am getting the key from the following section
UPDATE: this problem has vanished today. It appears to have been a bug on the Here side.
Yesterday: My JS API code, which has been working fine, is throwing 401s today as well, with no changes. I could kill the project and create a new one with a new API key, but I'm not sure that would fix it. I did find that it was "disabled" (due to a billing issue, I think), and I "enabled" it and it still throws 404s.
Did you confirm your email address (by clicking the link in the email they send)?
If you have not confirmed your email address, then the API Key is only valid for 30 minutes.

Microsoft Face API stopped working when sending binary data

Last time we tested our application was on Tuesday, it was working well.
Today morning a long wait and timeout received from Microsoft when sending DETECT request with binary data in body. Nothing has changed between in our application.
I tested and my keys are okay (when they are not, we receive an answer but not 200, not a timeout).
When I try to DETECT using an URL, it is working (proper content-type and body of course)
Did anyone noticed the same, or using the API differently?
HttpClient client = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("https://westeurope.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceLandmarks=false&returnFaceId=true");
request.addHeader("Ocp-Apim-Subscription-Key", MY_KEY);
request.addHeader("Content-Type", "application/octet-stream");
HttpEntity entity = new ByteArrayEntity(Base64.getDecoder().decode(base64));
request.setEntity(entity);
response = client.execute(request);
It seems it was not a problem at out side. Suddenly it started to work...Hopefully will stay this way.

Response Code From Google comes in wrong format upon on first sign in using Oauth 2.0 Authentication

Response Code received after signing on to google for first time.
[http://localhost:8080/?state=trueprompt%3Dconsent&code=4%2FjlCxJC7rg57nOG7w-0MP4M1BuQ7cbI4GLCNofMzPeQQ#][1]
Below given is the code i am using
GoogleConnectionFactory connectionFactory = new GoogleConnectionFactory("CLIENT_ID","CLIENT_SECRET");
System.out.println(connectionFactory.getScope());
connectionFactory.generateState();
OAuth2Operations oauthoperations =connectionFactory.getOAuthOperations();
OAuth2Parameters params = new OAuth2Parameters();
params.setRedirectUri("http://localhost:8080");
params.setScope("https://www.googleapis.com/auth/userinfo.profile");
params.setState("true");
String authorizeUrl = oauthoperations.buildAuthenticateUrl(GrantType.AUTHORIZATION_CODE,params);
After receving the authorizeUrl i am pasting that directly on to the browser, then it takes me to google signin page. After signing in it redirects back to call-back url with the code parameter value, which is mentioned at the very first link.
But that response code is not working for getting the Access Token. when i again copy paste the same login url on to brwoser it responds with a different response code which is mentioned below. This time as i am already logged i don't have to login in again and it responds with a different responds code which is working fine and i am able to get the AccessToken. The difference between first and second response code is that in first it responds with 4% where as in second it comes with 4/.
http://localhost:8080/?state=true&code=4/0Y9NMh9fYAr3kfy3r1por3Py1LCdbOsIUz3fwdv78gc#
AccessGrant accessGrant = oauthoperations.exchangeForAccess("AUTHORIZATION_CODE", "http://localhost:8080",null );
Connection<Google> connection = connectionFactory.createConnection(accessGrant);
System.out.println(connection.getDisplayName());
Please help me to resolve this issue.

Asp.net and OAuth simple example without existing Library

I try to get a request token from Twitter OAuth and I always received a server error 401 when I try to get the response. I don't want to used an existing library because I try to learn Oauth and maybe build my own library. This is my simple code :
WebRequest request = WebRequest.Create("https://api.twitter.com/oauth/request_token");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
StringBuilder sbParams = new StringBuilder();
sbParams.Append("OAuth ");
sbParams.AppendFormat("oauth_consumer_key={0},", "[COMSUMERKEY]");
sbParams.AppendFormat("oauth_signature_method={0},", "PLAINTEXT");
sbParams.AppendFormat("oauth_signature={0},", HttpUtility.UrlEncode("[COMSUMER_SECRET]&"));
sbParams.AppendFormat("oauth_timestamp={0},", ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds).ToString());
sbParams.AppendFormat("oauth_nonce={0},", "asdfalkjpoijwpeonpoaisudfnpowieuyfpasosdfdn");
sbParams.AppendFormat("oauth_version={0},", "1.0");
sbParams.AppendFormat("oauth_callback={0}", HttpUtility.UrlEncode(Request.Url.ToString()));
request.Headers.Add("Authorization", sbParams.ToString());
// Get the response.
WebResponse response = request.GetResponse();
From http://oauth.net/core/1.0a/#http_codes You know these
HTTP 401 Unauthorized
Invalid Consumer Key
Invalid / expired Token
Invalid signature
Invalid / **used nonce
The "used nonce" thing may be a problem. You need to generate a random string. From http://oauth.net/core/1.0a/#nonce
A nonce is a random string, uniquely generated for each request
Onto the serious business. You are not supposed to transmit your consumer secret, once you ever received it! Many OAuth libraries have a
request_request_token(consumer_key,consumer_secret)
Despite appearances, the consumer_secret is never transmitted. It is used at client-side, for verification of server's response. (A similar verification occurs at server-side too)
And you dont put in any static values for signing requests. From http://oauth.net/core/1.0a/#signing_process
All Token requests and Protected Resources requests MUST be signed by the Consumer and verified by the Service Provider.
Bottomline: do read the http://oauth.net/core/1.0a/ article to see how the protocol works. And choose a hands-on OAuth library that doesnt abstract too much details (The oauth-php library I used came with SQL tables and managed data stores and session memory by itself).

http post with blackberry

I am trying to set up an http post in my Blackberry app. I have successfully implemented this in my corresponding Android app, so I know the server it working find. I have tried several different things, and I'm not really getting errors, its just the info on the server is not getting updated. I have looked at this post:
Http POST in BlackBerry, and several others. I found them helpful, but they didn't ultimately solve my problem. Again, I don't get errors, but the server doesn't get updated. Here is the code I am currently using:
String url = "http://xxxx.com/ratings/add?;deviceside=true";
String postStr1 = "business_id=790";
String postStr2 = "&rating=4";
HttpConnection httpConnection = (HttpConnection) Connector.open(url);
httpConnection.setRequestMethod(HttpConnection.POST);
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
URLEncodedPostData encPostData = new URLEncodedPostData("UTF-8", false);
encPostData.append("business_id", String.valueOf(790));
encPostData.append("rating", String.valueOf(4));
byte[] postData = encPostData.toString().getBytes("UTF-8");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postData.length));
OutputStream os = httpConnection.openOutputStream();
os.write(postData);
os.flush();
Anyone have any ideas on what could be wrong?
A few things were going on. First, my simulator was not connecting to the internet properly. Once that got straightened out, I removed the
deviceside=true
from my url, and it now works great. Thanks all!

Resources