POST request with filled form values to login - http

I don't use javascript, so I'm completely new to it.
I have a link where I want to login per POST request. Just send a POST request with pre-defined correct login and password and get the data on the next page.
I'm using developer mode in Chrome to look on the requests sent by browser.
But when I type in correct combination of username and password, I don't see a single POST request, only GETs.
With incorrect username and password I'm able to see a POST request with following Form Data values:
xjxfun:_validateLogin
xjxr:1389197444586
xjxargs[]:<xjxobj>
<e><k>Username</k><v>SmyUsername</v></e>
<e><k>Password</k><v>SmyPassword</v></e>
<e><k>Autologin</k><v>S1</v></e>
<e><k>REFERER</k><v>Sdailyfield</v></e>
</xjxobj>
Here I typed in myUsername for Username and myPassword for Password.
My question is
What POST request do I need to send to this server to imitate form filling and submitting?
Thank you for answering. The best answer you can give is to describe the POST request with necessary data/headers/values, so that I can prove it fast in some REST client in browser

Here is the data I got sent from a valid login:
xjxfun:_validateLogin
xjxr:1389422948740
xjxargs[]:<xjxobj><e><k>Username</k><v>S<![CDATA[myemailhere]]></v></e><e><k>Password</k><v>Smypasswordhere</v></e><e><k>Autologin</k><v>S1</v></e><e><k>REFERER</k><v>Sdailyfield</v></e></xjxobj>
And this is what I got returned:
<?xml version="1.0" encoding="utf-8" ?><xjx><cmd cmd="js">Slocation.href = 'sudoku_des_tages.htm';</cmd></xjx>
By the way, this was a POST request.
I think the reason that you can only see GET requests, was because an HTTP redirect occurred on the server-side with your authentication details, and that request (as with all page requests) is a GET request, which is probably why you can only see GET requests with successful authentication.
Update: From what I understand, you are sending the values as header values (in others words, alongside Content-Type and the like), while you should send them in the post formdata. This is why you are finding your answer.

You can always use CURL :
$fields_string = '';
$url = "yourProceesfileURL";
$userdata = array(
'email' => youremail,
'password' => yourpassword
);
foreach ($userdata as $key => $value) {
$fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($userdata));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
:)

Note: This solution was suggested when the question was tagged with JavaScript and PHP and without Objective-C.
You can use JQuery to simulate the form filling like this:
$(function(){
$('#Username').val('MyUsername');
$('#Password').val('MyPassword');
$('input[type=submit]').trigger("click");
});
Working example here
First you want to set the values by getting the input element with his id and then setting his value. Once you finish updating all the requested values just trigger the submit button.
This will simulate you filling the form and submitting it. To do this automatically I would use PHP to get the content of the page and then firing the JQuery function:
echo file_get_contents("http://www.sudoku-knacker.de/anmeldung.htm?ref=dailyfield");

Related

JWT Authentication for WP-API - POST TO ACF Fields

I am trying to make an Auth via JWT Authentication for WP-API plugin. I am trying to follow this tutorial - steps, in this link:
https://firxworx.com/blog/wordpress/using-the-wordpress-rest-api-with-jwt-authentication/
Thus, I made a function in my functions.php file, inside my child theme and call this function in the header of a custom page template I have created, before get_header(); func. So, my code for now is like this:
function getToken() {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://www.example.com/wp-json/jwt-auth/v1/token');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'username=admin&password=password');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
"cache-control: no-cache",
));
$server_output = curl_exec($ch);
$token_result = json_decode($server_output);
if(isset($token_result->token)) {
return $token_result->token;
}
else {
return $token_result->message;
}
}
But, still getting this error:
"Invalid response getting JWT token on WordPress for API integration"
I want to make this API Call, in order to validate the user, before proceed my script. Without this validation, PHP should stop being execute.
After doing this API Call, I would like to make a POST in some Advance Custom Fields (ACF Pro plugin) that I have in some custom posts types..but this is another question..
Any advice or any other workarround solution on that, could be helpful please let me know
*EDITED
Found something.. because of Wordfence - captcha I can not get the token. it tells me to verify via email sent. Thus, the wordfence said: The filter “wordfence_ls_require_captcha” can be used to disable the CAPTCHA in circumstances of your choice. This may be useful for plugins that contain REST endpoints with authentication that should not require a CAPTCHA. Your filter should return false to bypass the CAPTCHA requirement when necessary, or otherwise true when the CAPTCHA should be required". How could I use this filter and where? How to return false in this filter like plugin suggests?
There is also the same problem here:
https://wordpress.org/support/topic/recaptcha-and-rest-api/
but no solution posted
Anyone, how to disable the verification send email through Wordfence? cause this is the problem
Finally, I got this working!
thanks to this post
How to disable auth verification email send, from Wordfence?
and #mircobabini help.
I have added the filter in my functions.php file of my child-theme like this:
add_filter( 'wordfence_ls_require_captcha', '__return_false' );
Thus, the validation email for logging in via Wordfence, does not send anymore and I can proceed to my code.
*I have edited my getToken() function, because there were some errors in it!

