【问题标题】:Multiple forward slashes in request mapping in spring春季请求映射中的多个正斜杠
【发布时间】:2019-03-04 04:34:04
【问题描述】:
@RestController
@RequestMapping("/api")
public class AbcController {

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

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

问题: 我的控制器正在接受以上所有网址。我想限制它并只接受有效的 url 并在无效的 url 上抛出错误。
注意:我没有使用任何自定义路由。这是默认的弹簧。

【问题讨论】:

  • 您是否使用 spring security 或任何过滤器来满足您的要求??
  • 尝试将您的值从“/abc”更改为“abc”,并让您的 servlet 进行调度。
  • 是的,我也试过了,但对我不起作用。
  • 不,我没有使用 Spring Security。我正在使用 keycloak 模块。管理用户认证和授权的第三方模块。

标签: spring spring-mvc spring-boot


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    最简单的方法是add custom handler interceptor验证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("//");
        }
    }
    

    然后更新MVC配置

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

    【讨论】:

      猜你喜欢
      • 2014-01-02
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 2018-01-10
      • 2015-03-13
      • 2011-10-22
      相关资源
      最近更新 更多