没有考虑带有安全注释的Spring引导

时间:2017-10-12 13:27:25

标签: spring-boot spring-security

我使用带弹簧安全装置的弹簧靴2.

我为休息和mvc分割了安全性。

@EnableWebSecurity
public class MultiHttpSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

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

    @Configuration
    @Order(1)
    public class RestWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .antMatcher("/rest/**")
                    .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                    .httpBasic().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable();
        }
    }

    @Configuration
    @Order(2)
    public class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    .antMatchers("/css/**",  "/js/**", "/img/**", "/").permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin().loginPage("/login").permitAll().successHandler(new CustomAuthenticationSuccessHandler())
                    .and()
                    .logout()
                    .logoutUrl("/logout")
                    .logoutSuccessHandler(new CustomLogoutHandler())
                    .and().csrf().disable();
        }
    }
}

我在db中的角色是

超级用户,管理员,集成商。

在我的其他一个控制器中,我把

@Secured("hasRole('user')")

这个角色并不存在于我的应用程序中。

我尝试了一个有角色的用户:超级用户和集成商,并且有效...

相同
@PreAuthorize("hasAuthority('user')")

还有其他配置吗?

1 个答案:

答案 0 :(得分:2)

为了保护您的方法,您必须使用@EnableGlobalMethodSecurity注释启用 方法安全性

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class HelloMethodSecurityConfig {

    @Bean
    public MethodSecurityService methodSecurityService() {
        return new MethodSecurityServiceImpl(); //Class managed by Spring
    }

    @Autowired
    public void registerGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
          .inMemoryAuthentication()
          .withUser("user").password("password").roles("USER").and()
          .withUser("admin").password("password").roles("USER", "ADMIN");
    }

}

使用上述最小配置,现在可以使用方法安全性保护类MethodSecurityService的方法。

要获得更多自定义方法安全性,您需要扩展GlobalMethodSecurityConfiguration

查看官方docs