i want to know is there a way to get the HttpServletRequest body before any Jackson involvement in spring. I tried it with #JsonDeserializer and spring HandlerInterceptorAdapter and also with a HttpRequestWrapper but no luck for now. if anyone knows please suggest me a way to do this thanks.
You can add a custom Filter in the application (explained here) and override doFilter method. E.g.:
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain){
....
}
This would give you the request object from which, you can get the payload.
Related
I have a simple blog webpage with a lot of links. They are all using GetMapping. Therefore whenever I have a bot try to access those pages using POST I get an error saying
Request method 'Post' not supported.
I understand that this is caused because I use #GetMapping, and if I switch to #RequestMapping then everything will be fine. However I do not want to allow anyone to access my blog with POST. The only page that should be POST is /contact/message except that page everything should be accessed through GET.
So I have two questions:
How do I enforce people to use GET only.
How do I catch attempts to use POST and redirect them to /error?
Sidenote: I do not use spring security, there is no logging in or anything that is hidden behind an account. Also most of my mappings are using regex. Do not know if this info is of any help or not.
#GetMapping(value = {
"", "{page:^[1-9][0-9]*$}", "{section:^\\d*[a-zA-Z][a-zA-Z0-9]*[^.]+$}",
"{section:^\\d*[a-zA-Z][a-zA-Z0-9]*[^.]+$}/{page:^[1-9][0-9]*$}"})
You can add a filter in your application:
public class Tfil implements Filter {
#Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
if (!"GET".equals(req.getMethod())) {
//redirect or error page
HttpServletResponse res = (HttpServletResponse) servletResponse;
//here redirect
res.sendRedirect("redirect url");
//or return 404 code
res.setStatus(404);
}
filterChain.doFilter(servletRequest,servletResponse);
}
}
I am learning how secure my endpoints, but everything i searched for contains pretty complicated examples, that didn't really answerd my question, and for now, just for the sake of this example project, i was looking for something simple.
My current solution is to make endpoints return like this:
return authenticate(request.headers) ? cityService.getCity() : utils.unauthenticatedResponse();
Where authenticate(request.headers) checks for token in header.
The thing i want to improve is to have that authenticate method run before every request to my endpoints (aside from login and register), so i can just return cityService.getCity(), and i won't have to make that check every time.
Will appreciate every answers, but please make it easy yo understand, since i am just a beginner.
Since you need to run the authenticate method before every request, you need to implement a Filter. It's pretty straightforward and you can get the steps and template to implement a filter here.
Every request to an endpoint will first pass through the filter (this is configurable), where you can have the authenticate method and then allow it further accordingly.
For starters, you can implement a filter like below:
#Component
public class AuthFilter implements Filter {
#Override
public void doFilter
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if(authenticate(req.getHeaders)){
chain.doFilter(request, response);
} else {
//else logic, ie throw some exception in case authenticate returns false
}
}
}
The advantages that this provides are :
You can implement multiple filters
You can provide Order/priority to filters
You can configure which endpoints need to pass through the filter and which ones do not.
You can use ContainerRequestFilter (if you are using Spring/Tomcat)
Every request coming to the server will go through this filter, so you can implement your code in it.
I have ServletRequest, which client machine sent. How to know which one it is: GET POST UPDATE or DELETE?
HttpServletRequest contains getMethod() which returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT
If you are using Spring MVC and your comunication protocol is HTTP, you don't need use ServletRequest, you can use directly HttpServletRequest in your method like this:
public ModelAndView index(HttpServletResponse response, HttpServletRequest request)
But if you need use ServletRequest and you are sure your comunication protocol is HTTP you can cast your ServletRequest to HttlServletRequest and use getMethod() like Shriram said.
I need to change the serverName of the ServletRequest object in my Grails controller. I'm having trouble figuring out how to do this since the serverName is a read-only property.
The most correct thing to do is probably to set up a clever filter or redirect which "fixes" your request URL before your servlet even gets involved. I know nothing about how to do that; you should ask on serverfault.com if you want to do that.
In java, you can fake it by creating your own subclass of HttpServletRequestWrapper which provides setServerName() and overrides getServerName() while delegating all other methods to the superclass. You can then provide a filter which creates an instance of your request and sends that one down the chain.
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
YourHttpServletRequest yourRequest =
new YourHttpServletRequest(request, newServerName);
chain.doFilter(yourRequest, response);
}
If I understand this correctly, CORS filter might help
I've used http://software.dzhuvinov.com/cors-filter.html in my previous project.
But you can also lookup on github for example https://github.com/eBay/cors-filter
i want remove all "\n" for JSP page output.
i think i should be using a Filter for this.
but i dont know how to do
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)throws IOException, ServletException {
//how to remove all "\n" for output?
}
any idea? thanks for help :)
BalusC has a post showing such a filter. Check here
This question shows other options for trimming whitespaces.
To get access to the response generated by a resource, you need to wrap the HttpServletResponse object. i.e. change the response object that is passed to the doFilter()
method of the FilterChain object. The custom wrapper can buffer up all the output from your resource (JSP/Servlet) which can be accessed and changed before sending it back to the client.
You can use simple String.replaceAll() method to replace all \n's.
You can use the HttpServletResponseWrapper class to wrap the response object. Take a look at filter tutorial. This book also gives clear instructions on how to modify a response from a Filter. See section 9.9 of the book.