Spring Security 3.2:Servlet< 3.0环境中的JavaConfig springSecurityFilterChain设置

时间:2014-01-29 16:06:08

标签: spring-security

我正在尝试在Servlet 2.5环境中使用JavaConfig设置Spring Security 3.2。引用(http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/reference/htmlsingle/#jc)仅涵盖 springSecurityFilterChain Servlet 3.0 + 设置。

感谢提示/链接如何以正确的方式在Servlet 2.5环境中设置此过滤器链。

1 个答案:

答案 0 :(得分:4)

Spring Security 3.2在Servlet 2.5环境中使用JavaConfig在下面的代码中配置。

的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>

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder registry)
        throws Exception {
    registry.userDetailsService(userDetailsService).passwordEncoder(
            new BCryptPasswordEncoder());
}

@Override
public void configure(WebSecurity webSecurity) throws Exception {
    webSecurity.ignoring().antMatchers("/resources");
}

@Override
protected void configure(HttpSecurity http) throws Exception {

http.csrf().disable()
    .authorizeRequests()
        .antMatchers("/admin.htm")
        .hasAuthority("ROLE_ADMIN")
        .antMatchers("/personal/myPhotos.htm")
        .hasAnyAuthority("ROLE_USER", "ROLE_FAMILY", "ROLE_ADMIN")
        .antMatchers("/personal/familyPhotos.htm")
        .hasAnyAuthority("ROLE_FAMILY", "ROLE_ADMIN")
        .antMatchers("/**").permitAll()
        .anyRequest().authenticated()
    .and()
        .formLogin()
        .usernameParameter("j_username") // default is username
        .passwordParameter("j_password") // default is password
        .loginPage("/login.htm")
        .loginProcessingUrl("/j_spring_security_check")
        .failureUrl("/login.htm?login_error=t")
        .permitAll()
    .and()
        .logout().logoutSuccessUrl("/")
        .logoutUrl("/j_spring_security_logout")
    .and()
        .rememberMe().key("myAppKey").tokenValiditySeconds(864000);
}
}

javaconfig和xml配置有一些相同点和不同点,this blog

中有很好的解释