Spring MVC:Spring Security 4没有拦截

时间:2016-06-15 12:59:35

标签: java spring spring-mvc spring-security

我尝试通过Spring Security为我的Spring MVC项目(最近更新为4.2.6.RELEASE)完成授权。所以我添加了这些依赖:

    <dependency org="org.springframework.security" name="spring-security-config" rev="4.1.0.RELEASE" />
    <dependency org="org.springframework.security" name="spring-security-core" rev="4.1.0.RELEASE" />
    <dependency org="org.springframework.security" name="spring-security-crypto" rev="4.1.0.RELEASE" />
    <dependency org="org.springframework.security" name="spring-security-taglibs" rev="4.1.0.RELEASE" />
    <dependency org="org.springframework.security" name="spring-security-web" rev="4.1.0.RELEASE" />

根据我的理解,我只需要创建这些类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/", "/home").permitAll().anyRequest().authenticated().and().formLogin()
                .loginPage("/login").permitAll().and().logout().permitAll();
    }

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

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityWebInitializer extends AbstractSecurityWebApplicationInitializer {
}

我希望现在为尚未登录的用户阻止所有网址,但&#34; /&#34;,&#34; / home&#34;,&# 34; /登录&#34;和&#34; / logout&#34;。实际上没有任何东西被阻止,我的webapp完全可以访问。所以我在某处错了......

真的很感激,如果你能在这里给我一个关于我的问题可能是什么的提示。谢谢!

1 个答案:

答案 0 :(得分:0)

我测试了你的蚂蚁匹配器,它运行得很好(一切似乎都很好)所以我认为你没有将你的客户安全配置( SecurityConfig )注册到spring servlet,它是用 @Import

@EnableWebMvc 
@Configuration
@ComponentScan({ "yourpackage" })
@Import({ SecurityConfig .class }) // See here
public class SpringServlet {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/..");
        viewResolver.setSuffix("...");
        return viewResolver;
    }

}