我使用带弹簧安全装置的弹簧靴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')")
还有其他配置吗?
答案 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
。