我正在尝试使用Spring Security保护在Spring Boot中创建的rest API,特别是@Secured批注。我正在尝试阅读这篇文章:https://www.baeldung.com/role-and-privilege-for-spring-security-registration(Spring Security 2.1.6.RELEASE)。
我的@RestController
类中有一个名为getUsers()
的方法,它看起来像这样:
@Secured("USER_READ")
@RequestMapping(value = USER_STRING, method = RequestMethod.POST)
@JsonView(UserViews.ExternalLight.class)
public Iterable<User> getUsers(@RequestBody(required = false) SearchContext context) {
return getUsersHelper(context);
}
理想情况下,我希望有一个名为“ USER_READ”的特权,该特权应该能够读取用户(我打算提供的不仅仅是ADMIN和USER角色)。
在我的UserPrinciple implements UserDetails
类中,我具有以下方法:
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getAuthorities(user.getRoles());
}
当我尝试使用良好的凭据访问API并调试此行时,我看到getAuthorities()
返回了SimpleGrantedAuthority
对象的列表,其中包含“ USER_READ”,“ ROLE_ADMIN”和其他一些。但是,正如标题所示,尽管GrantedAuthority
对象列表中仍然存在“ USER_READ”,我仍然得到403。
我看过一些文章说我需要在角色前加上“ ROLE_”前缀,但是我已经为角色完成了此操作,如果将@Secured("USER_READ")
更改为@Secured("ROLE_ADMIN")
,仍然会收到相同的错误。
我还使用@EnableGlobalMethodSecurity(securedEnabled = true)
启用了方法安全性。
我对Spring还是很陌生,所以任何建议都将不胜感激。