【问题标题】:Spring Boot AntMatchers vs @PostAuthorize usageSpring Boot AntMatchers 与 @PostAuthorize 用法
【发布时间】:2021-03-04 11:46:56
【问题描述】:

我的任务是在我正在处理的 REST API 中实现 RBAC(基于角色的访问控制)。

让我感到困惑的是,当我在扩展 WebSecurityConfigurerAdapter 的 Security 类中使​​用配置方法 antMatchers 时,授权工作正常,但是当我处理 antMatchers 并尝试在端点顶部用 @PostAuthorize 替换它们时, RBAC 无法工作。

这是我从扩展 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*/
}

效果很好。

这是由端点顶部的注释,应该被授权,但不是。

@PostAuthorize("hasRole('ADMIN')")
@RequestMapping("/hello")
String hello(){

    return "hello";
}

我做错了什么,它不能正常工作?

【问题讨论】:

  • 要启用注释处理,您需要添加@EnableGlobalMethodSecurity

标签: spring-boot spring-security rbac


【解决方案1】:

您是否尝试使用以下注释来注释您的安全配置类?

类似的东西。

@Configuration  
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)  
public class SecurityConfig extends WebSecurityConfigurerAdapter {  
    protected void configure(final HttpSecurity http) throws Exception {}  
}

【讨论】:

    猜你喜欢
    • 2018-04-28
    • 2017-01-10
    • 2013-12-30
    • 2019-05-26
    • 2017-08-09
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多