Настройка Spring Security на встроенной Jetty в Spring - PullRequest
4 голосов
/ 11 июля 2011

У меня есть файл определения Spring beans, как показано ниже

<bean id="jettyZk" class="org.eclipse.jetty.server.Server" init-method="start" destroy-method="stop">
    <!-- properties, threadPool, connectors -->

    <property name="handler">
        <bean class="org.eclipse.jetty.servlet.ServletContextHandler">
            <property name="eventListeners">
                <list>
                    <!-- my.ContextLoaderListener
                    * An ApplicationContextAware ContextLoaderListener that allows for using the current ApplicationContext,
                    * as determined by ApplicationContextAware, as the parent for the Root WebApplicationContext.
                    * 
                    * Also provides for specifying the contextConfigLocation of the Root WebApplicationContext, because
                    * Eclipse Jetty 7 ServletContextHandler does not expose a setInitParameters method.
                    -->
                    <bean class="my.ContextLoaderListener">
                        <property name="contextConfigLocation" value="/META-INF/spring/applicationContext-securityZk.xml"/>
                    </bean>
                    <!-- not sure if this is needed, disabled for now -->
                    <!-- <bean class="org.springframework.web.context.request.RequestContextListener"/> -->
                </list>
            </property>
            <property name="servletHandler">
                <bean class="org.eclipse.jetty.servlet.ServletHandler">
                    <property name="filters">
                        <list>
                            <bean class="org.eclipse.jetty.servlet.FilterHolder">
                                <property name="name" value="springSecurityFilterChain"/>
                                <property name="filter">
                                    <bean class="org.springframework.web.filter.DelegatingFilterProxy"/>
                                </property>
                            </bean>
                        </list>
                    </property>
                    <!-- filterMappings, servlets, servletMappings -->
                </bean>
            </property>
        </bean>
    </property>
</bean>

При попытке запустить контекст я получаю следующее исключение

Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: ServletContext must not be null

Caused by: java.lang.IllegalArgumentException: ServletContext must not be null
    at org.springframework.util.Assert.notNull(Assert.java:112)
    at org.springframework.web.context.support.WebApplicationContextUtils.getWebApplicationContext(WebApplicationContextUtils.java:109)

Это использует Spring 3.0.5.RELEASE

Исключение понятно, если взглянуть на код и JavaDocs для DelegatingFilterProxy # findWebApplicationContext, где написано

WebApplicationContext должен быть уже загружен и сохранен в ServletContext до того, как этот фильтр инициализируется (или вызывается).

потому что я пытаюсь создать фильтр как (под) свойство обработчика контекста, поэтому кажется разумным, что контекст еще не был инициализирован и, следовательно, не имеет Spring WAC.

Что я хотел бы знать, так это как настроить Spring Security во встроенном контейнере Jetty, который собирает сам Spring?

Кажется, что есть сценарий уловки 22, который просто нуждается в поздней инициализации, но я не могу найти подходящий флаг для вращения. Я пытался установить lazy-init="true" на bean-компоненте фильтра, но это, по-видимому, не достигло многого, что неудивительно.

Связанный: Как встроить Jetty в Spring и использовать тот же AppContext, в который он был встроен?

1 Ответ

0 голосов
/ 11 июля 2011

Я использую Jetty 6.1.4 и Spring 3.0.5, но делаю это по старинке, используя WEB-INF / web.xml.

При таком подходе проблем не возникает.

public class JettyServer {

    public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    props.load(new FileInputStream("./etc/server.properties"));

    Server server = new Server();

    final String configFile = props.getProperty("server.config");

    XmlConfiguration configuration = 
        new XmlConfiguration(new File(configFile).toURI().toURL());
    configuration.configure(server);
    HandlerCollection handlers = new HandlerCollection();

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath(props.getProperty("context.path"));
    webapp.setDefaultsDescriptor(props.getProperty("default.config"));

    webapp.setWar(props.getProperty("war.path"));

    NCSARequestLog requestLog = new NCSARequestLog(props.getProperty("log.file"));
    requestLog.setExtended(true);
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    requestLogHandler.setRequestLog(requestLog);

    handlers.setHandlers(
       new Handler[] { webapp, new DefaultHandler(), requestLogHandler });

    server.setHandler(handlers);

    server.setStopAtShutdown(true);
    server.setSendServerVersion(true);

    server.start();
    server.join();
}
...