我的应用程序只需要支持一个url。喜欢http://.../service/api. 要执行的操作取决于“操作”请求参数
为了处理这个问题,我创建了下面的控制器
@RestController
public class Controller {
@PostMapping(path = "/api", params = "ACTION=INIT")
public String init() {
return "Inside Initialize";
}
@PostMapping(path = "/api", params = "ACTION=FETCH")
public String fetch() {
return "Inside Fetch";
}
@PostMapping(path="/view", param = "!ACTION")
public String view() {
return "Inside View";
}
缺少操作参数时将调用/视图。对于前两个请求,我配置了oauth身份验证,后一个请求,即./view将使用formlogin。
我已经创建了一个过滤器,在其中检查操作参数,如果缺少,则将请求转发给/view处理程序。
@Component
public class RouteFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, FilterChain filterChain)
throws ServletException, IOException {
if(!StringUtils.hasText(httpServletRequest.getParameter("ACTION"))){
httpServletRequest.getRequestDispatcher("/view").forward(httpServletRequest,httpServletResponse);
}else {
filterChain.doFilter(httpServletRequest,httpServletResponse);
}
}
下面是过滤器注册。我已确保在filterchainproxy之前调用我的筛选器
@Autowired
private RouteFilter routeFilter;
@Bean
public FilterRegistrationBean<RouteFilter> filter() {
FilterRegistrationBean<RouteFilter> bean = new FilterRegistrationBean<>();
bean.setFilter(routeFilter);
bean.addUrlPatterns("/api");
bean.setOrder(-100);
return bean;
}
下面是安全配置
@Configuration
@Order(1)
public class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api")
.hasAuthority("SCOPE_API")
.anyRequest()
.authenticated()
.and()
.oauth2ResourceServer()
.opaqueToken();
}
}
@Configuration
@Order(2)
public class Config2 extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/view")
.permitAll()
.and()
.formLogin();
}
}
当我调用/service/api时,routefilter将请求转发给/view处理程序,但与/view关联的Spring Security 不受尊重。spring安全过滤器链是否不适用于转发的请求,或者我是否遗漏了某些内容。我使用的是spring boot 2.4.0版
1条答案
按热度按时间mpgws1up1#
如本文所述,我们需要将dispatchertype.forward添加到springfilterchain以拦截转发的请求。上面链接中描述的步骤不起作用,因为springfilterchain是由securityautoconfiguration创建的。要在此中添加转发调度程序,我们需要将application.yml中的属性设置为
设置此属性后,安全筛选器链将拦截请求。