What the difference between [FromForm] and [FromBody] in Asp.Net Core. I will use one of them for post method. If I use FromForm, can it occur be a security problem?
-
1Docs explain it best learn.microsoft.com/en-us/aspnet/core/mvc/models/…– NkosiAug 22, 2019 at 20:56
-
If I use FromForm, can it occur be a security problem?– SUAT SUPHIAug 22, 2019 at 21:25
-
That is a "it depends" kind of question which is too broad to answer here.– NkosiAug 22, 2019 at 21:40
3 Answers
The FromForm
attribute is for incoming data from a submitted form sent by the content type application/x-www-url-formencoded
while the FromBody
will parse the model the default way, which in most cases are sent by the content type application/json
, from the request body.
For security problem , you could use ValidateAntiForgeryToken
Attribute for post method which specifies that the class or method that this attribute is applied validates the anti-forgery token. If the anti-forgery token is not available, or if the token is invalid, the validation will fail and the action method will not execute.
The anti-forgery token found in MVC is a way to prevent cross site request forgery (CSRF) attacks. Without going into too much detail, a CSRF attack occurs when a user visits an untrusted site and enters some information that is then posted back to a site to which the user has already authenticated.
You could refer to the following link on how AntiForgeryToken() actually works:
-
2Any word of advice on what good practice should be for using one versus the other on a typical REST service interface? Dec 11, 2019 at 16:33
-
I am curious of this as well. Should Restful always use FromBody since its suppose to be in the body of the request? 3 hours ago
FromBody (ContentType: application/json):
{ "user" : "conejo", "password" : "panda" }
FromForm (ContentType: application/x-www-url-formencoded):
user=conejo&password=panda
Take into account that to send more than one field using FromBody you would have to wrap them in an object. As per se, FromForm is not less secure than FromBody. Vulnerabilities mainly come from not using HTTPS
If you look in the Microsoft documentation
- [FromQuery] - Gets values from the query string.
- [FromRoute] - Gets values from route data.
- [FromForm] - Gets values from posted form fields.
- [FromBody] - Gets values from the request body.
- [FromHeader] - Gets values from HTTP headers.