How to render a page following a GET request node js - javascript

I am working on express js and a particular endpoint renders the page using
res.render('dialog',{state:'admin'});
This endpoint is at http://localhost:3000/api/login. When i open this link in the browser, it opens the dialog.ejs page but when i call this endpoint using a GET request from another part of the server, the dialog.ejs page is not rendered
request({
url: 'http://localhost:3000/api/login',
headers:{
'Authorization' : auth
},
method: 'GET'
}, function(err, response, body) {
console.log("Response to request for authorization code : " + response.statusCode);
});
Please help !

Well, when you build a handmade request chances are that you're missing half of the headers the browser is sending, so that can be one of the reasons the whole thing is failing
On the other, if your making a machine to machine request, you DON'T want the ejs page renders, You only need to recover the neeeded data and /or make the server do something "as you were login in from a browser".
And as you're including the authorization Header, you're probably trying to simulate a login or authorization of some kind ( maybe a JWT Token ?)
Any case i think oyour only options is to mimic what your browser do as far as possible . So Build a perfectly correct set of headers, inject what will
be the result of form data, probably url_encoded, and use the correct request method (GET is perfectly correct, but coming from an html from POST is much more common. check it)
Just only one suggestion. Rendering a full web page from an /api/login seems a bit incorrect. Usually Api enpoints talk JSON only. In and out

Related

DJango Post csrf_token invalid and /favicon.ico not found

