Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable Spring Security pre-post-annotations programmatically

I have Spring WebMVC Application using @PreAuthorize and @PostAuthorice annotations on the controller-methods. But these annotations are ignored since I don't have enabled it in my spring security.

If I would have a spring-security.xml I could enable it with the following line:

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

Unfortunately I have a complete Annotation-based configuration. Spring-Security in principle works in my Application.

My question: How can I enable pre-post-annotation with an annotation based MVC configuration?

  • Spring-Version: 4.0.5.RELEASE
  • Spring-Security-Version: 3.2.4.RELEASE

This is my WebSecurityConfigurerAdapter implementation:

@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();     } } 

My MessageSecurityWebApplicationInitializer is empty:

public class MessageSecurityWebApplicationInitializer extends         AbstractSecurityWebApplicationInitializer {  } 
like image 840
Tarator Avatar asked Oct 25 '14 01:10

Tarator


1 Answers

I had to add the following annotation to the Configuration-class: @EnableGlobalMethodSecurity(prePostEnabled=true)

like image 187
Tarator Avatar answered Sep 28 '22 06:09

Tarator