4
votes
@RestController
@RequestMapping("/api")
public class AbcController {

  @RequestMapping(value = "/abc", method = RequestMethod.GET)
  public String abc(){
    return "Hello";
  }
}

Valid URL: http://localhost:8080/api/abc
Invalid URls:
http://localhost:8080////api/abc
http://localhost:8080/////api////abc
http://localhost:8080/////////api/////abc

Problem: My controller is accepting all above urls. I want to restrict it and accept only valid url and throw error on invalid urls.
Note: I'm not using any custom routing. It's default spring has.

2
are you using spring security or any filters for your request?? - Shubh
Try to change your value from "/abc" to "abc" and let your servlet do the dispatching. - M46
Yeah, I tried this as well but it did not work for me. - Tayyab Razaq
No, I'm not using spring security. I'm using keycloak module. It's a third party module to mange user's authentication and authorization. - Tayyab Razaq

2 Answers

0
votes

Add maven dependency for spring security and use below code to allow access to all the paths without logging in.

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    public void configure(WebSecurity web) throws Exception
    {
        web
                .ignoring()
                .antMatchers("/**");
    }
}
0
votes

The simplest way is to add custom handler interceptor to validate the url.

public class ValidateURLInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (isValidUrl(request.getRequestURI())) {
            return true;
        }
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid URL");
        return false;
    }

    private static boolean isValidUrl(String url) {
        return !url.contains("//");
    }
}

And then update the MVC configuration

@Configuration
public class AppConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new ValidateURLInterceptor());
    }
}