Tayyab Razaq
Tayyab Razaq

Reputation: 378

Multiple forward slashes in request mapping in spring

@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

Answers (2)

samabcde
samabcde

Reputation: 8114

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

Technology World
Technology World

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

Related Questions