google oauth access token 411 response - c#

I'm working with google's OAuth api for web server applications, specifically asp.net mvc, and i'm able to get to the point where google returns an authorization code for a certain oauth request. At that point, I'm trying to obtain the access token using the following code:
public ActionResult GetOAuthToken()
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(OAuthConfig.getTokenUrl(Request.QueryString["code"].ToString()));
myReq.Method = "POST";
myReq.Host = "accounts.google.com";
myReq.ContentType = "application/x-www-form-urlencoded";
WebResponse resp = myReq.GetResponse();
return View();
}
The OAuthConfig is just a class I wrote that contains a method getTokenUrl(), which returns a url with parameters such as code, client_secret, client_id etc. for the url: https://accounts.google.com/o/oauth2/token. I've debugged and checked that there's nothing wrong with this url.
I keep getting the following error: The remote server returned an error: (411) Length Required.
I don't know what to specify for the content length, or if there's something else that i need to include to fix this error?

Have you tried to have a look at Google-API .NET Client?
If you debug you will see Google uses "length" as an internal property when sending access-token request. you can try to fix it on your own, but you can use THEIR class in order to send the token request; If you use their class you do not have to worry about internal such as length...

Related

Getting 400 bad request message while requesting for access token from DocuSign API

I am able generate access token with docusign site by using link https://developers.docusign.com/oauth-token-generator
But when try to get access token in our system using c# code then getting message (The remote server returned an error: (400) Bad Request.)
I follow the authenticate process mentioned in below link.
https://developers.docusign.com/esign-rest-api/guides/authentication/oauth2-code-grant
I able to get authentication code. I used this authentication code to hit API (https://account-d.docusign.com/oauth/token).
Below is my code sample
string integrationKey = "key removed";
string secretKey = "key removed";
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://account-d.docusign.com/oauth/token");
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
string apiStoreConsumer = "removed";
httpWebRequest.Headers.Add("Authorization", "Basic " + apiStoreConsumer);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string input = "authorization_code&authorization_code= <authentication code goes here>;
streamWriter.Write(input);
streamWriter.Flush();
streamWriter.Close();
}
WebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
Query:
Why am I getting 400 error?
Do we have any expiry time for access token, if yes then how long?
Does authentication code get change for every request?
Please help me on this.
Thank You!
I recommend you use a library for OAuth in .NET/C#.
If you want to see how this is done, please clone this repo.
The issue is that you need to first get a code and then exchange it for a token. There are 2 steps involved if you do this manually.
The first step requires you to authenticate the user in a browser before you can call any API.
During that step you need to pass in your integration key and redirect back to your URL.
Once redirected back you'll receive a code that can be exchanged for an access token using the API call you had talks about.

Using one legged OAuth1 in C#, gets error: (401) Unauthorized

I am using an one legged OAuth1 web service! which means I don't need to get a token to get my result just consumer key and secret is enough.I have used many different APIs and got the same result every time,I don't get what I'm doing wrong!
here is the latest API I've used:
https://github.com/rhargreaves/oauth-dotnetcore
the OAuth classes are pretty much straight forward,I've used those and made my request this way:
OAuthRequest client = OAuthRequest.ForRequestToken("key", "secret");
client.RequestUrl = "http://some site/?q=api/sbu_rest/user_books_returned/username";
// For HTTP header authorization
string auth = client.GetAuthorizationHeader();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(client.RequestUrl);
request.Headers.Add("Authorization", auth);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
but I get the error:
The remote server returned an error: (401) Unauthorized.
It's worth to mention that I have checked my URL ,key and secret in postman and they work fine(I'll get the result I want which is a list of books!)
PS: the signature method is HMAC-SHA1

How to call Google API from .NET/C# Web Application

