How to prevent xss from java api side - java

I have REST API with Java Springboot 2.1.5.RELEASE and need to prevent every controller to check first the RequestBody contain XSS or not. if yes I want to return like BadRequest. The App only for API no HTML, JSP and etc
Here is sample my controller
#PostMapping("/test1")
public ResponseEntity<ResponseModel> process(#Valid #RequestBody Student request)
I've tried with some library to check Student to Json and clean the XSS like https://github.com/OWASP/json-sanitizer/ and etc
but still, doesn't work
and Already check https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
but still not found about implement in java api
I expect every request to API reject/return 400(BadRequest)
The validation can be on Controller, Filter, Interceptor or Spring Security

Related

Grails 2.4.5 Rest API GET Request: Can't get Response Body from CUrl and from React UI, but can get it from Postman and Browser

Grails 2.4.5 REST Controller returning List of non Domain object DTO
What's the best way to turn a method/action into a REST Resource accessible through a GET request, without returning a domain class/entity, but with a non-domain/entity DTO class?
With SpringBoot, it will look like this:
#RestController
class EmployeeController { ...}
/**
**I am not sure that even in Spring/SpringBoot you can return a list of non entity class DTO.
** Can you return a random non entity
**/
#GetMapping("/employees")
List<EmployeeDTO> all() {
return repository.findAll();
}
For my Grails project, I am trying to return a list of DTO object having data from different domain/entities. Since the class is not a Grails domain class, how do you do that, since it doesn't follow the Grails convention?
I have the code as below:
class ClassNameController extends RestfulController{
/**
** Grails usually wants you to use call the parent constructor and and put a domain class as
** a parameter like super (DomainClass).
** In my case, since I have a non-conventional Controller which combines different data
** sources/domains/entities, how do I implement my method/action to turn it into a Grails REST
** Resource?
** Is there an annotation like #RestController, #ResponseBody and #GetMapping in Grails or can they be used in Grails too, since Grails 2.4.5 is built on top of Spring?
**/
/**
** I used just one of the multiple domain/entity classes as a parameter to the parent constructor,
** in order to follow that convention like this below.
**/
ClassNameController(){
super(OneDomainClassOutOfTheManyDomainClassesInsideDTOClass)
}
List<ClassDTO> getAllDTOs(){
//allClassDTOs() is a private method inside same controller returning a list of all classDTOs
List<ClassDTO> classDTOsList = allClassDTOs()
respond classDTOsList, status: 200
}
With that code, I can see the data displayed in Postman as well as inside the browser. However, I am not able to see the data when testing with CUrl, somehow looking at the log, Grails considers the request as successful and redirect to the home page. I am not sure why that's the case. I even removed any security to see if it was due to the Oauth Access token, but I can see that it's not the case, as even with #Secured(['IS_AUTHENTICATED_FULLY']), I can see in the logs of Spring Security that the user has been authenticated successfully and the authorization access has been granted successfully.
Pretty much, I am looking for a sample example of a simple Grails REST API that doesn't use the Grails convention and returns a non domain object.

Spring Thymeleaf Html form + Crud Operations

I'm new to Spring Framework and currently trying develop an simple application were restaurant owners can add a dish to a main database through logging in and imputing the dish data into a Html form (with Thymeleaf). (dish name, price, gluten free = true etc.)
App users should then be able to search the main database based on their location and dietary requirements etc.
I'm trying to learn through Youtube tutorials however, all of them seem to use #RestController and #Requestbody and use Postman to send JSON requests. I'm having difficulty adapting this to my Html form.
I have used the #controller annotation for simple 'save' methods but when I research 'how to include a foreign key in the data added to the data base' (i.e. include 'restaurant id' as foreign key in the 'dish' class), all of the tutorials use #RequestController and JSON requests in Postman.
As I'm trying to build a usable application sending requests in Postman doesn't seem like a good solution.
I think the problem I'm according to other posts is the following:
"If you use template engine like Thymeleaf it will not work with #RestController because of #ResponseBody which included in this annotation" – Sonique
"#ResponseBody makes the returned objects to something that could be in the body, e.g. JSON or XML" – Martin Thoma
I've tried removing #RequestBody and changing it to #RequestParam but I get errors.
Are there any work-arounds to my issue? E.g. using a different file format for the 'add new dish' form or not using Thymeleaf?
Any help/advice would be very much appreciated!
If you want to use HTML with Thymeleaf and the class should annotate by #Controller and the method parameter that handle the object from the FORM you want to control should be #ModelAttribute("").

Use checkstyle to force a parameter to be present on any method with specific annotation

I want that all my rest services has as an input parameter HttpServletRequest httpRequest that I need later for some loggin purposes. This parameter sometimes is forgotten to be added and some methods are not logged. As are all rest services, and I am using Spring, all of them has some very specific annotations. I was thinking on using checkstyles to force the parameter to be present.
A little more of explanation of want I want to achieve. I am developing some rest servicies, and I am interested on logging some header that are sent to the rest services with some extra information. For this purpose, I have added HttpServletRequest request to each rest services as follows:
#GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
public Status get(HttpServletRequest request, #PathVariable("id") Integer id) {
....
}
This paremeter is correctly retrieved and I can read the headers correctly (everything automated using AspectJ). My problem now is that is for a new rest service, I forgot to add the parameter, no logs will be shown. As the parameter is optional (you can or cannot add to the rest service without any error) and all logging is automated by AspectJ, is possible that I can forget it for future rest services and no notice the miss until late.
The scope is to ensure that always is present in all my rest services. My first thought was using checkstyle as I am already using for other different purposes.
Is it possible using checkstyle or any similar tool to force that a parameter is present on any method that has an annotation? If not, there is any other different way to achive my objective?

Validating REST Request using RequestBodyAdvice

Im trying to use RequestBodyAdvice in Spring Boot application to validate my JWT token and Device info. It works for POST method as it has #RequestBody in Controller however it is not working for GET method because there is no request body/payload. How to validate GET Services using RequestBodyAdvice, is there any other option?
As far as I know, GET request do not have request body. You should use interceptor or filter.

Any simple way to test a #RequestBody method?

If I have a #Controller method whose parameter is a #RequestBody param, I usually have to write some jQuery script or something similar to perform an AJAX request with JSON object in order to call that method. If I tried calling that method via a web browser directly, it returns with a Error 415 Unsupported Media Type.
Is there any alternative to just quickly call such method using browser without having to write some jQuery code? Like perhaps a way to write the JSON object in the URL/address bar?
code:
#RequestMapping("testCall")
#ResponseBody
public List<TestObject> getTestCall (#RequestBody TestParams testParams) {
return stuff;
}
public class TestParams {
private Integer testNumber;
//getter/setter for testNumber
}
I thought maybe I could just do:
http://localhost/testCall?testNumber=1
maybe Spring would auto populate a new TestParams instance with that property set to 1 but that didnt work...
maybe I need to do something extra for that?
The whole point of a #RequestBody annotated parameters is for the Spring MVC stack to use the HTTP request body to produce an argument that will be bound to the parameter. As such, you need to provide a request body. Sending a request body is very atypical for a GET request. As such, browsers don't typically support it, at least not when simply entering an address in the address bar and submitting the request.
You'll need to use a different HTTP client, like jQuery. I typically have a small Java project in Eclipse that's setup with an Apache HTTP components client which can send HTTP requests to whatever server. It takes a few seconds/minutes to setup the correct request body and run.
I have spent the last year building a REST API, and by far the best way to exercise that API manually is using the Chrome Extension, Postman. I cannot recommend this tool enough.
https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
To test your simple example you'll need to invoke a POST (I assume that as you have a request body, but your controller method doesn't define a HTTP Verb) using POSTMAN to your Url (like the following example):
POST /contextRoot/testCall
{
"testNumber": 1
}
If you want to test your API automatically (which I recommend), you can use the excellent Spring Mvc Test project. This allows your to call your API via a rest-like DSL and assert that the response is in the shape you want. More details can be found here:
http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/testing.html#spring-mvc-test-framework
you can add request params to the getTestCall method:
#RequestParam(value = "testNumber", required = false, defaultValue = "") String testNumber
There is a chrome app called Advanced REST client. You can pass the data in form of json to your controller using this chrome app. For eg. json data is
id:1,
name:"xyz"
whereas the controller can have #RequestBody Person form.
The Person class would be a POJO having id and name as instance variables. The Spring would automatically map the json data to the form.
I think this is the easiest and simplest way of checking your spring controller.
Check the extension Advanced REST client here
From what I know You can send JSON object to the webbrowser and it will be displayed without further need of AJAX.
useful tutorial:
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/

Categories