HttpWebResponse 401-error Unauthorized - c#

I'm currently having issues with a HttpWebRequest/Response when I'm trying to make calls to an API.
The API use JSON/Ajax to make calls, but I need to make the calls through HttpWebRequest/Response which I don't fully understand and I think I'm passing the wrong access token.
Here's my current code, which I got from a tutorial:
byte[] buffer = Encoding.ASCII.GetBytes("username=User&password=Password");
HttpWebRequest WebReq =(HttpWebRequest)WebRequest.Create("http://api40.maildirect.se/User/Authorize");
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
Stream PostData = WebReq.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
var status = WebResp.StatusCode; (returns OK)
Stream _Answer = WebResp.GetResponseStream();
StreamReader Answer = new StreamReader(_Answer);
//Here I try to make another request, do I need to make another instance?
WebReq = (HttpWebRequest)WebRequest.Create("http://api40.maildirect.se/Contacts?&select=ContactId,FirstName,LastName");
WebReq.Method = "GET";
WebReq.ContentType = "text/json; charset=utf-8";
WebReq.Headers.Add("Authorization", Answer.ReadToEnd());
HttpWebResponse WebResp2 = (HttpWebResponse)WebReq.GetResponse();
^ This is where it breaks because I'm not authorized.
And the only useful documentation from the API is that I need to pass the access token when making additional calls, but I suspect I'm passing the wrong token.
Thanks in advance
deSex

I was sending the HttpWebResponse as the token, instead of the string that resulted from the StreamReader. I created a new variable called token with this string value and added it to the header "Authorization" as should be.
byte[] buffer = Encoding.ASCII.GetBytes("username=Username&password=Password");
HttpWebRequest WebReq = (HttpWebRequest) WebRequest.Create("http://api40.maildirect.se/User/Authorize");
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
Stream PostData = WebReq.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
HttpWebResponse WebResp = (HttpWebResponse) WebReq.GetResponse();
//This token variable was something I missed creating and it also had to get the " removed to work properly.
var token = new StreamReader(WebResp.GetResponseStream()).ReadToEnd().Replace("\"", "");
WebReq = (HttpWebRequest) WebRequest.Create("http://api40.maildirect.se/Contacts");
WebReq.Method = "GET";
WebReq.ContentType = "application/json; charset=utf-8";
// This is where another part of the problem was, sent in the wrong type to the header, but when I replaced it with the token variable it worked like a charm :)
//WebReq.Headers.Add("Authorization", WebResp.ToString());
WebReq.Headers.Add("Authorization", token);
HttpWebResponse WebResp2 = (HttpWebResponse) WebReq.GetResponse();

Related

c# PayPal Acess Token does not return anything although connection is "OK"

I am using .net to connect to PayPal to get access token. I was following the documentary provided on PayPal. https://developer.paypal.com/docs/api/overview/#make-your-first-call
This is what I have so far. Mostly go it from here. Although it connects, it does not return anything back. I tried it on the Postman and I am getting a json object with access token, but nothing is returned here.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token");
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(clientId + ":" + clientSecret));
request.Accept = "application/json";
request.Headers.Add("Accept-Language", "en_US");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
byte[] postBytes = Encoding.ASCII.GetBytes("grant_type=client_credentials");
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Flush();
postStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
This is what I am getting from on breakpoints.
response.CharacterSet = ""
response.ContentLength = 899
response.StatusCode = OK
Found the answer. The following code provides the json object.
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString); // This will display the answer as JSON, now just parse it.
Follow PayPal's .NET SDK Quick Start guide. You can authenticate and get your access token as follows:
using PayPal.Api;
// Authenticate with PayPal
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();

Google OAuth2 Bad Request

