Prevention against CSRF? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I often use AJAX to write into MYSQL database like so
$.ajax({
url: "writescript.php",
type: "POST",
data: { data : mydata,//this could be anything
},
success: function (html) {
//do something
}
});
And the writescript.php looks like this
$data=$_POST["data"];
//and then write into database.
Now this works and everything but then anybody can view the ajax request since it's pure JS and can be viewed from the page source. Given the information about the script name and parameters, an attacker could try to call the writescript as well and write into my database or read depending on what the script does. This is obviously not good. So am I missing something here? Is AJAX not designed to be used for such stuff? Or am I using it wrong?

I don't think a CSRF problem is presented here. CSRF means an attacker tricking a legitimate and authenticated user into hitting a page by clicking a link or any other means, in turns doing things on behalf of them. If your application checks for the header to make sure the request is an ajax call from the browser, and do not allow cross domain ajax requests, theoretically an attacker could not perform a CSRF attack
The problem you presented is more of an authorization problem. You are afraid that an attacker can write/read into your database, but any legitimate users should be able to do that, so naturally the solution is to add an authentication layer to fend off attackers.

You are missing "sessions". You can use sessions or any other authentication method to avoid this case. That is, be sure that the user is logged in at the beginning of the php code.

When user requests the page, generate a security token on that page and note it on the server. Then the response comes back, just compare the recieved security token with the saved one.
https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet

Related

Inserting into MySQL database with javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm currently working on a school project and I need some help. I ran into a problem when trying to put the data I read from another IP address (using AJAX) into a MySQL database. I tried using node.js but because I'm calling the function when I press the button on a webpage it doesn't work... So any suggestions or tips on how to make node.js work.
ajax function:
function AddShoots() {
$.ajax({
method: "POST",
dataType: "json",
url: "http://192.168.1.8",
success: function (html) {
for ($i = 0; $i < html.length; $i++) {
console.log(html[$i]);
}
},
});
}
The data I get and would like to insert into database:
EDIT: additional explanation
sorry for the HTML/CSS there was an error while copying. To clarify my endpoint I have a python image recognition program written on raspberry PI, the Raspberry PI server that is on the IP returns the numbers seen in the picture, I would like to insert the numbers into a MySQL database and I need help with how to do that because I only inserted data into tables with PHP before, but I can't do this in this case because I'm using AJAX (at least not with my knowledge) I hope this explains everything better.
Another edit:
A picture that might help with understanding (I'm super bad at explaining sorry English is not my primary language that's why I have bad expressions and a hard time explaining some stuff).
Sounds like you're getting your technologies mixed up a bit.
Lets clarify a few terms first:
NodeJS
Is a JavaScript runtime for server-side or backend code.
Runtime
An environment for code to execute like NodeJS or a web browser.
Server-Side
This refers to code running on a server. Could be PHP, Java, Python etc... or even JavaScript if you're using Node.
Backend
Usually means the same thing as "server-side" when people say "backend".
Frontend
In this context, "frontend" is referring to code being executed in a web browser.
AJAX
A style of HTTP request that a browser can use to send and fetch data without reloading the current page.
Now that we have that out of the way...
Node is a server-side runtime for JavaScript, so your JS code running in the browser has no way to talk to your Node code directly.
If you want to click a button in the browser and see data get written to your database you have to make an AJAX call to a url that your backend is listening to (known as an endpoint or a route).
It's a bit difficult to interpret your intentions from your example but I think you mean to send a POST to http://192.168.1.8. So you'll need a route configured in your Node app that can handle the AJAX request, and from there you can write the data to your database.
Of course you'll also need to pass the data with the request. That gets passed along with the options parameter in your $.ajax(/* ... */) call.
At a high level this is what I believe you're trying to achieve:
So basically your app should have at least two files:
index.html This will have your button as well as the JS code that fetches data from your Pi. This "front-end" JS will also have to send an AJAX request to your Node app.
app.js This will be your Node app. It will have to expose an endpoint that your front-end code can send data to. Inside the function of that endpoint, you'll handle writing the data to your database.
There's a library called Express that will help you make your endpoint. I recommend following their Getting Started guide: https://expressjs.com/en/starter/installing.html
Update
I see you updated your answer with a diagram. I assumed your mental model was probably exactly like that, which is why you're having a hard time.
When a user visits a url such as https://stackoverflow.com for example, the request doesn't go to the web browser. The request has to go through a server first. When you use Node, your app essentially is the server, and is responsible for returning the correct response.
In your case the response would be an HTML file like index.html for example.
That index.html is the webpage and it is going to contain your "front-end" JavaScript code, which can communicate to your Raspberry Pi server over HTTP to get that image data you're talking about.
JavaScript running in the browser has no way to communicate to a SQL database directly. So you have to send a request over the network to your Node service. Inside your backend application you can write the data to a MySQL database with the help of packages you can get from NPM. Here's an example of one: https://www.npmjs.com/package/mysql
Update 2
It sounds like you're more comfortable using PHP. You can swap NodeJS out with PHP and my diagram would still represent what you want to achieve at a high level. The key difference is you won't have to figure out how to set up a "route".
With PHP you can just have a file named something like SaveMyData.php:
<?php
// Get the body of the POST request
$data = file_get_contents('php://input');
// Decode the JSON string so you can work with it in PHP
$decodedData = json_decode($data);
// $decodedData is now an array of the data you sent from the browser
foreach($decodedData as $row) {
// write the row to your database here
}
Then the "endpoint" (making some assumptions about how your serving your app) is just http://localhost:8080/SaveMyData.php and that becomes the URL you pass to your AJAX call from the browser.
Your AJAX request would look something like:
function AddShoots() {
$.ajax({
method: "POST", // the post to your Pi I'm assuming?
dataType: "json",
url: "http://192.168.1.8",
success: function (data) {
$.ajax({
method: "POST", // this is going out to your PHP backend
dataType: "json",
url: "http://localhost:8080/SaveMyData.php",
data: data,
success: function (response) {
// do stuff with the response if you'd like
})
});
},
});
}
Tons of "best practices" are being violated here, but for the purposes of a school assignment this should get you pointed in the right direction.

