Spring @PreAuthorize在RestController中不起作用

时间:2017-03-11 20:13:38

标签: spring rest spring-security

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

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

1 个答案:

答案 0 :(得分:1)

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

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

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

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

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

相关问题