我正在尝试理解一些 Spring 安全代码。我也是 Spring Security 的新手,我想我在这里缺少一些基本的东西。
我在其中一个类上有注释:
@Controller
@RequestMapping("/download-resource")
@PreAuthorize(value="hasRole('LINKS_ADMIN')")
public class DownloadResourcesController extends BaseHtmlController
{..}
我读到了有关 @PreAuthorize
的内容,这是合乎逻辑的。
我仍然无法理解 Spring 安全性从何处检索定义的角色字符串:'LINKS_ADMIN'
。在哪里定义的?
谢谢, 射线。
最佳答案
这些角色是您分配给 UserDetails 的角色(权限)当用户登录时。这些将由 Authentication 返回实现。
它们是一种形式 Collection<? extends GrantedAuthority>
, 通常 SimpleGrantedAuthority
用来。
例如,在我的应用程序中,每个人都被分配到组中。因此,当用户登录时,我会检查该用户所属的所有组,并将这些添加到他的用户详细信息中。
for (Group group : groups) {
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + group.getName().toUpperCase()));
}
因此,如果我有名为“Admin”、“User”和“Reporter”的组,我现在可以检查 has_role('ROLE_ADMIN')
, has_role('ROLE_USER')
和 has_role('ROLE_REPORTER')
在引擎盖下它是从中检索的
SecurityContextHolder.getContext().getAuthentication().getAuthorities();
哪里getAuthentication()
返回我上面链接到的 Authentication 实例,然后您从该对象中获取权限。
关于java - @PreAuthorize 安全角色注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19093701/