自定义的AccessDecisionManager的验证方法 ,怎么在配置@PreAuthorize
时间: 2024-05-13 09:16:40 浏览: 49
@PreAuthorize 注解是用于在方法调用之前进行权限检查的,它使用Spring Security的表达式语言(SpEL)指定权限检查规则。默认情况下,SpEL表达式会调用底层的AccessDecisionManager进行权限检查。
如果你要使用自定义的AccessDecisionManager进行权限检查,需要在Spring Security配置类中,手动指定AccessDecisionManager。例如:
```java
@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AccessDecisionManager myAccessDecisionManager;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("admin").password("{noop}password").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic()
.and()
.csrf().disable()
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler());
}
@Bean
public AccessDeniedHandler accessDeniedHandler() {
return new CustomAccessDeniedHandler();
}
@Bean
public FilterSecurityInterceptor filterSecurityInterceptor() throws Exception {
FilterSecurityInterceptor filterSecurityInterceptor = new FilterSecurityInterceptor();
filterSecurityInterceptor.setAuthenticationManager(authenticationManager());
filterSecurityInterceptor.setAccessDecisionManager(myAccessDecisionManager);
filterSecurityInterceptor.setSecurityMetadataSource(securityMetadataSource());
return filterSecurityInterceptor;
}
@Bean
public MySecurityMetadataSource securityMetadataSource() {
return new MySecurityMetadataSource();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(filterSecurityInterceptor(), FilterSecurityInterceptor.class);
}
}
```
在这个例子中,我们使用自定义的AccessDecisionManager,并将它注入到了FilterSecurityInterceptor中。然后,我们在configure方法中,添加了一个FilterSecurityInterceptor的Bean,并将它添加到了HttpSecurity中。这样,在使用@PreAuthorize注解时,就会使用我们自定义的AccessDecisionManager进行权限检查。
阅读全文