SpringBoot WebMvcConfigurer.addInterceptors() - java

in SpringBoot2.0.0.RELESAEversion
use WebMvcConfigurer configure MyWebMvcConfigurer
#Configuration
public class MyMvcConfig implements WebMvcConfigurer{
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new TestHandlerInterceptors()).addPathPatterns("/**");
}
}
public class TestHandlerInterceptors implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return false;
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
static resource cannot be loaded when preHandle method returning false

Instead of implementing WebMvcConfigurer, you can extend WebMvcConfigurerAdapter Which will give you default implementation.
For static resources, you can override as below.
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations(new String[] {"classpath:/","classpath:/public/"});
}

Related

Send a Spring Boot websocket message after connection

I need to send a websocket message to the user after the handshake, without waiting the user to send something.
I tried to use afterHandshake in a HandshakeInterceptor, however possibly the user is not identified yet.
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
private final ApplicationContext applicationContext;
WebSocketConfig(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/reply");
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setHandshakeHandler(new UserHandshakeHandler())
.addInterceptors(new MessagesHandshakeInterceptor(applicationContext));
}
}
public record MessagesHandshakeInterceptor(
ApplicationContext applicationContext) implements HandshakeInterceptor {
#Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler handler, Map<String, Object> attributes) {
return true;
}
#Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler handler, Exception exception) {
//send the message to the user
applicationContext.getBean(SimpMessagingTemplate.class)
.convertAndSendToUser(user, "/reply", message);
}
}
public class UserHandshakeHandler extends DefaultHandshakeHandler {
#Override
protected Principal determineUser(ServerHttpRequest request, WebSocketHandler handler,
Map<String, Object> attributes) {
return () -> userId;
}
}

Interceptor not working in Spring Boot GraphQL

Im using graphql-java-kickstart/graphql-spring-boot and I'd like to create an interceptor to add an HTTP header after processing the request.
When I'm sending a graphql request to the backend the the interceptor is not triggered. But some calls trigger the interceptor. For example when I'm opening /graphiql in my browser I see that the interceptor is triggered but when I send a graphql request from graphiql client it is not. Any idea why? Anybody got experience with this?
My config looks like this:
#Configuration
public class InterceptorConfig implements WebMvcConfigurer {
#Autowired
private TestInterceptor testInterceptor;
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(testInterceptor).addPathPatterns("/**");
}
}
Also my Interceptor:
#Slf4j
#Component
public class TestInterceptor extends HandlerInterceptorAdapter {
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
// post processing
log.info("hello there");
}
}
I have following interceptor that successfully works in my project:
My WebConfig:
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(requestInterceptor);
}
#Autowired
private ControllerExecInterceptor requestInterceptor;
}
Where ControllerExecInterceptor defined as:
#Component
public class ControllerExecInterceptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws AccessDeniedException, Exception {
// ...
}
#Override
public boolean postHandle(HttpServletRequest request, HttpServletResponse
response, Object handler) throws {
// ...
}
}

Configure WebRequestInterceptor in Spring Configuration

I am trying to use WebRequestInterceptor but i don't know how can i configure it in spring boot, as if I implement WebMvcConfigurer interface it requires a HandlerInterceptor object so i cannot assign my interceptor to it. Any help would be highly appreciated.
Interceptor class:
public class CustomerStateInterceptor implements WebRequestInterceptor {
#Resource(name = "customerStateRequestProcessor")
private CustomerStateRequestProcessor customerStateRequestProcessor;
#Override
public void preHandle(WebRequest webRequest) {
customerStateRequestProcessor.process(webRequest);
}
#Override
public void postHandle(WebRequest webRequest, ModelMap modelMap) {
//unimplemented
}
#Override
public void afterCompletion(WebRequest webRequest, Exception e) {
//unimplemented
}
}
and config class:
#Configuration
public class InterceptorConfig implements WebMvcConfigurer {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CustomerStateInterceptor()); // <-- Error here.
}
}
You supposed to implement HandlerInterceptor from org.springframework.web.servlet package and not WebRequestInterceptor.
Update
You can just wrap with WebRequestHandlerInterceptorAdapter:
#Configuration
public class InterceptorConfig implements WebMvcConfigurer {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(
new WebRequestHandlerInterceptorAdapter(
new CustomerStateInterceptor()));
}
}
Add filter class to your package and please try the code below -
public class RequestValidateFilter extends GenericFilterBean {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
try {
request = new RequestWrapper(httpServletRequest);
chain.doFilter(request, response);
} catch (Exception e) {
throw new ServletException();
}
}
}
FilterClass :
#Configuration
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.addFilterBefore(requestValidateFilter(), BasicAuthenticationFilter.class);
http.authorizeRequests().antMatchers("/projectname/**").authenticated();
http.addFilterAfter(responseValidateFilter(), BasicAuthenticationFilter.class);
}
private RequestValidateFilter requestValidateFilter() {
return new RequestValidateFilter();
}
private ReponseValidateFilter responseValidateFilter() {
return new ReponseValidateFilter();
}
}

postHandle method is not invoking after http request handling

I've created following component to add X-Frame-Options into each response:
#Component
public class SecurityInterceptor extends HandlerInterceptorAdapter {
#PostConstruct
public void init(){
System.out.println("init");
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
response.addHeader("X-Frame-Options", "DENY");
}
}
method init executes on startup thus spring knows about this.
Also I have following rest service:
#PostMapping("/rest_upload")
public DeferredResult<ResponseEntity> upload(#RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
final DeferredResult<ResponseEntity> deferredResult = new DeferredResult<>();
...
return deferredResult;
}
Unfortunately postHandle method is not invoking.
How can I correct it?
Spring knows about your Interceptor as just a bean and nothing more. You need to register it with InterceptorRegistry so that it is called as part of interceptors.
#Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Autowired
SecurityInterceptor securityInterceptor;
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(securityInterceptor);
}
}
You need a configuration class that extends WebMvcConfigurerAdapter and overrides the addInterceptor method:
#Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new SecurityInterceptor());
}
You also need to make sure you have enabled WebMvc in Spring.

Override the Query String using a Servlet Filter

I have a requirement where I need to to decrypt the query string. I am planning to do it via Servlet Filter and extending HttpServletRequestWrapper as shown below.
#WebFilter(filterName = "urlDecryptionFilter", urlPatterns = {"/*"})
public class UrlDecryptionFilter implements Filter {
static class FilteredRequest extends HttpServletRequestWrapper {
public FilteredRequest(ServletRequest request) {
super((HttpServletRequest)request);
}
public String getQueryString() {
//here i put the logic to transform the existing string
return "quertStr=modified";
}
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(new FilteredRequest(request), response);
}
#Override
public void destroy() {
}
}
But this doesn't seem to be working. I would appreciate if anyone can point in the right direction.

Categories

Resources