春季在请求映射中出现多个正斜杠

时间:2018-09-28 08:00:03

标签: spring spring-mvc spring-boot

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

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

有效网址: http://localhost:8080/api/abc
无效的URls:
http://localhost:8080////api/abc
http://localhost:8080/////api////abc
http://localhost:8080/////////api/////abc

问题:我的控制器接受上述所有网址。我想限制它,只接受有效的网址,并对无效的网址抛出错误。
注意:我没有使用任何自定义路由。这是Spring的默认设置。

2 个答案:

答案 0 :(得分:0)

为 spring 安全添加 maven 依赖,并使用以下代码允许无需登录即可访问所有路径。

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("/**");
    }
}

答案 1 :(得分:0)

最简单的方法是add custom handler interceptor验证网址。

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("//");
    }
}

然后更新MVC配置

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