Is it better to use:
<form class="delete" action="/post/delete/id/1234.html" method="POST">
<input type="submit" value="delete this post"/>
</form>
...instead of:
<a class="delete" href="/post/delete/id/1234.html">delete this post</a>
...when there is need to modify something in database? Like when adding, updating, deleting and voting? Also for logout action (which in my application is saving timestamps when the action is taken), etc.?
Well, per the HTTP spec, POST (in this case, your form submission) is for changing data and GET (in this case, your link) is for retrieving data. So you should use POST to delete things, and links should only be used to retrieve things. If nothing else, this makes it slightly harder for your end users to edit the URL to delete things that they shouldn't. But really, it's just "right" to use POST for anything that will change your data.
EDIT: including some text from above link:
GET
Requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect.
<form class="delete" action="/post/delete/id/1234.html" method="POST">
<input type="submit value="delete this post"/>
</form>
About code will generate HTTP Post
<a class="delete" href="/post/delete/id/1234.html">delete this post</a>
Above code will generate HTTP Get. You should not use Get to update/delete record. In other words, you should not use above hyperlink to delete a record.
HTTP Verb
Here are the explanation of HTTP Verb from ASP.NET MVC 4 and the Web API book
GET - Get a specific task, identified by the URI
PUT - Replace or create the single task identified by the URI
POST - Create a new subordinate under the task identified by the URI
DELETE - Delete the tasks identified by the URI
Using GET, you have potential for accidental or malicious actions. Consider this:
<img src="http://yourdomain.com/post/delete/id/1234.html">
If a user views this "image" (on any website) and they have delete permissions, it will send a request to that page and delete the post. Yes you can check the referer and such things, but it is an issue that is better avoided. For this reason, I also prefer POST for logouts as well.
The only time you should use GET is to request something for viewing, not deleting, editing, or adding data.
For this context it doesn't mather.
It mather when you have form items (text box, checkbox) or if you want to send information through POST instead of GET.
Form submit is when you want to submit the user defined values to the server . here in your example
<form class="delete" action="/post/delete/id/1234.html" method="POST">
<input type="submit value="delete this post"/>
</form>
in form submit you can enter you values that has to be submitted to the server for manipulation. Examples of when to use form submits are Login page. Registration page, ie when user defined values are to be submitted to the server
but in this example
<a class="delete" href="/post/delete/id/1234.html">delete this post</a>
you are not having a input interface for the user to enter values and submit to the server. These are used when you want to pass static values which are not user defined or mainly to redirect to another page.
Related
I am learning about protecting a website from unauthorized access and I have came across anti forgery. Here is my thought (and my problem I have with it). Please correct me if I am wrong.
Anti-forgery is in the ASP.NET MVC Applications handled (there might be many other ways, but this one is quite common) by inserting #Html.AntiForgeryToken() to the Form that is present on a webpage.
This token is afterwards used once user tries to POST the data to the system, where if we decorate our IActionResult or JsonResult method with [ValidateAntiForgeryToken] attribute, it checks whether the key matches the expected result. Here is an example of what I mean by decoration:
[Route("")]
[HttpPost("")]
[ValidateAntiForgeryToken]
public JsonResult UpdateRecords([FromBody]CustomRequest request)
{
if (ModelState.IsValid)
{
//...do some logic here
}
}
The reason why a webistes are using anti-forgery keys are, so that we do not want to allow unauthorized access to our business objects such as databases. The problem is, that if a website uses a cookie authentification, that is stored to a local cache, hackers can easily retrieve this stored value and use it when posting the data to our website. Due to that, we are implementing another level of protection, which is by inserting a special (unique) key to a webpage, which is being check upon posting the data. If the key is not matching, then the whole posting procedure fails.
Here is the thing I do not understand. Let's say that we have implemented our anti forgery on super simple form on our webpage like this:
<form method="post" ng-submit="addItem()" id="main-form">
#Html.AntiForgeryToken()
<input placeholder="Add New Item" ng-model="newItem" id="new-item" />
</form>
I know it does nothing, but let's imagine that by clicking the input button user tries to post some data to the database. If we inspect the webpage, we will suddenly see, that this is what the HTML generated code would look like:
<form class="ng-pristine ng-valid" method="post" ng-submit="addItem()" id="main-form">
<input name="__RequestVerificationToken" value="CfDJ8Ig8dRjRrw9FjKYv6kYaxVu7APOddjpVxQ3ZxGaamjVzV03eQEG7tgRe5q2uXJkKkbUf4RqzRCtJ1DGMK5C-ymroTBe_J9XQ-...(more text here )" type="hidden">
<input class="ng-pristine ng-valid ng-touched" placeholder="Add New Item" ng-model="newItem" id="new-item">
</form>
Now here, what I (and potential hacker) can see, is the special anti-forgery key we have just talked about. How come that this key is visible to anyone using the website? What I understand from this is, that we are basically serving our code to the hacker and he can now easily use it when posting to the database in order to authenticate himself; or am I wrong?
I am quite confused at the moment and therefore any help / info or recommendation regarding this matter would be more than appreciated.
The token is there to prevent people from falsifying form requests. It's also regenerated each time it's required - at least per-user and probably per-request (I am not sure on this last point). This means the attacker can't just copy their own token, or make it up; they would have to take it from the user's page and if they can do that then they probably have enough information to bypass the token anyway.
An attacker could craft a form on another website with some values and point it at a page on your website. If the admin submits this form (unwittingly through javascript, for example) then they have effectively just performed that action with their privileges and with the values specified by the attacker. This is bad, with sufficient knowledge you could trick someone into deleting an account, posting something obscene, etc.
I have created a form that contains the following within its <form> tag:
<input type="hidden" value="<?php echo $user_id ?>" name="author">
The problem I see here is that users can easily inspect element and change the value... and when doing so, affect how that value is processed in the form.
How do people make this type of form processing more secure so that users can't alter values?
The problem I see here is that users can easily inspect element and change the value... and when doing so, affect how that value is processed in the form.
Your application should not allow any such action without full server-side authorisation checks.
If the user is not supposed to be able to change the author value, you shouldn't even bother read the author value in the form submission, take the value you originally put into the form. If the user is supposed to have limited ability to change the author value (eg. only Administrator users can change the author), then check to see if the author value is allowed for the current user, and if it isn't then generate an error.
How do people make this type of form processing more secure so that users can't alter values?
The user is completely in control of what happens on the client-side, you can't make a browser take that control away from them. The security control must be on the server side.
(Some comments are suggesting encryption to protect a value given to a user, but this is much harder to get right than it looks. Applying an encryption function alone is no protection against tampering at all; to do that you need message signing and some connection between data in the signed message and the user/session and field purpose so the user can't just paste in an encrypted value they find elsewhere. Don't go this way until you really need to, the road is littered with corpses.)
<?php echo $user_id ?>
BTW you should use htmlspecialchars() when echoing any variable data into an HTML template otherwise you are vulnerable to HTML-injection (XSS).
I'm not the php crack but I would use something like
<input type="hidden" value="<?php echo encrypt($user_id, $secret) ?>" name="author"/>
where encrypt() should be a php encryption function (maybe How do you Encrypt and Decrypt a PHP String? will help...
On the server side you may use
$user_id = decrypt($POST["author"], $secret)
If conversion fails, somebody did something. To even harden your data, you could add some checksum field to cover the complete data set of hidden values. .NET ASP.NET does something similar with their data passed to the client as part of a form...
Consider:
<form action="?login" method="post"> <button>Login with Google</button> </form>
I usually see the action refer to a PHP or HTML file, but the "?login" stumps me.
Background information:
This is buried within the example-google.php file from lightopenid framework. I've been staring at the OpenID code to use Google as a third-party OpenID provider for user login on my web site and the sample code all works.
I am trying to get a clearer picture of what the framework is doing when the user presses the login button. I know that we must be sending a bunch of arguments to Google on this button action, but the ?login doesn’t seem to point anywhere.
http://gitorious.org/lightopenid
A question mark denotes the query string.
It will post to the current URL with a query string parameter of login. I am not sure how you are processing the request after you click submit (post the form), but usually it would have a value assigned to it as in login=value.
It means:
http://whatever/the-current-page-url-is?login (where "login" is the query string).
It is a relative-URI notation, similar to <img src="foo.jpg"> -- note the rest of the URI was not specified explicitly.
Happy coding
i am writing code to insert data into mysql on same page from where i retrive data by post method . it working fine but when i refresh page it will insert again.
my question is that how to stop reexcuting the insert query on refreshing page
This is being caused by the POST data being sent again when you refresh. Your browser should give you a warning that it's doing that. If you're not getting that warning, you might be using GET instead of POST which is not a good idea for actions which change or insert data.
Check your form has this attribute:
<form method="post">
If you want to avoid it altogether, just redirect the browser after the post back.
<?php
if ($_POST) {
// insert into database
header("location: thisPage.php");
// don't bother with die() here
}
Since the redirect is not being used for security purposes, and you're just redirecting back to the same page, it's not really necessary to die() afterwards.
You probably want to use the Post-Redirect-Get pattern to resolve this situation. It's good that you use POST to send data to your server. After you've done the necessary modifications, redirect your user to the page you want him to see, with a simple redirect-header. This will NOT break the back button, and a click on it will take the user back to the form, without sending the data again.
Add some variable to your form and then during saving reset it's value.
if(isset($_POST['save']))
{ //do your saving
$save="";
}
Say a user is browsing a website, and then performs some action which changes the database (let's say they add a comment). When the request to actually add the comment comes in, however, we find we need to force them to login before they can continue.
Assume the login page asks for a username and password, and redirects the user back to the URL they were going to when the login was required. That redirect works find for a URL with only GET parameters, but if the request originally contained some HTTP POST data, that is now lost.
Can anyone recommend a way to handle this scenario when HTTP POST data is involved?
Obviously, if necessary, the login page could dynamically generate a form with all the POST parameters to pass them along (though that seems messy), but even then, I don't know of any way for the login page to redirect the user on to their intended page while keeping the POST data in the request.
Edit : One extra constraint I should have made clear - Imagine we don't know if a login will be required until the user submits their comment. For example, their cookie might have expired between when they loaded the form and actually submitted the comment.
This is one good place where Ajax techniques might be helpful. When the user clicks the submit button, show the login dialog on client side and validate with the server before you actually submit the page.
Another way I can think of is showing or hiding the login controls in a DIV tag dynamically in the main page itself.
You might want to investigate why Django removed this feature before implementing it yourself. It doesn't seem like a Django specific problem, but rather yet another cross site forgery attack.
2 choices:
Write out the messy form from the login page, and JavaScript form.submit() it to the page.
Have the login page itself POST to the requesting page (with the previous values), and have that page's controller perform the login verification. Roll this into whatever logic you already have for detecting the not logged in user (frameworks vary on how they do this). In pseudo-MVC:
CommentController {
void AddComment() {
if (!Request.User.IsAuthenticated && !AuthenticateUser()) {
return;
}
// add comment to database
}
bool AuthenticateUser() {
if (Request.Form["username"] == "") {
// show login page
foreach (Key key in Request.Form) {
// copy form values
ViewData.Form.Add("hidden", key, Request.Form[key]);
}
ViewData.Form.Action = Request.Url;
ShowLoginView();
return false;
} else {
// validate login
return TryLogin(Request.Form["username"], Request.Form["password"]);
}
}
}
Just store all the necessary data from the POST in the session until after the login process is completed. Or have some sort of temp table in the db to store in and then retrieve it. Obviously this is pseudo-code but:
if ( !loggedIn ) {
StorePostInSession();
ShowLoginForm();
}
if ( postIsStored ) {
RetrievePostFromSession();
}
Or something along those lines.
Collect the data on the page they submitted it, and store it in your backend (database?) while they go off through the login sequence, hide a transaction id or similar on the page with the login form. When they're done, return them to the page they asked for by looking it up using the transaction id on the backend, and dump all the data they posted into the form for previewing again, or just run whatever code that page would run.
Note that many systems, eg blogs, get around this by having login fields in the same form as the one for posting comments, if the user needs to be logged in to comment and isn't yet.
I know it says language-agnostic, but why not take advantage of the conventions provided by the server-side language you are using? If it were Java, the data could persist by setting a Request attribute. You would use a controller to process the form, detect the login, and then forward through. If the attributes are set, then just prepopulate the form with that data?
Edit: You could also use a Session as pointed out, but I'm pretty sure if you use a forward in Java back to the login page, that the Request attribute will persist.