I am trying to make a simple call to a authorization Server with OAuth 2.0.
And I am very new to OAuth 2.0.
How do I make a call to the Authorization Server to get back my access token to send in the request header of request (if I am wording that correctly).
Below is what I have, Thanks in advance to any help.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Uri);
request.Method = "POST";
var uri = new Uri(Uri);
string postData = output;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
IAuthorizationState authorization = null;
AuthorizationServerDescription serviceDecription = new AuthorizationServerDescription
{
AuthorizationEndpoint = uri,
};
WebServerClient client = new WebServerClient(serviceDecription, Key, Secret);
client.AuthorizeRequest(request, authorization);
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
sr.ReadToEnd();
}
}
else
{
dataStream.Close();
response.Close();
}
}
What AS? how do users authenticate?
Typically, OAuth2 flows require user interaction with a browser (like described in this doc). It'd be great if you could add more context to what you are trying to do.
There are plenty of frameworks that you could use to avoid having to deal with lower level details of OAuth.
Related
I'm sending a request but the cookies are not being stored in my container for the response?
Example of code -
string uri = "https://www.localhost.com/"
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.ContentType = "application/x-www-form-urlencoded";
CookieContainer cookies = new CookieContainer();
request.CookieContainer = cookies;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (Stream stream = request.GetRequestStream())
{
byte[] bytes = new UTF8Encoding().GetBytes(s);
stream.Write(bytes, 0, bytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream stream2 = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream2, Encoding.UTF8))
{
str6 = reader.ReadToEnd();
}
}
}
as you can see I've implemented
CookieContainer cookies = new CookieContainer();
request.CookieContainer = cookies;
Which should store the cookies from the request within the container for further usage right within the response right? Like if the response needs the request cookies to load the page.
I suggest using HttpClient as it handles cookies for you and is just generally easier to work with. Also note that even though it’s disposable you generally should use the same HttpClient throughout your application. See: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
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).
I've been trying to have a WPF client connecting to a PHP server, logging itself in and fetching 'IsLogged.php' to validate that the client is logged in. However, 'IsLogged.php' always returns that the client isn't authenticated, what am I doing wrong?
Servercode:
"CreateAccount.php"
session_start();
if (isset($_POST['user']))
{
$_SESSION['UserName'] = $_POST['user'];
echo "check";
}
"IsLogged.php"
session_start();
if (isset($_SESSION['UserName']))
{
echo "allowed";
}
else
{
echo "not allowed";
}
Client code:
"Post" method
public static string Post(string RequestName, string PostData, out HttpStatusCode ReturnCode)
{
byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
WebRequest Request = WebRequest.Create(ChatAPI.Settings.BaseUrl + RequestName);
Request.Method = "POST";
Request.ContentType = "application/x-www-form-urlencoded";
Request.ContentLength = byteArray.Length;
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = Request.GetResponse();
dataStream = response.GetResponseStream();
ReturnCode = ((HttpWebResponse)response).StatusCode;
StreamReader reader = new StreamReader(dataStream);
string returnedData = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return returnedData;
}
And finally the window triggering the POST requests.
HttpStatusCode Code;
MessageBox.Show(General.Post("IsLogged", "", out Code)); --> Not allowed (intended)
MessageBox.Show(General.Post("CreateAccount", "user=jan", out Code)); --> check (intended)
MessageBox.Show(General.Post("IsLogged", "", out Code)); --> Not allowed (should be allowed)
Why is the server not registering the requests as a session?
The way the server identifies the client (and the corresponding session state) is through cookies.
Basically, in the CreateAccount request, the server attaches a cookie to its response and expects the client to present the cookie on every subsequent request.
If the cookie is not present in a request, the server has no way of identifying the client and treats the request as coming from an unknown source.
Your code does not manage cookies at all, so this is why the C# client always appears to be a new client to the PHP server.
The easiest way to save the cookie received from the server and present it on every new request is to use an instance of CookieContainer and attach it to every request you make.
I didn't try this code, so I'm not 100% sure of the syntax, but here's a starting point:
// this instance will be reused across multiple requests
private static CookieContainer cookieContainer = new CookieContainer();
public static string Post(string RequestName, string PostData, out HttpStatusCode ReturnCode)
{
byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
WebRequest Request = WebRequest.Create(ChatAPI.Settings.BaseUrl + RequestName);
Request.Method = "POST";
Request.ContentType = "application/x-www-form-urlencoded";
Request.ContentLength = byteArray.Length;
Request.CookieContainer = cookieContainer; // this line is new
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = Request.GetResponse();
dataStream = response.GetResponseStream();
ReturnCode = ((HttpWebResponse)response).StatusCode;
StreamReader reader = new StreamReader(dataStream);
string returnedData = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return returnedData;
}
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"a_value=0"a_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"a_value=0"a_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();
I am trying to replicate a Couch database using .NET classes instead of a curl command line. I have never used WebRequest or Httpwebrequest before, but I am attempting to use them to make a post request with the script below.
Here is the JSON script for couchdb replication(I know this works):
{ ""_id"":"database_replicate8/7/12", "source":sourcedb, ""target"":"targetDB", ""create_target"":true, ""user_ctx"": { ""roles"": ["myrole"] } }
The above script is put into a text file, sourcefile.txt. I want to take this line and put it in a POST web request using .NET functionality.
After looking into it, I chose to use the httpwebrequest class. Below is what I have so far--I got this from http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
HttpWebRequest bob = (HttpWebRequest)WebRequest.Create("sourceDBURL");
bob.Method = "POST";
bob.ContentType = "application/json";
byte[] bytearray = File.ReadAllBytes(#"sourcefile.txt");
Stream datastream = bob.GetRequestStream();
datastream.Write(bytearray, 0, bytearray.Length);
datastream.Close();
Am I going about this correctly? I am relatively new to web technologies and still learning how http calls work.
Here is a method I use for creating POST requests:
private static HttpWebRequest createNewPostRequest(string apikey, string secretkey, string endpoint)
{
HttpWebRequest request = WebRequest.Create(endpoint) as HttpWebRequest;
request.Proxy = null;
request.Method = "POST";
//Specify the xml/Json content types that are acceptable.
request.ContentType = "application/xml";
request.Accept = "application/xml";
//Attach authorization information
request.Headers.Add("Authorization", apikey);
request.Headers.Add("Secretkey", secretkey);
return request;
}
Within my main method I call it like this:
HttpWebRequest request = createNewPostRequest(apikey, secretkey, endpoint);
and I then pass my data to the method like this:
string requestBody = SerializeToString(requestObj);
byte[] byteStr = Encoding.UTF8.GetBytes(requestBody);
request.ContentLength = byteStr.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(byteStr, 0, byteStr.Length);
}
//Parse the response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
//Business error
if (response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine(string.Format("Error: response status code is{0}, at time:{1}", response.StatusCode, DateTime.Now.ToString()));
return "error";
}
else if (response.StatusCode == HttpStatusCode.OK)//Success
{
using (Stream respStream = response.GetResponseStream())
{
XmlSerializer serializer = new XmlSerializer(typeof(SubmitReportResponse));
reportReq = serializer.Deserialize(respStream) as SubmitReportResponse;
}
}
...
In my case I serialize/deserialize my body from a class - you will need to alter this to use your text file. If you want an easy drop in solution, then change the SerializetoString method to a method that loads your text file to a string.