Adding spring security to embedded Jetty

一曲冷凌霜 提交于 2019-12-22 11:05:04

问题


I am trying to add Spring Security - OAuth2 to my Rest API which resides on embedded Jetty. I am getting "No bean named 'springSecurityFilterChain' is defined" error. When I add a ContextLoadListener with context.addEventListener( new ContextLoaderListener() ); I start getting

Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!" 

error. The following is the structure of my Code

public class Launcher
{
  public static void main( String[] args )
  {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( CMApplicationConfig.class, TestConfig.class);  
    JettyServer server = new JettyServer();
    server.start( ctx );
  }
}


public class JettyServer
  public void start( AnnotationConfigApplicationContext c )
  {
    ServletContextHandler context   = new ServletContextHandler( ServletContextHandler.SESSIONS );

    // Set application context parent of webapp context. The purpose is sharing singleton objects which reside on the application side with Jetty context       
    final GenericWebApplicationContext webApplicationContext = new GenericWebApplicationContext();
    webApplicationContext.setServletContext(context.getServletContext());
    webApplicationContext.setParent(c);
    webApplicationContext.refresh();

    context.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
    context.setContextPath( "/" );

    ServletHolder springServlet = context.addServlet( org.springframework.web.servlet.DispatcherServlet.class, "/" );
    springServlet.setInitParameter( "contextClass", AnnotationConfigWebApplicationContext.class.getName() );
    springServlet.setInitParameter( "contextConfigLocation", "config.CMWebContextConfiguration");
    springServlet.setInitOrder( 1 );

    // Add spring security      
    context.addFilter(new FilterHolder( new DelegatingFilterProxy( "springSecurityFilterChain" ) ),"/*", EnumSet.allOf( DispatcherType.class ));

    //This gives: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader
    context.addEventListener( new ContextLoaderListener() );

    // Configure server
    _jettyServer = new Server( createThreadPool() );
    _jettyServer.setConnectors( createConnectors( _jettyServer ) );
    _jettyServer.setHandler( context );

    try
    {
        _jettyServer.start();
    }
    catch ( Exception ex )
    {
        ex.printStackTrace();
    }
}

来源:https://stackoverflow.com/questions/29365858/adding-spring-security-to-embedded-jetty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!