Spring安全性抛出javax.servlet.ServletException:无法解析名称为' j_spring_security_check'

时间:2015-06-13 05:15:20

标签: java spring spring-mvc spring-security tiles-3

我正在尝试将 Spring security 自定义登录页面访问数据库添加到我的Spring MVC应用程序中。看起来我的映射是错误的,因为它无法映射j_spring_security_check

要解决此问题,我查看了以下网页123但尚未解决此问题。

如果您没有太多时间,请阅读下面的第2部分,即问题的编辑部分开始的地方。否则,请同时阅读第1部分第2部分

第1部分

我还在web.xml文件中添加了以下行,但应用程序返回以下异常。

     <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Caused by: java.lang.IllegalStateException: Duplicate Filter registration for 'springSecurityFilterChain'. Check to ensure the Filter is only configured once.
    at org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer.registerFilter(AbstractSecurityWebApplicationInitializer.java:215)
    at org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer.insertSpringSecurityFilterChain(AbstractSecurityWebApplicationInitializer.java:147)
    at org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer.onStartup(AbstractSecurityWebApplicationInitializer.java:121)
    at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5423)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

Jun 13, 2015 2:44:54 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:188)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:691)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:456)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

Jun 13, 2015 2:44:54 PM org.apache.catalina.startup.Catalina start
SEVERE: The required Server component failed to start so Tomcat is unable to start.
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:691)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:456)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 11 more

在提交表单后不添加过滤器,请求将由以下控制器捕获。

@Controller
public class MainController {

    @RequestMapping("/{viewName}")
    public String index(@PathVariable String viewName) {
        ...
    }

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <listener>
        <listener-class>org.apache.tiles.extras.complete.CompleteAutoloadTilesListener</listener-class>
    </listener>


