【发布时间】:2019-11-30 11:33:43
【问题描述】:
假设我有一个具有以下身份验证的用户:
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));
在安全检查中,我应该检查用户是否具有访问 API 的权限。我做了以下事情来实现它:
http
.httpBasic().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/product/**").hasAuthority("READ_PRODUCT");
这里我用hasAuthority()来检查用户是否有正确的权限,但是我发现还有一个方法叫hasRole()但是不知道这两种方法有什么区别?谁能解释我的区别,如果我想在这里使用hasRole(),我该如何在这里使用它?我试图用hasRole() 替换hasAuthority(),但没有成功
【问题讨论】:
-
this问题的答案可能对您有所帮助。
-
在您的情况下,
hasRole()不适用,因为您的权限没有以“ROLE_”为前缀。如果您有权限,例如“ROLE_USER”,则hasRole("USER")等同于hasAuthority("ROLE_USER")。在您的情况下,对于“READ_PRODUCT”权限,没有等效角色。 -
啊,我明白了,非常感谢@EleftheriaStein-Kousathana
标签: spring-security