@preauthorize(“hasauthority('string'))无法正常工作

tzdcorbm  于 2021-09-30  发布在  Java
关注(0)|答案(1)|浏览(444)

这个问题在这里已经有了答案

hasanyauthority总是让我在声明停止请求时进入api(1个答案)
上个月关门了。
我创建了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();
    }
}

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

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

我用这种方法打印了这张照片

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

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

bmvo0sr5

bmvo0sr51#

我想你应该补充一点 @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();
    }
}

相关问题