java - 403 Forbidden 当使用@Secured Spring Security
问题描述
我正在尝试使用 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”和其他一些对象。但是,正如标题所示,尽管“USER_READ”仍然存在于对象列表中,但我仍然得到 403 GrantedAuthority
。
我看过文章说我需要在角色前面加上“ROLE_”,但我已经为我的角色做了这个,如果我更改@Secured("USER_READ")
为@Secured("ROLE_ADMIN")
,我仍然会收到同样的错误。
我还使用@EnableGlobalMethodSecurity(securedEnabled = true)
.
我对 Spring 很陌生,所以任何建议都将不胜感激。
解决方案
推荐阅读
- sql - 选择前 X 行并删除其余行
- c# - 无法在 Visual Studio 中打开类的设计器视图
- python - Python 程序给出 TypeError: cannot unpack non-iterable int object
- discord - 如何使用 discord.js 从服务器获取所有成员
- php - PHP copy() Windows 错误*出现*的确切时间是什么时候?
- javafx - 找不到前缀“gluonfx”的插件 + 导致无法识别 gluon mobile 和 javafx 代码
- mysql - SQL 语句选择总是相同的字段,即使语句搜索其他
- python - Python:合并嵌套字典列表并获取字典(树)
- configuration - 使用 Terraform 将自定义 DNS 服务器 IP 添加到 Azure VM NIC
- c# - 当 VSCode 没有给我错误时该怎么办?