将@PreAuthorize添加到服务类时:“在SecurityContext中找不到身份验证对象”

我有一个运行良好的Spring Boot控制器,并具有以下声明:

@RestController
@RequestMapping("/api/our")
@PreAuthorize(value = "hasRole('ROLE_USER')")
@Api(value="our",produces="Our data")
public class OurController {

当我在代码上运行Fortify静态分析工具时,它抱怨我们的服务类说:

  

在没有适当的访问控制的情况下,OurService.java中的findAll()方法可以在第36行执行包含攻击者控制的主键的SQL语句,从而使攻击者可以访问未经授权的记录。

所以我尝试将@PreAuthorize注释添加到我们的服务类中,如下所示:

@Service
@PreAuthorize(value = "hasRole('ROLE_USER')")
public class OurService {
    private final OurRepository ourRepository;

    public OurService(OurRepository ourRepository) {
        this.ourRepository = ourRepository;
    }

    public Page<Our> findAll(Pageable pageable) {
        return ourRepository.findAll(pageable);
    }

    public Page<Our> findAll(Specification<Our> specification,Pageable pageable) {
        return ourRepository.findAll(specification,pageable);
    }
}

但是在启动我们的应用程序时,它失败,但出现以下异常:

  

由以下原因引起:org.springframework.security.authentication.AuthenticationCredentialsnotFoundException:在SecurityContext中找不到身份验证对象

maliaoliao1234 回答:将@PreAuthorize添加到服务类时:“在SecurityContext中找不到身份验证对象”

配置类中是否有@EnableGlobalMethodSecurity(prePostEnabled = true)

  
      
  • prePostEnabled属性启用Spring Security的前/后注释
  •   
  • securedEnabled属性确定是否应启用@Secured批注
  •   
  • jsr250Enabled属性允许我们使用@RoleAllowed批注
  •   

要使@PreAuthorize(value = "hasRole('ROLE_USER')")工作,您需要在配置类中添加该注释。

您可以阅读此Introduction to Spring Method Security以获得更多信息。

,

失败源于带有@Component的类,该类实现了ApplicationRunner接口。

我必须在其构造函数中添加以下代码:

Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
Authentication authentication = new UsernamePasswordAuthenticationToken(this.getClass().getName(),"ROLE_USER",authorities);
SecurityContextHolder.getContext().setAuthentication(authentication);
,

您可以在@PreAuthorize中不使用value关键字吗?

例如:

@PreAuthorize("hasRole('ROLE_USER')")
本文链接:https://www.f2er.com/3141984.html

大家都在问