Correct Key for Microsoft Cognitive API

I am currently trying to do a News Search on the MS Cognitive Services Bing Search API. I have read many docs, but seem to be stuck.
Here is the code I'm using:
$url = 'https://bingapis.azure-api.net/api/v5/news/search?q=microsoft&mkt=en-us';
$key = '{MY KEY}';
$request_headers = array();
$request_headers[] = 'Ocp-Apim-Subscription-Key: '. $key;
$request_headers[] = 'User-Agent: mozilla';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
$data = curl_exec($ch);
curl_close($ch);
echo $data;
This code returns the following result:
{ "statusCode": 401, "message": "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription." }
As I get the same result from the API Explorer on the site, I think the problem is with my key, rather than my code. But this is the key supplied by Cognitive Services for my subscription, as found on https://www.microsoft.com/cognitive-services/en-us/subscriptions (when logged in).
If this is not the correct key, what should I be using?
I'm on the Cognitive Service team at Microsoft. You may hit this issue for the Bing APIs if you generated your subscription keys after 22 June (or renewed your key) and are currently using the https://bingapis.azure-api.net/api/v5/ base URI.
When updating to use the new subscription keys, you must update your application to use the https://api.cognitive.microsoft.com/bing/v5.0/ base URI.
Additionally, If you were using the API Reference for Bing APIs, you can try the following links below which should work with the new keys.
Apologies for the inconvenience and thanks for reporting the issue- we are getting the link updated.

Receive Bearer Token from API with R

I'm searching for a solution to receive a Bearer token from an API using username and password.
Right now I'm reading the token through Chrome and extract my data, which is less then ideal of course.
I tried with httr and curl to optain through R and receive the Bearer token, but i think i am quite lost.
I think it should be quite simple, from the login information i gathered the mask from the login as
{"username":"name","password":"pw"}, shouldn't this just work with the POST command and the right headers?
POST(url="api_login",config=add_headers(c("username: name"
,"password: pw")))
Doesn't work at all. I can provide the example for php which looks like this:
<?php
// Include Request and Response classes
$url = 'url';
$params = array(
'username' => 'sample_username',
'password' => 'sample_password'
);
// Create a new Request object
$request = new Request($url, 'POST', $params);
// Send the request
$request->send();
// Get the Response object
$response = $request->getResponse();
if($response->getStatusCode() == 200) {
print_r($response->getBodyDecoded());
}
else {
echo $response->getStatusCode() . PHP_EOL;
echo $response->getReasonPhrase() . PHP_EOL;
echo $response->getBody() . PHP_EOL;
}
?>
As I'm not very familiar with php i would be very pleased for any help or a guide into the right direction. I searched hours
for API access through R but everything looks very specific to a special login.
I figured out this API uses a deprecated version of Swagger, if this is any useful information.
Thats what I'm doing atm, login with the website and read the token out of my browser. I want to login from inside R, sorry if I wasn't clear.
I updated my code now to:
opts=curlOptions(verbose=TRUE,
ssl.verifypeer = T)
postForm(url,
"username:" = uname, "password:"=pswd,
httpheader = c('Content-Type' = 'application/json', Accept = 'application/json'),
.opts=opts,
style='POST'
)
Which results in an error: SSL certificate problem: self signed certificate in certificate chain.
I tried a lot of different certificates with 'cainfo' inside the argument but can't make it work.

Should I URL-encode POST data?

