@PreAuthorize("hasAuthority('String')") 没有按预期工作

@PreAuthorize("hasAuthority('String')") not working expectedly

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

@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();
    }
}

每个用户都有自己的role/authority截至目前:

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,
                                           @Parameter(in = ParameterIn.QUERY, description = "Get users based on Last Name" ,
                                                   schema=@Schema()) @Valid @RequestParam(value = "lastname", required = false) String lastname,
                                           @Parameter(in = ParameterIn.QUERY, 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();
    }
}