Spring security 在Spring安全性中,hasRole()和hasAuthority()之间有什么区别

Spring security 在Spring安全性中,hasRole()和hasAuthority()之间有什么区别,spring-security,Spring Security,假设我有一个具有以下身份验证的用户: List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); grantedAuthorities.add(new SimpleGrantedAuthority("READ_PRODUCT")); grantedAuthorities.add(new SimpleGrantedAuthority("WRITE_PRODUCT")); SecurityContex

假设我有一个具有以下身份验证的用户:

 List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
 grantedAuthorities.add(new SimpleGrantedAuthority("READ_PRODUCT"));
 grantedAuthorities.add(new SimpleGrantedAuthority("WRITE_PRODUCT"));

 SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("usr", "pwd", grantedAuthorities));
在这里,我使用
hasAuthority()
检查用户是否拥有正确的权限,但我发现还有一个方法叫做
hasRole()
,但我不知道这两种方法之间的区别是什么?有人能解释一下区别吗?如果我想在这里使用
hasRole()
,我该如何在这里使用它?我试图将
hasAuthority()
替换为
hasRole()
,但没有成功

hasRole()定义角色(例如:“员工”或“访客”),而
hasAuthority()定义了权限(例如:一名员工只能使用正门,但另一名员工也可以使用后门)

问题的答案可能会对您有所帮助。在您的情况下,
hasRole()
不适用,因为您的权限没有前缀“ROLE”。如果您拥有权限,例如“ROLE\u USER”,则
hasRole(“USER”)
相当于
hasAuthority(“角色用户”)
。在您的情况下,对于“阅读产品”的权限,没有等效的角色。啊,我明白了,非常感谢@EleftheriaStein Kousathana
 http
    .httpBasic().disable()
    .authorizeRequests()
    .antMatchers(HttpMethod.GET, "/product/**").hasAuthority("READ_PRODUCT");