@PreAuthorize("hasAuthority('String')") 无法正常工作

问题描述

我已经创建了 Spring Security 配置,如下所示:

@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/Login").permitAll()
                .anyRequest().authenticated()
                .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http
            .addFilterBefore(jwtRequestFilter,UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

并且每个用户都有自己的角色/权限:

public enum TypeEnum implements GrantedAuthority {
    CUSTOMER("Customer"),EMPLOYEE("Employee");

    private String value;

    TypeEnum(String value) {
      this.value = value;
    }

    @Override
    @JsonValue
    public String toString() {
      return String.valueOf(value);
    }

    @JsonCreator
    public static TypeEnum fromValue(String text) {
      for (TypeEnum b : TypeEnum.values()) {
        if (String.valueOf(b.value).equals(text)) {
          return b;
        }
      }
      return null;
    }

    @Override
    public String getAuthority() {
      return name();

在我的控制器中,我试图用某些角色对其进行预授权

@PreAuthorize("hasAuthority('Employee')")
public ResponseEntity<List<User>> getUsers(@Parameter(in = ParameterIn.QUERY,description = "Get user that corresponds to userID",schema=@Schema()) @Valid @RequestParam(value = "userid",required = false) Integer userid,@Parameter(in = ParameterIn.QUERY,description = "Get user that has account with IBAN",schema=@Schema()) @Valid @RequestParam(value = "iban",required = false) Integer iban,description = "Get users based on Last Name",schema=@Schema()) @Valid @RequestParam(value = "lastname",required = false) String lastname,description = "Maximum numbers of items to return",schema=@Schema()) @Valid @RequestParam(value = "limit",required = false) Integer limit)
{
    return new ResponseEntity<List<User>>(userService.getAllUser(),HttpStatus.OK);
}

我打印了 getAuthorities 方法

System.out.println(SecurityContextHolder.getContext().getAuthentication().getAuthorities());

导致 Customer

当我尝试访问端点时,它仍然显示结果并给出状态 200。

解决方法

我认为您应该在安全配置中添加 @EnableGlobalMethodSecurity(prePostEnabled = true) 注释,以便能够使用 hasAuthority() 方法。

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfigurer extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
       http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/Login").permitAll()
            .anyRequest().authenticated()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

       http
            .addFilterBefore(jwtRequestFilter,UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws 
                                                             Exception {
        return super.authenticationManagerBean();
    }
}