I want to authenticate the users who visit my website using google's OAUTH2.0.
I have successfully got the authorization_code in response and now I am facing problem when I make a 'POST request' to Google when getting an access token. The problem is that the request is being continued over the time and I'm not getting any response.
Is there anything wrong in the code I have written below?
StringBuilder postData = new StringBuilder();
postData.Append("code=" + Request.QueryString["code"]);
postData.Append("&client_id=123029216828.apps.googleusercontent.com");
postData.Append("&client_secret=zd5dYB9MXO4C5vgBOYRC89K4");
postData.Append("&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=124545459218.apps.googleusercontent.com&client_secret={zfsgdYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string addons = "/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=123029216828.apps.googleusercontent.com&client_secret={zd5dYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code";
request.ContentLength = addons.Length;
Stream str = request.GetResponse().GetResponseStream();
StreamReader r = new StreamReader(str);
string a = r.ReadToEnd();
str.Close();
r.Close();
As I mentioned in my comment, you just have a few minor mistakes in your code. As it stands, you're not actually POST-ing anything. I'm assuming you intend to send the postData string.
The following should work:
//Build up your post string
StringBuilder postData = new StringBuilder();
postData.Append("code=" + Request.QueryString["code"]);
postData.Append("&client_id=123029216828.apps.googleusercontent.com");
postData.Append("&client_secret=zd5dYB9MXO4C5vgBOYRC89K4");
postData.Append("&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
//Create a POST WebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=124545459218.apps.googleusercontent.com&client_secret={zfsgdYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//Write your post string to the body of the POST WebRequest
var sw = new StreamWriter(request.GetRequestStream());
sw.Write(postData.ToString());
sw.Close();
//Get the response and read it
var response = request.GetResponse();
var raw_result_as_string = (new StreamReader(response.GetResponseStream())).ReadToEnd();
You were just missing the part where you attached the string to your POST WebRequest.
Related
I am a SQL Developer, JSON and C# are completely new to me. I am trying to get the JSON data from Rest API from elastic DB using POST method. I think my code is incorrect since I am getting all the response from the API even though I am passing string json variable in my c# code.
public static string COSMOS(string getAPiurl, string ApiUserId, string ApiPassword)
{
string url = getAPiurl;
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "POST";
webrequest.ContentType = "application/JSON";
webrequest.Accept = "application/JSON";
String username = ApiUserId;
String password = ApiPassword;
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
webrequest.Headers.Add("Authorization", "Basic " + encoded);
using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
{
string json = "{\"query\":{\"bool\":{\"should\":[{\"match\":{\"platform\":{\"query\":\"COSMOS\"}}}],\"filter\":" +
"[{\"range\":{\"cu_ticketLastUpdated_date\":{\"gte\":\"2022-05-01 00:00:00\",\"lt\":" +
"\"2022-05-31 23:59:59\"}}}]}}}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)webrequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var rl = streamReader.ReadToEnd();
httpResponse.Close();
}
I am using the above code in my SSIS script component. When I am trying to debug the above code in the var rl I am getting all the response even though I am passing the filters like "filter":[{"range":{"cu_ticketLastUpdated_date":{"gte":"2022-05-01 00:00:00","lt":"2022-05-31 23:59:59"}}
Please help me with an solution.
i am trying to send a POST request with body to WordPress API. I am still getting 401 error.
I decided to use: https://gist.github.com/DeskSupport/2951522 to authorize via OAuth 1.0 and it works perfectly with GET method. Then i wanted to implement another method which sends simple body.
That's my code:
var oauth = new OAuth.Manager();
oauth["consumer_key"] = _consumerKey;
oauth["consumer_secret"] = _consumerSecret;
oauth["token"] = _accessToken;
oauth["token_secret"] = _tokenSecret;
var appUrl = _baseUrl + url;
var authzHeader = oauth.GenerateAuthzHeader(appUrl, "POST");
string body = GenerateBody(parameters);
byte[] encodedData = Encoding.ASCII.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(appUrl);
request.Method = "POST";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.Headers.Add("Authorization", authzHeader);
request.ContentLength = encodedData.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream newStream = request.GetRequestStream();
newStream.Write(encodedData, 0, encodedData.Length);
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
}
}
The result of method GenerateBody is user_login=login&user_pass=BXE&04K44DoR1*a
I also tried to change the '&' character to '%26' but it didn't work.
This request works via Postman and i don;t know what's wrong.
OK, I found a solution.
https://blog.dantup.com/2016/07/simplest-csharp-code-to-post-a-tweet-using-oauth/
This guy wrote the way to make this request. What is also important you have to change a oauth_nonce for unique token.
After many struggles, I was finally able to get the OAuth Authentication/Refresh token process down. I am certain that the tokens I am using in this process are good. But I am struggling to communicate with the Compliance API and I think it may have more to do with my headers authentication process than it does specifically the Compliance API but I am not certain. I've tried so many different combinations of the below code unsuccessfully. I've tried to do the call as a GET and a POST (the call should be a GET). I've tried it with the access token encoded and not encoded. With all of my different code combinations tried I've been getting either an authorization error or a bad request error. You can see some of the various things I've tried from commented out code. Thank you for your help.
public static string Complaince_GetViolations(string clientId, string ruName, string clientSecret, string accessToken, ILog log)
{
var clientString = clientId + ":" + clientSecret;
//byte[] clientEncode = Encoding.UTF8.GetBytes(clientString);
//var credentials = "Basic " + System.Convert.ToBase64String(clientEncode);
byte[] clientEncode = Encoding.UTF8.GetBytes(accessToken);
var credentials = "Bearer " + System.Convert.ToBase64String(clientEncode);
var codeEncoded = System.Web.HttpUtility.UrlEncode(accessToken);
HttpWebRequest request = WebRequest.Create("https://api.ebay.com/sell/compliance/v1/listing_violation?compliance_type=PRODUCT_ADOPTION")
as HttpWebRequest;
request.Method = "GET";
// request.ContentType = "application/x-www-form-urlencoded";
//request.Headers.Add(HttpRequestHeader.Authorization, credentials);
//request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + codeEncoded);
request.Headers.Add(HttpRequestHeader.Authorization, credentials);
//request.Headers.Add("Authorization", "Bearer " + codeEncoded);
request.Headers.Add("X-EBAY-C-MARKETPLACE-ID", "EBAY-US");
log.Debug("starting request.GetRequestStream");
string result = "";
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream())) //FAILS HERE
{
result = streamReader.ReadToEnd();
}
//DO MORE STUFF BELOW
return "STUFF";
}
And I finally figured out a resolution to this problem. The HTML encoding of the entire bearer string was the issue. If anyone needs this in the future your welcome. =)
HttpWebRequest request = WebRequest.Create("https://api.ebay.com/sell/compliance/v1/listing_violation?compliance_type=PRODUCT_ADOPTION")
as HttpWebRequest;
request.Method = "GET";
request.Headers.Add(HttpRequestHeader.Authorization, System.Web.HttpUtility.HtmlEncode("Bearer " + accessToken));
request.Headers.Add("X-EBAY-C-MARKETPLACE-ID", "EBAY-US");
log.Debug("starting request.GetRequestStream");
string result = null;
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
I'm trying to scrape a website that requires a login. Getting an error that I haven't received before, copied the code from another forum successfully in the past:
Exception Details: System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
with the code:
Stream newStream = http.GetRequestStream(); //open connection
Here's the entire code:
#{
var strUserId = "userName";
var strPassword = "password";
var url = "formSubmitLandingSite";
var url2 = "pageToScrape";
HttpWebRequest http = WebRequest.Create(url) as HttpWebRequest;
http.KeepAlive = true;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
string postData = "email=" + strUserId + "&password=" + strPassword;
byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (Stream postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
HttpWebResponse httpResponse = http.GetResponse() as HttpWebResponse;
// Probably want to inspect the http.Headers here first
http = WebRequest.Create(url2) as HttpWebRequest;
http.CookieContainer = new CookieContainer();
http.CookieContainer.Add(httpResponse.Cookies);
HttpWebResponse httpResponse2 = http.GetResponse() as HttpWebResponse;
Stream newStream = http.GetRequestStream(); //open connection
newStream.Write(dataBytes, 0, dataBytes.Length); // Send the data.
newStream.Close();
string sourceCode;
HttpWebResponse getResponse = (HttpWebResponse)http.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
sourceCode = sr.ReadToEnd();
}
Response.Write(sourceCode);
}
You're creating a new request object here:
http = WebRequest.Create(url2) as HttpWebRequest;
Keep in mind that the default HTTP verb used is GET. Then you try to open the request stream here:
Stream newStream = http.GetRequestStream();
This method is used to enable writing data to the request's content. However, GET requests don't have content. As you do in the code above the error, you'll need to use a different HTTP verb. POST is most common for this, and is what you're using above:
http.Method = "POST";
So just use a POST request again. (Assuming, of course, that's what the server is expecting. In any event, if the server is expecting content then it's definitely not expecting a GET request.)
I am using C# (ASP.NET). I want to use Google OAuth for accessing the user profile detail in my app. I successfully got the authorization code but having a problem in getting the access token.
I prefer the Google tutorials. In tutorial, I read that I have to send the request and get the response from google. For that, I use System.Net.HttpWebRequest/HttpWebResponse (am I going in the right way). I have used this code...
byte[] buffer = Encoding.ASCII.GetBytes("?code=" + code + "&client_id=xxx&client_secret=xxx&redirect_uri=xxxx&grant_type=authorization_code");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://accounts.google.com");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = buffer.Length;
Stream strm = req.GetRequestStream();
strm.Write(buffer, 0, buffer.Length);
strm.Close();
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Response.Write(((HttpWebResponse)resp).StatusDescription);
But, I got the error:
The remote server returned an error: (405) Method Not Allowed.
Update: Here variable code is authorization code.
I think you are sending the POST request to the wrong endpoint, the correct one is https://accounts.google.com/o/oauth2/token
As I had similar problems in the process of implementing Google auth, I will post the code that works.. The last mentioned problem: error (400) Bad request could be caused by leading '?' in the above code..
string codeClient = "code="+ t +"&client_id=number.apps.googleusercontent.com&";
string secretUri = "client_secret=yoursecret&" + "redirect_uri=path&"
+ "grant_type=authorization_code";
postString = codeClient + secretUri;
string url = "https://accounts.google.com/o/oauth2/token";
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(postString);
Stream os = null;
try
{
request.ContentLength = bytes.Length;
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
}
catch
{ }
try
{
HttpWebResponse webResponse = (HttpWebResponse) request.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
result = responseStreamReader.ReadToEnd();//parse token from result
My code is working, I have done mistakes in above two lines. It should be like this
byte[] buffer = Encoding.ASCII.GetBytes("code=" + code + "&client_id=xxx&client_secret=xxx&redirect_uri=xxxx&grant_type=authorization_code");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
Remaining code is correct.
The original request seems to be somewhat outdated. But I found that the Google's code examples contain lots of "Best Practices" housekeeping code that's hard to separate from the essential operations.
I recently published a document that represents all the REST operations as curl commands. It's hard to be conversant in every language, but curl seems universal. Most people know it- otherwise, it's pretty easy to grasp. In my curl examples, the -d flag indicates a POST operation. Otherwise, the parameters are appended to the URL.
http://www.tqis.com/eloquency/googlecalendar.htm
public string ReceiveTokenGmail(string code, string GoogleWebAppClientID, string GoogleWebAppClientSecret, string RedirectUrl)
{
string postString = "code=" + code + "&client_id=" + GoogleWebAppClientID + #"&client_secret=" + GoogleWebAppClientSecret + "&redirect_uri=" + RedirectUrl;
string url = "https://accounts.google.com/o/oauth2/token";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(postString);
Stream os = null;
try
{
request.ContentLength = bytes.Length;
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
}
catch
{ }
string result = "";
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
result = responseStreamReader.ReadToEnd();
return result;
}
It was surprisingly difficult to find the correct and simple way of getting access token by auth code. (Especially because it has taken some time for me and then even with the correct code I got “invalid_grant” error because my auth code expired while searching :) )
So here is the code:
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets()
{
// Use ones from "Web SDK configuration" section if you created your app in Firebase.
ClientId = "…",
ClientSecret = "…"
},
Scopes = new[] { "email" },
}
);
TokenResponse token = await flow.ExchangeCodeForTokenAsync(string.Empty, "4/…", string.Empty, CancellationToken.None);
As you can see, userId can be just empty, as well as redirectUri.
Don’t forget to add the Google.Apis.Auth Nuget package reference.