我正在开发一个启动嵌入式 Jetty 服务器的 Spring 应用程序。然后它将 Spring MVC Web 应用程序“部署”到此 Jetty 服务器。
一切都在多个 Controller 上运行良好,但我无法将 Spring Security 添加到 Web 应用程序。
我使用编程和基于注释的配置,Jetty 服务器配置如下:
Server server = new Server(8080);
server.setStopAtShutdown(true);
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.mypackage.web");
context.setParent(mainContext);
ServletContextHandler contextHandler = new ServletContextHandler();
contextHandler.setErrorHandler(null);
contextHandler.setContextPath("/");
DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
DefaultServlet staticServlet = new DefaultServlet();
contextHandler.addServlet(new ServletHolder(dispatcherServlet), "/");
contextHandler.addServlet(new ServletHolder("staticServlet", staticServlet), "/res");
contextHandler.addEventListener(new ContextLoaderListener(context));
contextHandler.setResourceBase("webapp");
server.setHandler(contextHandler);
我还创建了一个扩展
WebSecurityConfigurerAdapter
的类 com.mypackage.web.SecurityConfig并像这样覆盖配置方法:@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().and()
.httpBasic();
}
}
据我了解文档,这应该足以“锁定”我的应用程序。当我以 Debug模式启动应用程序时,在配置方法中会遇到一个断点,因此 Spring 似乎检测到了配置类。
但是,我仍然可以访问应用程序中的任何页面,而不会被重定向到默认登录表单。
我是否需要将此配置告知 Jetty Servlet 容器,还是我遗漏了其他内容?
最佳答案
好的,所以我错过的是我需要将 Spring 的 DelegatingFilterProxy 添加到 Jetty 的 ServletContextHandler。通常的 Spring 方式是扩展 AbstractSecurityWebApplicationInitializer,它会添加过滤器代理。
不幸的是,这也不适用于 Jetty。
不过,可以手动将过滤器代理添加到 Jetty,在此 comment 中解释了调用:
import static org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME;
...
ServletContextHandler contextHandler = new ServletContextHandler();
...
contextHandler.addFilter(
new FilterHolder( new DelegatingFilterProxy( DEFAULT_FILTER_NAME ) ),
"/*",
EnumSet.allOf( DispatcherType.class ));
我还必须在 Jetty 中启用 session 处理,但这解释得很好here .
关于spring - 嵌入式 Jetty 无法识别 Spring MVC 安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30927761/