首页 > 解决方案 > 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 很陌生,所以任何建议都将不胜感激。

标签: javaspring-bootspring-security

解决方案


推荐阅读