I am trying to write a YouTube app for windows phone, and I stumbled upon some problems on the authentication side. For some reason the following code is not working properly,
string url = "https://accounts.google.com/o/oauth2/token?";
string postData = "code=" + str + "&client_id=*********.apps.googleusercontent.com&client_secret=*******&grant_type=authorization_code";
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);
byte[] data = Encoding.Unicode.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
using (Stream stream =await httpWReq.GetRequestStreamAsync())
stream.Write(data, 0, data.Length);
HttpWebResponse response =(HttpWebResponse)(await httpWReq.GetResponseAsync());
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
I am fairly new to HttpWebRequest so probably I missed something, although I am getting a response:
Bad Request
To be specific it says that grant_type is missing although I am pretty sure that it is not, I did everything according to the documentation. What am I doing wrong ?
This will probably fix it
parameters.Append("code=" + str);
parameters.Append("&client_id=*****.apps.googleusercontent.com");
parameters.Append("&client_secret=*****");
parameters.Append("&redirect_uri=urn:ietf:wg:oauth:2.0:oob:auto");
parameters.Append("&grant_type=authorization_code");
string p_params = parameters.ToString();
byte[] p_data_params = Encoding.UTF8.GetBytes(p_params);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
request.Accept = "application/json";
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = await request.GetRequestStreamAsync();
dataStream.Write(p_data_params, 0, p_data_params.Length);
dataStream.Dispose();
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
Stream responseStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8);
string result = readStream.ReadToEnd();
Works fine for me.

How do I store a cookie after login