Document.write() is giving back "Uncaught TypeError: Cannot read property 'document' of null"" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am using Angular2 for the front end on a website. It will be iframed into another website. when using the HTTP post method i receive the response which is json
This is the API Post method. it will return a json result
in the front end sending of the post request i take the response and put it into json. then i set a variable in my AppService class with a set method. then in the completion of the HTTP request i open a new tab and fill it with the HTML. using the document.write() is where i get the error
This is the front end Post request
the 2 options i thought of to solve this were sending a window.postmessage() to the parent of the iFrame to try and open the new tab. Or make another iFrame inside of the current however both of these are non-optimal.
It's entirely possible that a pop-up window gets blocked by the browser. If that happens, window.open() returns null and you need to write your script to handle this situation.
Most modern browsers are pretty "clever" about blocking pop-up windows, meaning they only allow a script to open one as a direct consequence of a user interaction. Because of this, running window.open() on the completion of an AJAX request is very likely to fail. One way to solve this is to open the window immediately when the user has initiated the action, then perform the AJAX request and write to the window when it's successful. Something like this:
button.onClick = function() {
var popUp = window.open();
if (popUp) {
doAjaxRequest().then(function(data) {
popUp.document.write(data);
popUp.document.close();
});
}
}

Is GET better than POST in AJAX approach? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm wondering, why are we still using GET method in AJAX requests for example:
$.ajax({
type: "GET",
url: "SomeController/GetSomething",
data: { id: 100}
});
GET is handy, when you want to store data in url, when you are querying Google and you want to send that query to friend or whatever else. On the other hand, we have security gaps. They are not big (I'd say they are obstacles), but it'd be slightly better to use POST when you don't want to show form data. Moreover, POST can store any type of data, control data size and hide somehow passing variables.
Is it a good solution to always use GET in places, which are not "public" (search bars, article page, user profile, ...) and use POST everywhere else? With this approach, all AJAX queries should be send using POST method.
When using POST XHR, you use a two-step process : sending the headers first and then the data, but you use Ajax for responsiveness, right ? So why use a two-step process when you can use a one-step process (GET XHR)?
Furthermore, AFAIK, GET request are cacheable, POST are not.
Last but not least, as some have pointed : HTTP verbs do have a meaning.
Keep on using GET XHR for getting datafrom server, and POST XHR for sending data.
Like you said, GET is not secure but it allows us to copy and paste links and get the same results. POST is more secure in the way it does not show the parameters directly, it still needs work on the backend to plug all the holes.
The key is not to forget why one is called "GET" and the other one "POST".
GET is accessible, so not good for anything sensitive, but easy to manipulate directly.
POST should be used to submit to the server side, sensitive or "lengthy" data.
This is only my opinion:
A savvy user who really wants to know what data is being posted will always be able to discover exactly what data is being transmitted during an http request. The only tool that you really need for this are the tools that are built into modern browsers. If you transmit using HTTPS, then a third party will be able to discern GET parameters, but not POST data, so I would say you are correct that sensitive data should only be sent as POST. Otherwise, as a security tool, POST over GET serves a similar function to a password mask on password inputs (prevent someone from looking at your data over your shoulder).
Now, to your question "Is GET better...?"
I would say that just like with synchronous http requests, you should use GET when the user or your application need to get data, and POST when your app of the user needs to post data (for persistence - in the session (like a login), or a database, etc). So it's really more of a semantic difference. Practically, you could use post for everything if you wanted to.

How to do a api request on the server side before rendering the page? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a JS script on a page that makes a call to Y server on page load and it displays some data. If you look on page source you can see the script making the call to Y server.
What I need to do instead is make the api request to Y server from MY server and render the page to client completed without the JS scripts. So if you look at the page source you will not see any reference to Y server because that will all have happened on my server in the background before the page was rendered to the client.
Does anyone know how this setup can be accomplished? Looking for guidance... Links to docs? Please ask for clarification if unclear.
At a high level, you'll need to:
Implement an HTTP client for the API
Add code that calls the API (probably in a controller, but it could be a helper, model or service object)
(Optionally) parse the response (this depends on what format it's in and what format you need)
Render the parsed response in the view
2 & 4 are easy. 3 is going to be up to you, unless you can provide concrete examples. It should be easy, though. That leaves 1.
If you're using a popular API, there's a good chance that a client has already been written. If it's something in house, you can write something custom using Net::HTTP or one of the other popular HTTP client libraries. As long as you don't need to send along any cookies/headers from the browser, this should be really easy.
Here's a quick example of how this could look using RestClient and an API that returns HTML.
class SampleController < ApplicationController
def index
#mydata = RestClient.get('http://path.to/your/api?with=params')
end
end
# /app/views/index.html.erb
<h1>Here's Your Data</h1>
<%= raw #mydata %>
what you need, is to generate directly your html from your server, and render a dynamic page.
You'll have to general your html from your templates, and render it directly to the client.
For example, php, you'll have your .twig file with php variables instead of your static html.
The same goes for java, with your servlets.
The page is rendered Back side, and sent as static file to the client.
Not sure for the exact method for ROR.
I'm trying a simple example. imagine that the variable data contain the elements you want to get from your api, here is your 2 ex :
//first case staticPage1.html
[...]
var data=loadAjax(url)
window.console.log(data);
//the page served from the back is the same in the front
//second case generated.someServerSideTemplate [...]
var data={{getDataFromUrl(url)}}
//some server side templating language
generated.html [...]
var data={"message":"hello world"} // actual page rendered
i hope it's clear...

How to redirect a user with PHP instead of JS [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have been searching to find out if it would be better to redirect a user loggin into a website on the client or server side. From my research i see that it is better to rely on to the server side.
I have a JS script that will use Jquery to post data to a php script to check the users login details, if they're find it tells the JS to redirect. This worked okay but now i want to redirect using the PHP script but the script won't redirect when i us $.post() method.
So the question is, how do i redirect the use this way? I'm trying to build this system so it's independent on the user having JS turned on in their browser so any help and tips would be very welcome.
Thanks.
Because you're using AJAX, only the JavaScript can redirect the browser. If the server attempts to do so, it will only redirect the AJAX request.
That being said, your statement that you are "trying to build this system so it's independent on the user having JS turned on" is contradictory with your use of $.post().
you may get the "Location" header (redirect URL) from here:
jQuery - get AJAX response headers
success: function(res, status, xhr) {
alert(xhr.getResponseHeader("Location"));
}
Use a standard form to post credentials to the auth method. Using JavaScript as the primary method of authentication is like having no authentication at all.
If you have already worked around that adequately and are just looking for a non-js fallback, make it all non-js. PHP redirects are very easy, but you have to output a header, which can't be done asynchronously, so you will have to post the data anyway.
Example PHP Redirect
header ('HTTP/1.1 301 Moved Permanently');
header ('Location: '.$location);

Categories

Resources