How to activate Spring Security in a webflux war a

2020-03-26 08:31发布

问题:

How to activate a webflux security in a war packaging application. I am using the Spring 5 built-in AbstractAnnotationConfigDispatcherHandlerInitializer, but it does not work.

public class AppIntializer extends AbstractAnnotationConfigDispatcherHandlerInitializer {

    @Override
    protected Class<?>[] getConfigClasses() {
        return new Class[]{
            WebConfig.class,
            SecurityConfig.class
        };
    }
}

But it seems the Spring Security WebFilter is not enabled. Spring Security 5 does not include a Reactor specific WebApplicationInitializer to activate Spring security filter chain.

Stack: Spring Security 5.0.0.M4

Source codes: https://github.com/hantsy/spring-reactive-sample/blob/master/war/src/main/java/com/example/demo/AppIntializer.java

回答1:

You should be able to just use AbstractAnnotationConfigDispatcherHandlerInitializer. However, there is a bug in AbstractDispatcherHandlerInitializer. You can work around the problem using:

public class AppInitializer extends AbstractAnnotationConfigDispatcherHandlerInitializer {

    @Override
    protected Class<?>[] getConfigClasses() {
        return new Class[]{
            WebConfig.class,
            SecurityConfig.class
        };
    }

    protected void registerDispatcherHandler(ServletContext servletContext) {
        String servletName = getServletName();
        ApplicationContext applicationContext = createApplicationContext();

        refreshApplicationContext(applicationContext);
        registerCloseListener(servletContext, applicationContext);

        HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(applicationContext)
            .build();
        ServletHttpHandlerAdapter handlerAdapter = new ServletHttpHandlerAdapter(httpHandler);

        ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, handlerAdapter);

        registration.setLoadOnStartup(1);
        registration.addMapping(getServletMapping());
        registration.setAsyncSupported(true);

        customizeRegistration(registration);
    }
}

In Spring 5.0.2.RELEASE+ (scheduled for release Nov 15, 2017) you can extend AbstractReactiveWebInitializer instead.

public class AppIntializer extends AbstractReactiveWebInitializer {

    @Override
    protected Class<?>[] getConfigClasses() {
        return new Class[]{
            WebConfig.class,
            SecurityConfig.class
        };
    }
}