Spring MVC 4 REST安全性的问题

时间:2015-04-14 18:54:50

标签: java spring-mvc spring-security spring-boot

我在为REST API添加安全性时遇到了真正的困难,我想知道是否有人可以在这里提供帮助。我有一组Model,Controller和DAO类,以便通过我的API添加,编辑和删除客户。我使用的是最新版本的Spring MVC 4.我希望有一些基本的身份验证,以便只有少数用户可以这样做。

我开始添加以下课程:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
        http.csrf().disable();
    }
}

您可以注意到我在测试期间返回一些错误消息后禁用了csrf。我还添加了以下类来初始化SecurityConfig

public class MessageSecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
     public MessageSecurityWebApplicationInitializer() {
        super(SecurityConfig.class);
    }
}

我当然在我的pom.xml中添加了(因为我没有使用web.xml)相关的依赖项。所以我使用maven构建我的项目,然后将.war文件复制并粘贴到tomcat7 webapps文件夹中。加载.war文件时,我收到以下错误消息:

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

我也在下面的课程中初始化我的应用程序。我没有AbstractAnnotationConfigDispatcherServletInitializer的实现来添加SecurityConfig

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class TestApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(TestApplication.class);
    }
}

这里出了什么问题?我搜索了整个网络,试图弄清楚如何简单地将基本身份验证添加到我的API中,记住我的所有配置都是基于java而不是web.xml。我甚至找不到一篇可以解决我遇到的问题的文章。有什么想法吗?

编辑:

仍然存在Spring Security问题。我删除了MessageSecurityWebApplicationInitializer,现在当我尝试访问/ customers(客户列表)时,我收到了一个登录表单。当我输入用户名和密码时,我得到以下异常:

javax.servlet.ServletException: Filter execution threw an exception
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:267)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:108)
    at org.springframework.boot.context.web.ErrorPageFilter.access$000(ErrorPageFilter.java:59)
    at org.springframework.boot.context.web.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.AbstractMethodError: null
    at javax.servlet.http.HttpServletRequestWrapper.changeSessionId(HttpServletRequestWrapper.java:249)
    at javax.servlet.http.HttpServletRequestWrapper.changeSessionId(HttpServletRequestWrapper.java:249)
    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.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:202)
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:187)
    at org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy.applySessionFixation(ChangeSessionIdAuthenticationStrategy.java:48)
    at org.springframework.security.web.authentication.session.AbstractSessionFixationProtectionStrategy.onAuthentication(AbstractSessionFixationProtectionStrategy.java:82)
    at org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy.onAuthentication(ChangeSessionIdAuthenticationStrategy.java:32)
    at org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy.onAuthentication(CompositeSessionAuthenticationStrategy.java:83)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:216)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)

1 个答案:

答案 0 :(得分:0)

错误消息指出已经创建了根ApplicationContext。如果您使用Java Configuration执行此操作,则可能创建了AbstractAnnotationConfigDispatcherServletInitializer的子类。变化应该是:

public class MessageSecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
     public MessageSecurityWebApplicationInitializer() {
        // remove super(SecurityConfig.class);
    }
}

然后更新现有的AbstractAnnotationConfigDispatcherServletInitializer

子类
public class MessageWebApplicationInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

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

    // ... other overrides ...
}

您可以在Hello Spring MVC Security Java Config

中找到完整的示例