有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java以编程方式启用Spring安全性前置符号

我有一个Spring WebMVC应用程序,在控制器方法上使用@PreAuthorize@PostAuthorice注释。但是这些注释被忽略了,因为我没有在spring security中启用它

如果我有一个spring-security.xml,我可以通过以下行启用它:

<global-method-security pre-post-annotations="enabled" />

不幸的是,我有一个完整的基于注释的配置。 Spring Security原则上适用于我的应用程序

我的问题:如何使用基于注释的MVC配置启用前后注释

  • Spring版本:4.0.5。释放
  • Spring安全版本:3.2.4。释放

这是我的WebSecurityConfigurerAdapter实现:

@Configuration
@EnableWebMvcSecurity()
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired DataSource dataSource;
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
            .dataSource(dataSource)
            .passwordEncoder(new ShaPasswordEncoder(256))
            .usersByUsernameQuery("select username,password, enabled from user where USERNAME=?")
            .authoritiesByUsernameQuery("select u.username, r.name from user u, role r, user_has_role uhr where u.id = uhr.user_id and r.id = uhr.role_id and u.username = ?  ");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/resources/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .defaultSuccessUrl("/", true)
                .and()
            .logout()
                //.logoutUrl("/logout") //this is the default
                // Call the URL invalidate_session after logout...
                .logoutSuccessUrl("/invalidate_session")
                .permitAll()
                .and()
               // @see http://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/#csrf-configure
            .csrf().disable();
    }
}

我的MessageSecurityWebApplicationInitializer是空的:

public class MessageSecurityWebApplicationInitializer extends
        AbstractSecurityWebApplicationInitializer {

}

共 (1) 个答案

  1. # 1 楼答案

    我必须向配置类添加以下注释:@EnableGlobalMethodSecurity(prePostEnabled=true)