I got a problem with DJango. Im trying to send data to a SQL Database in DJango. So I need my token, which I get with {{ csrf_token }}. But when I send the data on the HTML Website, it tells me POST 403 Forbidden and the DJango Terminal says NotFound: /favicon.ico, as well as Forbidden (CSRF token from POST has incorrect length.): /ausgeben/
Does anyone have a solution for this. Down below is the code I`m using for the token request.
Thanks!
let formData = new FormData();
formData.append("name", name);
formData.append("gewinde", gewinde);
formData.append("laenge", laenge);
formData.append("durchmesser", durchmesser);
//formData.append("containerNR", containerNR);
formData.append('csrfmiddlewaretoken', token);
fetch('/ausgeben/',{
method: 'POST',
body: formData
});
Try sending the csrftoken in the fetch headers rather than in the body of the request. Disclaimer that I haven't used this with fetch but it was necessary with JQuery and an $.ajax request.
fetch('/ausgeben/',{
headers: {
'X-CSRFToken': token
},
...
TL;DR
Add a favicon.ico
Long version :
Searching for more topics about CSRF issues, I found this one.
I think you are facing an old (but it seems still valid) issue with CSRF and some browsers. It is often related to the favicon.ico file but it could happen with other static ressources (like javacript sourcemap *.map files).
After accessing your page, the browser requests the favicon.ico. If the file does not exist AND the request is handled by your framework, it could lead to generating a new CSRF token, therefore making the one on your form invalid.
To quote another :
Users are assigned a session cookie when they land on a PHP page. A CSRF token is associated with a session when users visit the login page.
Favicon requests were going to PHP instead of a static resource. Normally that's fine, since PHP will see the cookie.
But since the request looked like it was for a static resource, Varnish stripped the cookies before passing it back to Apache/PHP. That meant PHP issued a new session that replaced the old one.
https://news.ycombinator.com/item?id=3590328

How to extract status code of a protected web page with Node.js backend?

I am trying to only access a webpage's returned status code but the page is proctected by a login process. I already have the credentials but I cannot directly send http request and see the status code because it returns HTML of login page. I need to find a way such that when I send http request to that web service, it should go through those login process and return me only status code. An advised way is that using scripted browser, but still even if I successfully login to that page and display it, how can I send status code to my local backend ?
If the logon process consists of just giving the correct username and password, you can "fake" it with a single request like
fetch("https://protected.page/login", {
method: "POST",
headers: {"content-type": "application/x-www-form-urlencoded"},
body: "username=you_know_it&password=you_know_it&submit=Logon"
}).then(response => response.status);
But if login involves one-time tokens or captchas, this is of course not sufficient.

How to obtain logged in user information from outside Phabricator domain?

In short, I have a Pharbicator setup on a domain A, but then I have to implement a service on domain B which relies on the Pharbicator.
So this is the story, I am trying to gather information using the Phabricator Conduit user.whoami API to see whether the current user is logged in. But due to various reasons I couldn't make it. I would like to know what is the correct way of doing so.
I have tried three methods but they all did not work. Here is what I tried
Method 1: Using Ajax Request
What I did is just to fire an POST Ajax request with the api token
$.ajax({
url: 'http://127.0.0.1:8080/api/user.whoami',
method: 'POST',
cache: false,
data: 'api-token='+app.PHABRICATOR_APIKEY
}).done(function(response) {
console.dir(response);
}).fail(function(jqXHR, textStatus) {
console.log(textStatus);
});
This method does not work (as expected) because it is a CORS request, and the Phabricator server does not have Access-Control-Allow-Origin header.
Although I can add that Access-Control-Allow-Origin header, but somehow this requires modifying the Phabricator source code so I would consider this as the last solution I would do.
Method 2: Using a PHP as proxy and inside use curl to request for it. So the whole request will be like Client Browser <-> PHP Proxy Script <-> Phabricator
This method is actually able to send the request and get response. But the information is wrong as it returns only the user of the API key.
If I understand it correctly, the curl is not having my browser session, so there is no way for it to really know who I (the browser client) am in Pharbricator. So I assume then the API will just fallback to use the information of API key and thus return information not I intended.
Method 3: Using the PHP library __phutil_library_init__.php provide by Phabricator
require_once '/var/www/html/phabricator/libphutil/src/__phutil_library_init__.php';
$api_token = PHABRICATOR_APIKEY;
$api_parameters = array();
$client = new ConduitClient('http://127.0.0.1:8080/');
$client->setConduitToken($api_token);
$result = $client->callMethodSynchronous('user.whoami', $api_parameters);
return $result;
Again this is nothing special, just a direct copy of code from the documentation. But again it is returning only the user the API key belongs to. And I think it is just the same as what method 2 is behaving.
I am thinking if I am understand the Conduit API in a wrong way. And more importantly I would like to know how I should implement the whole architecture so that it can gather information using the current browser session. Thank you.

Ruby on Rails: Difference of Authenticity Token being in Header or POST

I've just noticed it doesn't matter where I put my Authenticity Token when submitting a request via AJAX. I can either append it to the form as POST data, or put it into the Header.
Is there any difference? Especially regarding security?
Additionally:
I didn't encode the Token in Javascript. Am I exposed to something now?
Thanks in advance.
EDIT:
form.on("sending", function(file, xhr, formData) {
xhr.setRequestHeader('X-CSRF-Token', AUTH_TOKEN);
// formData.append('authenticity_token', AUTH_TOKEN);
});
This is my Javascript adding the token to the Header or (commented out) to the POST data. AUTH_TOKEN is the raw key. I did not encode it in any way.
Part one
There is totally no difference if you pass authenticity token via GET params, POST data or request headers (POST/GET params are virtually the same in Rails).
Let's look at the code (not the best code I've ever seen but...)
def verified_request?
!protect_against_forgery? || request.get? || request.head? ||
form_authenticity_token == params[request_forgery_protection_token] ||
form_authenticity_token == request.headers['X-CSRF-Token']
end
Request if valid if (any of following)
protect_against_forgery? is false
request is GET
request is HEAD
token in params equals one stored in session
token in headers equals one stored in session
I should add that token is generated for every request and stored in session for later inspection (if subsequent request is POST/PUT/PATCH/DELETE)
So as you see both ways of passing authenticity token are valid.
Part two
Is passing raw auth token in AJAX dangerous? No, as much as passing it in a form is totally not dangerous. To explain further I will quote an excellent answer in another SO question
Why this happens: Since the authenticity token is stored in the
session, the client can not know its value. This prevents people from
submitting forms to a rails app without viewing the form within that
app itself. Imagine that you are using service A, you logged into the
service and everything is ok. Now imagine that you went to use service
B, and you saw a picture you like, and pressed on the picture to view
a larger size of it. Now, if some evil code was there at service B, it
might send a request to service A (which you are logged into), and ask
to delete your account, by sending a request to
http://serviceA.com/close_account. This is what is known as CSRF
(Cross Site Request Forgery).
original answer: https://stackoverflow.com/a/1571900/2422778
I still consider this question laziness/lack of patience on your side as all I wrote is very well explained both in Rails Guides and on Stack Overflow. Hope next time you will be more persistent in looking for answers before posting here.
Anyway I am glad I could help.
You can see the difference when you use some tool like https://www.owasp.org/index.php/Category:OWASP_WebScarab_Project or http://www.charlesproxy.com/
That are proxies, which you can turn on locally to fiddle with your HTTP requests and responses.
Very useful for web development.
Good luck.

Ajax jquery unauthorized request

I am making an ajax request using Jquery and everything works fine except the page is protected so only logged in users can make request. I am already logged in but I think Jquery ajax doesn't send my cookies to the url. How can I solve this error so cookies, headers are also sent so the page doesn't treat it as 401 request?
Thanks in advance :)
It sounds like you're trying to request a page on a different domain from the one your site is running on. If this is the case then it's the browser that is telling you the request is unauthorized rather than the other site.
Edit:
If this is the case and you control the other website then I believe you can allow requests using a specific header (http://www.w3.org/TR/2008/WD-access-control-20080912/#access-control-allow-origin). If you don't control the other server then there is no (pure javascript) way round this problem.
You could run a proxy on a server you control to request the page and pass it on to you. However this will still have the problem that it will be requesting the page without your user's cookies.
my jquery solution:
in your ajax call(for basic authorization):
headers: {
"Authorization": "Basic " + btoa('username:password')
},
or
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', "Basic " + btoa('username:password'));
},
You still can check session as normal

Categories