I'm trying to sign in to a website. It should be done by a POST request. But i need to store the cookie somehow.
My actual code:
public void botLogin(string userName, string passWord)
{
ASCIIEncoding encoding = new ASCIIEncoding();
string post_data = "username=" + userName + "&password=" + passWord;
byte[] data = encoding.GetBytes(post_data);
var requestUri = "http://registration.zwinky.com/registration/loginAjax.jhtml";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
var sharedCookies = new CookieContainer();
request.CookieContainer = sharedCookies;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
MessageBox.Show(sr.ReadToEnd());
sr.Close();
stream.Close();
}
How would i store the cookie now to use it for other requests?
First of all, cast the created WebRequest to HttpWebRequest. This will give you access to more HTTP-specific properties and methods.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
Define a CookieContainer object at the application level and set that for each created request.
request.CookieContainer = sharedCookies;
I'm pretty sure, the HttpWebRequest object will store the cookies after the download so that the next request can use them. If that still doesn't work, examine the HttpWebResponse object for cookies (again, don't forget to cast the response object to that).

Having a really hard time getting OAuth2.0 token. Keep getting 400 Bad Request

/*WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string parameters = "code=4/f2PwqbN1Z5FpEEcT0scRH20B6d-F.ouqZIhzZqUYbEnp6UAPFm0EuJPwSigI&" +
"client_id=162438320977-ml14ajmuutlrr71maal933ma5cjolc8l.apps.googleusercontent.com&" +
"&client_secret=1IJxvSnmxcx-i2l_YGgYOD0i&redirect_uri=http://localhost&grant_type=authorization_code";
byte[] data = Encoding.UTF8.GetBytes(parameters);
var test = client.UploadData("http://accounts.google.com/o/oauth2/token","POST", data);
string result = data.ToString();*/
StringBuilder parameters = new StringBuilder();
parameters.Append("code=4/IoAJMoYxUqk7lkH_WbSr3lk4URf1.0t7Qx7qZE5QeEnp6UAPFm0G0EvMSigI");
parameters.Append("&client_id=162438320977-ml14ajmuutlrr71maal933ma5cjolc8l.apps.googleusercontent.com");
parameters.Append("&client_secret=1IJxvSnmxcx-i2l_YGgYOD0i");
parameters.Append("&redirect_uri=urn:ietf:wg:oauth:2.0:oob");
parameters.Append("&grant_type=authorization_code");
string p_params = parameters.ToString();
byte[] p_data_params = Encoding.UTF8.GetBytes(p_params);
HttpWebRequest request = (HttpWebRequest) WebRequest.Create("https://accounts.google.com/o/oauth2/token");
request.Accept = "application/json";
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = p_data_params.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(p_data_params, 0, p_data_params.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8);
string result = readStream.ReadToEnd();
The only approach that seems to work for me is using HttpWebRequest. I found the answer here: .Net Google OAuth token WebRequest Bad Request Protocol Error If anyone knows of a way to get the Web Client implementation working please let me know! Thanks.

Sequence of HttpWebRequest

I am currently in the process of automating a web interface for administrating users of an FTP.
I am trying to do this with HttpWebRequest, i have one call that logs me on the site and the second call is supose to add a new user for the FTP access.
I have tried my two urls in the browser and they work, they end up creating a user.
string login = "https://www.ftpsite.net/./panel/index.php?txvUsername=myaccount&txvPassword=myPassword&submitButton=Login";
this gets me logged in when i enter it in the browser address bar.
the second call to create a user is as follows.
string createUser = "https://www.ftpSite.net/panel/ftpsites/updatelogin?login_id=&login=toto123&realname=realnametoto&homedir=root&passwd=superpassword11&expdate=01-01-2100&neverExpire=on&quota_value=0&quota_unit=GB&group_id=0&status=on&ftp=on&filelist=on&ftp_download=on&http=on&web_filelist=on&web_download=on&email=";
This creates a user when i enter it in the browser's address bar if it follows the one that logs us in.
My problem is that i am trying to do this using HttpWebRequest and without success. I can get myself logged in but when i try to create the user it seems to return a "bad" error code saying i have created too many users already which isnt the case since i can create more after that call. Here is the code i use with HtttpRequest
_datCookie = new CookieContainer();
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(login);
httpWebRequest.Method = "POST";
httpWebRequest.CookieContainer = _datCookie;
WebResponse response = httpWebRequest.GetResponse();
referer = response.ResponseUri.AbsoluteUri;
Stream requestStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(requestStream);
_datCookie = httpWebRequest.CookieContainer;
response.Close();
httpWebRequest = (HttpWebRequest)WebRequest.Create(createUser);
httpWebRequest.CookieContainer = _datCookie;
httpWebRequest.Referer = referer;
httpWebRequest.Method = "POST";
response = httpWebRequest.GetResponse();
requestStream = response.GetResponseStream();
streamReader = new StreamReader(requestStream);
webBrowser.DocumentText = streamReader.ReadToEnd();
response.Close();
What i caught and tried to imitate without success here.
Are you sure they should be POST requests? The URLs seem to have all of the fields in the query-string, which suggests they should be GET requests instead.
Based on the Fiddler screen-shot, you need to make a POST request with the fields in the body, not the query-string:
var cookies = new CookieContainer();
// Request 1 : Login
var request = (HttpWebRequest)WebRequest.Create("https://www.ftpsite.net/./panel/index.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookies;
string postData = "txvUsername=myaccount&txvPassword=myPassword&submitButton=Login";
byte[] postBytes = Encoding.Default.GetBytes(postData);
request.ContentLength = postBytes.Length;
using (Stream bod = request.GetRequestStream())
{
body.Write(postBytes, 0, postBytes.Length);
}
WebResponse response = request.GetResponse();
string referer = response.ResponseUri.AbsoluteUri;
// Request 2 : Create user
request = (HttpWebRequest)WebRequest.Create("https://www.ftpSite.net/panel/ftpsites/updatelogin");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookies;
postData = "login_id=&login=toto123&realname=realnametoto&homedir=root&passwd=superpassword11&expdate=01-01-2100&neverExpire=on&quota_value=0&quota_unit=GB&group_id=0&status=on&ftp=on&filelist=on&ftp_download=on&http=on&web_filelist=on&web_download=on&email=";
postBytes = Encoding.Default.GetBytes(postData);
request.ContentLength = postBytes.Length;
using (Stream bod = request.GetRequestStream())
{
body.Write(postBytes, 0, postBytes.Length);
}
response = request.GetResponse();
requestStream = response.GetResponseStream();
streamReader = new StreamReader(requestStream);
webBrowser.DocumentText = streamReader.ReadToEnd();
response.Close();

Categories