Spring 启动 AntMatchers 与 @PostAuthorize 用法
Spring Boot AntMatchers vs @PostAuthorize usage
我的任务是在 REST API 中实现 RBAC(基于角色的访问控制)。
令我困惑的是,当我在扩展 WebSecurityConfigurerAdapter 的安全 class 中使用时,在配置方法 antMatchers 中,授权工作正常,但是当我处理 antMatchers 并尝试用 @PostAuthorize 替换它们时在端点之上,RBAC 无法工作。
这是我从 class 扩展 WebSecurityConfigurerAdapter 的配置方法:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.rememberMe()
.and()
.addFilter(new JwtUsernameAndPasswordAuthenticationFilter(authenticationManager()))
.addFilterAfter(new JwtTokenVerifierFilter(), JwtUsernameAndPasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.antMatchers("/user").authenticated()
.antMatchers("/hello").hasRole(ApplicationUserRole.ADMIN.name())
.anyRequest()
.authenticated();
http.headers().frameOptions().disable();/*REQUIRED FOR H2-CONSOLE*/
}
效果很好。
那是在应该被授权的端点之上的 annotarion,但没有。
@PostAuthorize("hasRole('ADMIN')")
@RequestMapping("/hello")
String hello(){
return "hello";
}
我做错了什么,它工作不正确?
您是否尝试使用以下注释来注释您的安全配置 class?
像这样。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(final HttpSecurity http) throws Exception {}
}
我的任务是在 REST API 中实现 RBAC(基于角色的访问控制)。
令我困惑的是,当我在扩展 WebSecurityConfigurerAdapter 的安全 class 中使用时,在配置方法 antMatchers 中,授权工作正常,但是当我处理 antMatchers 并尝试用 @PostAuthorize 替换它们时在端点之上,RBAC 无法工作。
这是我从 class 扩展 WebSecurityConfigurerAdapter 的配置方法:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.rememberMe()
.and()
.addFilter(new JwtUsernameAndPasswordAuthenticationFilter(authenticationManager()))
.addFilterAfter(new JwtTokenVerifierFilter(), JwtUsernameAndPasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.antMatchers("/user").authenticated()
.antMatchers("/hello").hasRole(ApplicationUserRole.ADMIN.name())
.anyRequest()
.authenticated();
http.headers().frameOptions().disable();/*REQUIRED FOR H2-CONSOLE*/
}
效果很好。
那是在应该被授权的端点之上的 annotarion,但没有。
@PostAuthorize("hasRole('ADMIN')")
@RequestMapping("/hello")
String hello(){
return "hello";
}
我做错了什么,它工作不正确?
您是否尝试使用以下注释来注释您的安全配置 class?
像这样。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(final HttpSecurity http) throws Exception {}
}