    <servlet>
        <servlet-name>my</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

<!--    <listener> -->
<!--        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> -->
<!--    </listener> -->
<!--    <filter> -->
<!--        <filter-name>springSecurityFilterChain</filter-name> -->
<!--        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> -->
<!--    </filter> -->

<!--    <filter-mapping> -->
<!--        <filter-name>springSecurityFilterChain</filter-name> -->
<!--        <url-pattern>/*</url-pattern> -->
<!--    </filter-mapping> -->


    <servlet-mapping>
      <servlet-name>my</servlet-name>
      <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/config/my-security.xml
        </param-value>
    </context-param>

</web-app>

我-security.xml文件

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.2.xsd">


    <http auto-config="true" access-denied-page="/notFound.jsp"
        use-expressions="true">
        <intercept-url pattern="/" access="permitAll" />
    </http>

    <!-- <beans:import resource="security-db.xml" /> -->

    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="alex" password="123456" authorities="ROLE_USER" />
                <user name="mkyong" password="123456" authorities="ROLE_USER, ROLE_ADMIN" />
            </user-service>
        </authentication-provider>
    </authentication-manager>
</beans:beans>

AppConfig.java

@EnableWebMvc
@Configuration
@ComponentScan({ "com.myproject.*" })
@EnableTransactionManagement
@Import({ SecurityConfig.class })
public class AppConfig {


    @Bean
    public SessionFactory sessionFactory() {
        LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(
                dataSource());
        builder.scanPackages("com.myproject.model").addProperties(
                getHibernateProperties());
        return builder.buildSessionFactory();
    }

    private Properties getHibernateProperties() {
        Properties prop = new Properties();
        prop.put("hibernate.format_sql", "true");
        prop.put("hiberate.show_sql", "true");
        prop.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        return prop;
    }

    @Bean(name = "dataSource")
    public BasicDataSource dataSource() {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/test");
        ds.setUsername("jack");
        ds.setPassword("jack");
        return ds;
    }

    @Bean
    public HibernateTransactionManager txManager() {
        return new HibernateTransactionManager(sessionFactory());
    }

}

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    @Qualifier("userDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(
                passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/profile/**")
                .access("hasRole('ADMIN')").and().formLogin()
                .loginPage("/signin").failureUrl("/signin?error")
                .usernameParameter("username").passwordParameter("password")
                .and().logout().logoutSuccessUrl("/index").and().csrf().and()
                .exceptionHandling().accessDeniedPage("/403");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

}

SpringMVCInitializer.java

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class SpringMvcInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { AppConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

}

LoginController.java

@Controller
public class LoginController {

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(
            @RequestParam(value = "error", required = false) String error,
            @RequestParam(value = "logout", required = false) String logout) {

        ModelAndView model = new ModelAndView();
        if (error != null) {
            model.addObject("error", "Invalid username and password!");
        }

        if (logout != null) {
            model.addObject("msg", "You've been logged out successfully.");
        }
        model.setViewName("login");

        return model;

    }
}

**

第2部分

根据Thomas的建议,我将代码改为

**

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <listener>
        <listener-class>org.apache.tiles.extras.complete.CompleteAutoloadTilesListener</listener-class>
    </listener>


    <servlet>
        <servlet-name>my</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
      <servlet-name>my</servlet-name>
      <url-pattern>/</url-pattern>
    </servlet-mapping>



</web-app>

AppConfig.java

@EnableWebMvc
@Configuration
@ComponentScan({ "com.myproject" })
@EnableTransactionManagement
@Import({ SecurityConfig.class })
public class AppConfig {

    @Bean
    public SessionFactory sessionFactory() {
        LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(
                dataSource());
        builder.scanPackages("com.myproject.model").addProperties(
                getHibernateProperties());
        return builder.buildSessionFactory();
    }

    private Properties getHibernateProperties() {
        Properties prop = new Properties();
        prop.put("hibernate.format_sql", "true");
        prop.put("hiberate.show_sql", "true");
        prop.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        return prop;
    }

    @Bean(name = "dataSource")
    public BasicDataSource dataSource() {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/test");
        ds.setUsername("jack");
        ds.setPassword("jack");
        return ds;
    }

    @Bean
    public HibernateTransactionManager txManager() {
        return new HibernateTransactionManager(sessionFactory());
    }

}

SecurityConfig.java

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    @Qualifier("userDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
//      auth.userDetailsService(userDetailsService).passwordEncoder(
//              passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/profile/**")
                .access("hasRole('ADMIN')").and().formLogin()
                .loginPage("/login").failureUrl("/login?error")
                .and().logout().logoutSuccessUrl("/index").and().csrf().and()
                .exceptionHandling().accessDeniedPage("/403");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

}

SpringMVCInitializer.java

public class SpringMvcInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { AppConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

}

MainController

@Controller
public class MainController {

    @RequestMapping("/{viewName}")
    public String index(@PathVariable String viewName) {
        System.err.println("View Name is :" + viewName);
        if (isValidView(viewName)) {
            return viewName;
        }
        return null;
    }

关于MainController,这是我处理静态页面的方式,例如www.myproject.com/index,www.myproject.com/contactus等。关于这个问题的另一个问题是here

2 个答案:

答案 0 :(得分:3)

您的代码中存在多个问题。最重要的一点是,您正在混合Java配置和Spring Security的XML配置。确定您更喜欢使用哪种配置。在我的回答中,我将重点关注基于Java的配置,因为我将从您的代码中完全删除XML配置。

在您的情况下,默认情况下@EnableWebSecurity注释已经注册了相应的过滤器。但是如果您使用的是Spring MVC,那么它应该是@EnableWebMvcSecurity

此外,请查看您的HttpSecurity配置:

 protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/profile/**")
                .access("hasRole('ADMIN')").and().formLogin()
                .loginPage("/signin").failureUrl("/signin?error")
                .usernameParameter("username").passwordParameter("password")
                .and().logout().logoutSuccessUrl("/index").and().csrf().and()
                .exceptionHandling().accessDeniedPage("/403");
}

您显然告诉登录页面位于/signin,但在您的LoginController中,映射是/login。那你为什么配置了.usernameParameter("username") .passwordParameter("password")?它已经在Spring Security默认配置中以这种方式完成。

您还应该添加SecurityInitializer类,它在Spring Security 3.2中可能如下所示:

public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {

    public SecurityInitializer() {
        super(SecurityConfig.class);
    }
}

总而言之,将Spring Security添加到项目中的基本步骤是执行以下操作:

  1. 为Spring Security添加适当的(Maven,Gradle)依赖项;
  2. 配置使用@EnableWebMvcSecurity注释的Spring Security类,尤其是configureGlobal(...)configure(...)方法;
  3. 注册延长AbstractSecurityWebApplicationInitializer;
  4. 的课程
  5. 在控制器中提供登录页面的映射,并在JSP页面中记下自定义表单。
  6. 基本登录表单如下所示:

        <form name='loginForm' method='POST'>
    
          <table>
            <tr>
                <td>User:</td>
                <td><input type='text' name='username' value=''></td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type='password' name='password' /></td>
            </tr>
            <tr>
                <td colspan='2'><input name="submit" type="submit"
                    value="submit" /></td>
            </tr>
          </table>
    
          <input type="hidden" name="${_csrf.parameterName}"
            value="${_csrf.token}" />
    
        </form>
    

    这些基本步骤可在项目中启用Spring Security。有关更多信息,好的教程是: http://docs.spring.io/spring-security/site/docs/3.2.x/guides/hellomvc.html http://docs.spring.io/spring-security/site/docs/3.2.x/guides/form.html

    祝你好运:)

答案 1 :(得分:1)

我强烈建议您遵循Java或XML配置。我个人更喜欢Java配置。

  • 删除所有与Spring Security相关的XML配置并创建以下内容 文件。
  • 将权限地址修改为您拥有的任何内容。

    public class MessageSecurityWebApplicationInitializer extends
            AbstractSecurityWebApplicationInitializer { //register the springSecurityFilterChain with the war
    
    }
    
    
    public class MessageWebApplicationInitializer extends
            AbstractAnnotationConfigDispatcherServletInitializer {
    
        @Override
        protected Class<?>[] getRootConfigClasses() {
            return new Class[] { SecurityConfig.class }; //make sure your config file gets loaded
        }
    
        @Override
        protected Class<?>[] getServletConfigClasses() {
            // TODO Auto-generated method stub
            return null;
        }
    
        @Override
        protected String[] getServletMappings() {
            // TODO Auto-generated method stub
            return null;
        }
    
    
       @Configuration
       @EnableWebMvcSecurity
       public class SecurityConfig extends WebSecurityConfigurerAdapter {
         @Autowired
            public void configureGlobal(AuthenticationManagerBuilder auth)
                throws Exception {
            System.err.println("in here");
            auth.inMemoryAuthentication().withUser("user@yahoo.com")
                    .password("password").roles("USER"); //access to inmemory credentials
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                    .antMatchers("/resources/**", "/", "/index", "/aboutus")
                    .permitAll() //allow access to your static pages and resources
                    .antMatchers("/profile/**")
                    .hasRole("USER") //profile address is only available to users ( do not need to add ROLE_ as Spring does it for you)
                    .and() //and is equivalent of end tag in XML 
                    .formLogin().loginPage("/signin").failureUrl("/signin?error")
                    .permitAll().and().logout().logoutUrl("/singout").permitAll();
        }
    

有关进一步说明和访问DB的信息,请参阅documentation