Reputation: 378
@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.
Upvotes: 5
Views: 1893
Reputation: 8124
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());
}
}
Upvotes: 1
Reputation: 1
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("/**");
}
}
Upvotes: 0