I am struggling to call APIs hosted in Google Cloud https://apis-explorer.appspot.com/apis-explorer/?base=https%3A%2F%2Finnovative-glass.appspot.com%2F_ah%2Fapi#p/mirror/v1/
Up to my understanding, APIs are exposed as REST service. I need to make rest service call from .net application.
I have done OAuth Authentication. I am passing access_token as per the guidance given https://developers.google.com/accounts/docs/OAuth2WebServer
My Code:
UriBuilder uriBuilder = new UriBuilder("https://innovative-glass.appspot.com/_ah/api/mirror/v1/timeline");
string userId = Session["userId"] as string;
var state = Utils.GetStoredCredentials(userId);
NameValueCollection queryParameters = HttpUtility.ParseQueryString(uriBuilder.Query);
queryParameters.Set("access_token", state.AccessToken);
uriBuilder.Query = queryParameters.ToString();
var request = (HttpWebRequest)WebRequest.Create(uriBuilder.ToString());
request.Method = "GET";
var response = (HttpWebResponse)request.GetResponse();
I am getting UnAuthorized exception.
Is my understanding is right? Am I doing right way?
It seems that cloud endpoints don't use the Google API default of accepting access_token as query parameter. According to the Discovery document the equivalent query parameter is oauth_token so it should work with:
queryParameters.Set("oauth_token", state.AccessToken);
Alternatively (which in my opinion is the better solution) you can also set the Authorization header of the request instead of adding the token as query parameter:
request.Headers.Add("Authorization", "Bearer " + state.AccessToken);
Where are you getting the AccessToken from, and are you sure it is still a valid token? Remember that access tokens expire about an hour after being generated, although can be revoked earlier.
Clicking on the sign-in button at innovative-glass.appspot.com gives me an origin mismatch error, so it looks like you may also have a configuration issue.
Have you been able to get it to work using just the API Explorer?

REST API: Combine login information and API action using C#?

I am trying to use name.com API in C#. The API has different actions including /Login, /account/get, /create/domain and more. You can find the documentation here
The /Login method is POST and the body is a JSON, and done it with HttpWebRequest and it works successfully. It returns something like:
{
"result": {
"code":100,
"message":"Command Successful"
},
"session_token":"a59a09be6562e977a166fdd2b345a235c8b6c724"
}
But after login, I need to use the other services (run the other API actions).
Here I am sending another HttpWebRequest as:
string base = "https://api.dev.name.com/api/"
HttpWebRequest request;
request = WebRequest.Create(base + "account/get") as HttpWebRequest;
....
....
Instead of returning the account information, it returns an error which says:
{
"result":
{
"code":251,
"message":"Authentication Error - No Api Session Or Username Token Supplied"
}
}
I think that I need a way to send the request along with the login information. The err message here is "Authentication Error - No Api Session Or Username Token Supplied"
NOTE: There is PHP sample code and classes for this API. Here is the link of the API Documentation
See page 18 of the documentation. You need to pass the returned session token as a request header:
Api-Session-Token: <session_token>
So, once you get the response and get the token, you would just add the following line:
httpWebRequest.Headers.Add("Api-Session-Token", <session_token>);

Google+ API plus.me

The question: How to use people.get with the "me" parameter?
I know how to get the json object when using https://www.googleapis.com/plus/v1/people/{id}?key={key}
but what parameters should I include when Im using "me" as id?
(I use response_type=code in the auth)
Edit: (fixed)
I am using ASP.NET, and I found this link, but the POST request for the access token json throws an error. Sending the request works but, but when I use GetResponse(), I get error(400). And also Im not sure if the uri that I use is correct: https://accounts.google.com/o/oauth2/token
Edit 2:
Problem solved. The request was bad because I used UTF32Encoding instead of UTF8Encoding when converting the parameter string to byte[] before writing to Stream. With UTF8Encoding works good. :)
Code that I wrote after this question:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(parameters);
Stream os = null;
try // send the post
{
webRequest.ContentLength = bytes.Length; // Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); // Send it
}
// error handling...
try // get the response
{
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse == null)
{ return null; }
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
// error handling...
he called this with the parameters from here, and the returned string(json) contains my access_token.
We have developed a .NET client library for Google+ APIs. This library makes it very easy to use Google+ APIs from any .NET programming languages like C#, VB.NET or ASP.NET
You can find more details about the .NET library for Google+ here: http://www.googleplustips.com/resources/3332-NET-Library-Google-APIs-released.aspx
The current version supports all Google+ APIs version 1, and works with API Key. Calling any Google APIs require only a single method call.
You can use me ID as long as you access the app with the access token of an (OAuth) authenticated user. To quote from the G+ API documentation:
If using the userId value "me", this method requires authentication using a token that has been granted the OAuth scope https://www.googleapis.com/auth/plus.me. Read more about using OAuth.
Example: when using the PHP API client, before issuing e.g.
$plus_api = new apiPlusService($client); // $client is the apiClient() object
$plus_api->activities->listActivities('me', ...);
you have to set the access token of the authenticated user first by executing:
$client->setAccessToken($access_token);
With that set, the me ID will be recognized without a problem.
I sent a POST request (info here) to get the Oauth2 access_token and used:
https://www.googleapis.com/plus/v1/people/me?key={key}&access_token={token}
GetActivity and ListComments are getting all the data, or it has some method(using nextPageToken) to get all the items?
Each method call returns the resultset page by page. The returned object has a property called NextPageToken which can be passed with the next call to retrieve the next page of the result set.

Categories

Resources