【问题标题】:Spring @PreAuthorize not working in RestControllerSpring @PreAuthorize 在 RestController 中不起作用
【发布时间】:2017-03-12 05:07:55
【问题描述】:

我将 GrantedAuthorities 作为[admin, player, user] 进行测试,我在方法中注入了 Authentication 对象并调用了authentication.getAuthorities(). ,但是在 REST 控制器方法中我输入了@PreAuthorize("hasRole('ROLE_player')")我得到了我的 REST Web 服务的响应为403 forbidden.

我定义了从数据库中挑选的自定义角色。我想在执行任何业务逻辑之前授权 REST 调用。 尝试使用@Secured,但仍然无法正常工作。

【问题讨论】:

  • 他们是数据库中的管理员、玩家、用户。我试过 @PreAuthorize("hasRole('player')") 但还是不行
  • Spring 期望角色以 ROLE_ 为前缀。您可以将数据库中的角色更新为 ROLE_ADMIN、ROLE_PLAYER、ROLE_USER,或者您应该能够使用 hasAuthority('admin') 而不是 hasRole() @PreAuthorize("hasAuthority('admin')")

标签: spring rest spring-security


【解决方案1】:

hasRole 的默认前缀是 ROLE_。如果没有提供前缀,spring 会自动添加它。由于您在数据库中的角色没有以 ROLE_ 为前缀,因此它们不会与 hasRole 匹配。

// will be checking for ROLE_admin, your role in DB is admin
@PreAuthorize("hasRole('admin')") 

您可以更新数据库中的角色以使用 ROLE_ 作为前缀,或者您可以更改 spring 在 DefaultWebSecurityExpressionHandler 上使用的前缀。您还应该能够使用 hasAuthority 而不是 hasRole。 hasAuthority 不会为提供的参数添加任何前缀。

@PreAuthorize("hasAuthority('admin')") 

http://docs.spring.io/spring-security/site/docs/current/reference/html/el-access.html

【讨论】:

    猜你喜欢
    • 2017-11-16
    • 2015-01-30
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 2020-06-24
    • 2015-12-09
    • 2015-06-20
    • 2019-07-28
    相关资源
    最近更新 更多