I'm POSTing data to an external API (using PHP, if it's relevant).
Should I URL-encode the POST variables that I pass?
Or do I only need to URL-encode GET data?
UPDATE: This is my PHP, in case it is relevant:
$fields = array(
'mediaupload'=>$file_field,
'username'=>urlencode($_POST["username"]),
'password'=>urlencode($_POST["password"]),
'latitude'=>urlencode($_POST["latitude"]),
'longitude'=>urlencode($_POST["longitude"]),
'datetime'=>urlencode($_POST["datetime"]),
'category'=>urlencode($_POST["category"]),
'metacategory'=>urlencode($_POST["metacategory"]),
'caption'=>($_POST["description"])
);
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
General Answer
The general answer to your question is that it depends. And you get to decide by specifying what your "Content-Type" is in the HTTP headers.
A value of "application/x-www-form-urlencoded" means that your POST body will need to be URL encoded just like a GET parameter string. A value of "multipart/form-data" means that you'll be using content delimiters and NOT url encoding the content.
This answer has a much more thorough explanation if you'd like more information.
Specific Answer
For an answer specific to the PHP libraries you're using (CURL), you should read the documentation here.
Here's the relevant information:
CURLOPT_POST
TRUE to do a regular HTTP POST.
This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
CURLOPT_POSTFIELDS
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with # and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the # prefix.
#DougW has clearly answered this question, but I still like to add some codes here to explain Doug's points. (And correct errors in the code above)
Solution 1: URL-encode the POST data with a content-type header :application/x-www-form-urlencoded .
Note: you do not need to urlencode $_POST[] fields one by one, http_build_query() function can do the urlencoding job nicely.
$fields = array(
'mediaupload'=>$file_field,
'username'=>$_POST["username"],
'password'=>$_POST["password"],
'latitude'=>$_POST["latitude"],
'longitude'=>$_POST["longitude"],
'datetime'=>$_POST["datetime"],
'category'=>$_POST["category"],
'metacategory'=>$_POST["metacategory"],
'caption'=>$_POST["description"]
);
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
Solution 2: Pass the array directly as the post data without URL-encoding, while the Content-Type header will be set to multipart/form-data.
$fields = array(
'mediaupload'=>$file_field,
'username'=>$_POST["username"],
'password'=>$_POST["password"],
'latitude'=>$_POST["latitude"],
'longitude'=>$_POST["longitude"],
'datetime'=>$_POST["datetime"],
'category'=>$_POST["category"],
'metacategory'=>$_POST["metacategory"],
'caption'=>$_POST["description"]
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
Both code snippets work, but using different HTTP headers and bodies.
curl will encode the data for you, just drop your raw field data into the fields array and tell it to "go".
Above posts answers questions related to URL Encoding and How it works, but the original questions was "Should I URL-encode POST data?" which isn't answered.
From my recent experience with URL Encoding, I would like to extend the question further.
"Should I URL-encode POST data, same as GET HTTP method. Generally, HTML Forms over the Browser if are filled, submitted and/or GET some information, Browsers will do URL Encoding but If an application exposes a web-service and expects Consumers to do URL-Encoding on data, is it Architecturally and Technically correct to do URL Encode with POST HTTP method ?"

User sign in to a MVC application from another website or through web service

Here's the situation: the user is able to sign into a MVC application from another website. That website is not ASP.NET-based. It could be PHP, JSP or Websphere... or anything
I have tried doing this:
[HttpPost]
public string RemoteLogOn(string userName, string password)
{
if (userName != null && password != null)
{
if (MembershipService.ValidateUser(userName, password))
{
FormsAuthentication.SetAuthCookie(userName, false);
return "success";
}
else
{
return "failed";
}
}
else
{
return "failed";
}
}
Calling the MVC app at the /RemoteLogOn URI (posting the request using PHP and cURL) works. The "success" string is returned. However, it seems that the cookie is not generated properly - when I returned to the MVC site and check User. Identity.Name, null is returned.
What is the right way to allow user to log in via. a web service?
Edit How do I properly set the returned cookie.
PS. This is just a trial POC; eventually we'll use SOAP or REST and try to improve the security.
Here's the PHP code that did the calling
<?php
$url = "http://localhost:54134/Account/RemoteLogOn";
$fields = array(
"userName" => "asd1234",
"password" => "****"
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
echo '<pre>'.print_r($result, true).'</pre>';
//close connection
curl_close($ch);
</php>
Debugging the app shows the user name and password are passed in properly to the MVC side.
OK what you need to do is save the cookie that comes back from your cURL request and make sure it gets sent with subsequent requests.
This is how to set where to store cookies (and include in subsequent requests) in PHP:
curl_setopt($ch, CURLOPT_COOKIEJAR, 'mycookiefile');
You'll need the cookie filename to be constant through the process, so I would suggest using a variable and initialising it thus:
$cookieFile = tempnam("/tmp", "CURLCOOKIE");
You can get more details on this at the PHP documentation site:
http://www.php.net/manual/en/function.curl-setopt.php
This becomes a curl and PHP question then. I do not know curl and know little PHP but should be easy:
Take the authorisation cookie by checking the value of Set-Cookie header
parse the value which is in the format of .ASPXAUTH=<Cookie Value> and get the cookie value
Set the cookie in PHP
In all subsequent calls, get the value of the cookie from client and send to server using curl
curl_setopt($ch, CURLOPT_COOKIEJAR, '/some/path/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, '/some/path/cookies.txt');
This should do the trick. As you need to store the cookies and send them back. Otherwise each request would be treated as if its coming from a completely different user.

Resources