0% found this document useful (0 votes)
69 views12 pages

Bean Validation - OWASP Cheat Sheet

OWASP Cheat Sheet

Uploaded by

Rizki Kurniawan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
69 views12 pages

Bean Validation - OWASP Cheat Sheet

OWASP Cheat Sheet

Uploaded by

Rizki Kurniawan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 12
9123/22, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series Bean Validation Cheat Sheet Introduction This articleis focused on prcviding clear, simple, actionable guidance for providing Java Bean Validation security functionality in your applications. Bean validation (JSR303 aka Bean Validation 1.0 /JSR349 aka Bean Validation 1.1) isoneof the most common ways to perform input validation in Java. It isan application layer agnostic validation spec which provides the developer with the means to define a set of validation constraints on a domain model and then perform validation of those constraints through out the Various application tiers. One advantage of this approach is that the validation constraints and the corresponding Validators are only written once, thus reducing duptcation of effort and ensuring uniformity: Typical Validation lolitas Custom Validation calcd} te uN eect ETT Cte Natl Data Access Gre uN leetcul ‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html ane 9123/22, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series Bean Validation Tur ele PT pele Vac} Setup The examples in this quide use Hibemate Validator (the reference implementetion for Bean Validation 1.1). ‘Add Hibemate Validator to your pom.xml: org.hibernate S.2.4.Final Enable bean validtion support in Spring's context.xml: For more info, please see the setup guide Basics ‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html 9123122, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series In ofderto get started using Bean Validation, you must add validation constraints (ePattera, evigits, @Min, OMex, @Size, éPast, GFuture, OCreditCardNunber , @Fmail, eURL ,etc) to your model and then utiize the @va1id annotation when passing your model around in various application layers. Constraints can be applied in several places: + Fields + Properties + Classes For Bean Validation 1.1 also on: + Parameters + Retum values © Constructors For the sake of simplicity all the examples below feature field constraints and all validation is triggered by the controller. Refer to the Bean Validation documentation for a fulllist of exemples. When it comes to ertor handing, the Hibemate Validator retums @ Bindingesutt object which containsa List<0bjectError> . The examples belaw feature simplistic error handing, while a Production ready application would have a more elaborate design that takes care of loggingand error page redirection. Predefined Constraints @Pattem Annotation: @Pattern(regex=, flag=) Data Type: CharSequence Use: Checks if the annctated string matches the regular expression regex considering the given flag match. Please visit OWASP Validation Regex Repository for other useful regex's. ‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html az 9123/22, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series Reference: Documentation Model: import org.hibernate. validator .constraints.Pattern; public class Article { /1Constraint: Alpha Numeric article titles only using a regular expression @Pattern(regexp = "[a-zA-20-9 |") private String articleTitle; public String gotarticleTitie() { return articleTitle; , public void setArticleTitle(String articleTitle) { this.articleTitle = articleTitle; , } Controller: import javax.validation. Valid; import com.conpany..app.model.Article; econtroller public class ArticleController { ‘@RequestHapping(value = "/postarticle", method = RequestHethod. POST) public @ResponseBody String postArticle(@Valid Article article, BindingResult result, HttpServietResponse response) { if (result.hasErrors()) { String errorMessage = ""; response..setStatus (Ht tpServletResponse..SC_BAD_REQUEST List errors = result.getAllerrors(); for(ObjectError e : errors) { errorHessage 4= “ERROR: " + e.getDefaultMessage() ; eee }eise { return “Validation Successful" , ‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html 9123122, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series @bigits Annotation: epigits integers, fraction=) Data Type: BigDecinal, Biginteger , CharSequence, byte, short, int, long andthe respective wrappers of the primitive types; Additionally supported by HV: any sub-type of Number Use: Checks whether the annctated value is a number having up to integer digits and fraction fractional digits Reference: Documentation Model: import org.hibernate. validator .constraints.Digit: public class Customer { //Constraint: Age can only be 3 digits long or less eDigite(integer = 3, fraction = 8) private int age; public String getAge() { return age; } public void setAge(String age) { this.age = age; } Controller: import javax.validation.Vali import com.conpany .app.model.Custoner ; econtroller public class CustomerController { ‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html 9123/22, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series @RequestMapping(value = “/registerCustoner”, method = RequestMethod.POST) public #ResponseBody String registerCustoner (@Valid Customer customer, BindingResult result, HttpServietResponse response) { if (result.hasErrors()) ‘String errorMessage = *"; response. setStatus(HttpServletResponse .SC_BAD_REQUEST) ; List errors = result.getAllerrors(); for( ObjectError e : errors) { errorMessage += "ERROR: " + e.getDefaulMessage(); , return errorMessage; }else { return “Validation Successful” ; , , + ‘Annotation: esize(mine, max=) Data Type: CharSequence , Collection, Map and Arrays Use: Checks ifthe annctated element's size is between min and max inclusive) Reference: Documentation Model: import org.hibernate. validator .constraints.Siz: public class Message { /[onstraint: Message must be at least 1@ characters long, but less than 580 @size(min = 18, max = 500) private String message; ‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html 9123/22, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series public String getMessage() { return message; d public void setMessage(String message) { ‘this.message = message; d Controller: import javax.validation. Valid; import com.conpany .app.model.Message; econtroller public class NessageController { eRequestMapping(value="/sendMessage", method=RequestMethod POST) public @ResponseBody String sendMessage(@Valid Message message, BindingResult resul HetpServletResponse response){ if(result hasErrors()){ String errorMessage = ""; response .cetStatus (HttpServietResponse .SC_EAD_REQUEST) ; List errors = result.getAllerrors() ; for( ObjectError e : errors){ errorvessage+= "ERROR: * + e,getDefaultMessage(); + return errorMessage; d else{ return "Validation Successful" ; d @Past / @Future Annotation: ePast, eFuture Data Type: ‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html m2 9123/22, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series java.util.Date, java.util.Calendar, java. time.chrono.ChronoZonedDateTime , java.tine.Tnstent, java. tine. OffsetdateTine Use: Checks whether the annctated date ‘the past /future Reference: Documentation Model: import org.hibernate. validator .constraints.Past; import org.hibernate. validator .constraints.Future; public class poctorVisit { //Constraint: Birthdate must be in the past private Date birthbete: public Date getBirthoate() { return birthdate; , public void setBirthdate(Date birthDate) { this-birthDate = birthdate; , //constraint: Schedule visit date must be in the future Future private String scheduledVisitbate; public String getScheduledvisitDate() { return scheduledVisitDate; , public void setScheduledVisitbate(String scheduledvisitDate) { this.scheduledVisitDate = scheduledVisitbate; d Controller: import javax.validation. Valid; import com.company .app.model .DoctorVisii ‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html 9123/22, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series econtroller public class DoctorVisitController { ‘eRequestNapping(value="/scheduleVisit", metho vequestMethod POST) public @ResponseBody String scheduleVisit(eValid DoctorVisit doctorvisit, BindingRe HttpServietResponse response) { if (result hasErrors()){ ‘String errorMessage response. setStatus(HttpServletResponse SC_BAD_REQUEST) ; ListeobjectError> errors = result getAllerrors(); for( ObjectError e : errors){ errorMessaget= "ERROR: " + e.getDefaultMessage() ; , return errorMessage; + else{ return "Validation Successful" ; + , + Combining Constraints Validation annotations can be combined in any suitable way. For instance, to specify avaid reviewRating valve between 1 and 5, specify the validation like this: Annotation: @Min(value=), @Max(value=) Data Type: BigDecinal, BigInteger, byte, short, int, long andthe respective wrappers of the primitive types; Additionally supported by HV: any sub-type of charsequence (thenumetic value represented by the character sequence is evaluated), any sut-type of Number Use: Checks whether the annctated value is higher/lower than or equal to the specified minimum Reference: Documentation ‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html enn 9123/22, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series Model: import org.hibernate.validator .constraints.Min; import org.hibernate.validator .constraints.Max; public class Review { //Constraint: Review rating mist be between 1 and 5 omin(1) ovax(8) private int reviewRatin public int getReviewRating() { return reviewRating; , public void setReviewRating(int reviewRating) { this. reviewRating = reviewRatin: Controller: Amport Javax.validation. Valid; Amport com.conpany .app.mode1.ReviewRating; econtroller public class ReviewController { GRequestNapping(value="/postReview", method=RequestMethod..POST) public @ResponseBody String postReview(@Valid Review review, BindingResult result, HttpservietResponse response) { if (result -hasErrors()){ String errorkessage = ""; response. setStatus(HttpServletResponse.SC_BAD_REQUEST) ; List errors = result getALlErrors(); for( ObjectError e : errors){ errortessaget= “ERROR: " + e.getDefaultMessage() ; } return errorMessage; + else{ return “Validation Successfu: + ‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html 9123122, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series Cascading Constraints Validating one bean is a good start, but often, beans are nested or in acomplete graph of beans. To validate that graph in one go, apply cascading validation with @Valid Additional Constraints In addtion to providing the complete set of JSR303 constraints, Hibemate Validator also defines ‘some additional constraints for convenience: © ecreditcardNunber = 8EAN * e€nail © eLength © eRange + eSafeHteml * @Seriptassert = ouRL Take a look at this table for the complete list. Custom Constraints One of the most powerful features of bean validation is the ability to define your own constraints: that go beyond the simple validation offered by builtin constraints. Creating custom constraints is beyond the scope of this guide. Please see this documentation. Error Messages Itis possible to specify a message ID with the validation annctation, so that error messages are customized : ‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html sine Bean Validation - OWASP Cheat Sheet Series erattern(regexp = “Ia-z4-20-9 |", message="article.title.error*) privete String articleTitle; Spring MVC will then look up a message with ID article.titfe.errar in a defined MessageSource. More on this documentation. ‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html

You might also like