JSF 2 AJAX Response Cache - ajax

When I use JSF 2 Ajax, how do I control whether the response is cacheable. If that's possible, how do I control the expry date of the AJAX response? Thanks! -- Charlie

As is typical for JSF applications, the caching headers are set via a Filter, which is part of the Servlet layer. For this layer there is no automatic difference between a normal request and an AJAX request.
JSF however marks requests as AJAX requests by means of the javax.faces.partial.ajax request parameter. (see JSF spec section 14.2.4)
If you thus want to specifically control the response headers for all JSF AJAX requests, you would do something like:
#WebFilter(filterName="httpHeaders", urlPatterns="/*")
public class HTTPHeaders extends Filter {
#Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
if (request.getParameter("javax.faces.partial.ajax") != null) {
response.setHeader("Cache-Control", "...");
response.setDateHeader ("Expires", "...");
response.setHeader("Pragma", "...");
}
chain.doFilter(request, response);
}
}

Related

Add response header in HandlerInterceptorAdapter

I am adding a header to the response inside HandlerInterceptorAdapter.
However it seems that the response header cannot be modified in the postHandle method.
public class CredentialInterceptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
return true;
}
#Override
public void postHandle(HttpServletRequest request,HttpServletResponse response,Object handler,ModelAndView modelAndView) {
String value = "...";
response.addHeader("header_name",value ); // doesn't work
}
}
How to add a header to the response ?
Popular solution is to use OncePerRequestFilter ( Set response header in Spring Boot ). Isn't there any other way ?
The problem with adding headers in the postHandle method is that the response may already be (partially) send. When that is the case you cannot add/change headers anymore. You need to set the headers before anything is sent to the client.
This you can do in the preHandle method or more generic a servlet filter before you call filterchain.doFilter. Doing it after the aforementioned call you might get the same issue that a response has already (partially) been sent.

Springbook 2.0 interceptor forward to controller

I am building a small application in which I am trying to manage user login session.
My question is, is it possible to forward the http request from HandlerInterceptor.preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) method to controller
Something like this..
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
request.getRequestDispatcher("someController").forward(request, response);
return true;
}

How to get raw JSON message from request and HTTP status code from response

I am developing a Spring Boot application. We have a requirement to store raw JSON request and HTTP response code to store in database as part of processing the request.
We are able to intercept request in a class that extends RequestBodyAdviceAdapter. This class has implemented afterBodyRead method to get body of the request. Unfortunately there is no way to get the raw JSON request in this method.
Similarly we have another class that has implemented ResponseBodyAdvice to intercept response. In beforeBodyWrite method, response status code is not available.
You can write a simple servlet filter:
#Component
public class JsonFilter implements Filter {
#Override
public void doFilter
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
// Log JSON request
chain.doFilter(request, response);
// Log JSON response and HTTP Status code
}
// other methods
}
Read more about filters and Spring Boot here: https://www.baeldung.com/spring-boot-add-filter

Spring boot 2 adding cache response headers without using Spring security

I am using Spring boot 2 and in application.properties file, I have specified the cache values as below :
spring.resources.cache.cachecontrol.max-age=0
spring.resources.cache.cachecontrol.no-cache=true
spring.resources.cache.cachecontrol.must-revalidate=true
spring.resources.cache.cachecontrol.no-store=true
Except for max-age, none of the headers is visible in the chrome developer tools network tab.
In my application I am making a Get request and getting ResponseEntity<Long> as response back.
Is there something else needs to be done to add these cache-headers in the response ?
I used filter for setting HttpHeader. It can give you fine grained control over setting value and validate your request before passing to controller.
public class CORSFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.setHeader("Access-Control-Max-Age", "3600");
res.setHeader("Access-Control-Allow-Headers",
"X-PINGOTHER,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
res.addHeader("Access-Control-Expose-Headers", "xsrf-token");
res.setHeader("Cache-Control","no-cache,no-store,must-revalidate,private,max-age=0");
res.setHeader("Pragma","no-cache");
res.setDateHeader("Expires",0);
if(!res.containsHeader("X-FRAME-OPTIONS"))
res.addHeader("X-FRAME-OPTIONS", "SAMEORIGIN");
if ("OPTIONS".equals(req.getMethod())) {
res.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
}

Spring security & Wicket + filters

the main approach to use when securing Wicket application using Spring security is to include such construct in AuthenticatedWebSession:
Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(username, password));
SecurityContextHolder.getContext().setAuthentication(authentication);
authenticated = authentication.isAuthenticated();
In opposition to Spring Security authentication request comes within a backend so there is too late for any HTTP Request processing. That said entire Spring Security filter chain is DOWN no-matter what, see this line in the AbstractAuthenticationProcessingFilter:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (!requiresAuthentication(request, response)) {
chain.doFilter(request, response);
return;
}
// (...) "normal" Spring authentication process which will never take place
successfulAuthentication(request, response, chain, authResult);
}
Where the requiresAuthentication method checks for the "j_spring_security_check" on the request path. Of course there isn't any in the approach taken.
What's the consequence? Since you rely ONLY on the AuthenticationManager you obtain from the application context itself actions that would normally be triggered in the filter chain just won't happen: for instance Spring remember-me services won't work. Cookies are being set in the filter method which returns prematurely. Cookies can be read, but they do not exist.
And my question is - is there a serious Spring Security to Wicket adaptation or not? I mean it should skip the chain but trigger all those actions which would normally be run from within the backend, as Wicket does.
Thanks!

Resources