我尝试在我的应用程序中扮演角色。但是我一直都在留言。
"status": 403, "error": "Forbidden", "message": "Forbidden",
在数据库中,我具有列角色和值USER或ADMIN
RestController
@GetMapping(value="/users")
@PreAuthorize("hasRole('ROLE ADMIN')")
public ResponseEntity<List<User>> getAllusers(){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
System.out.println(authentication.getAuthorities());
List<User> users = userService.findAll();
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
如果我评论@PreAuthorize
System.out.println(authentication.getAuthorities());
正确显示了"ROLE ADMIN"
或"ROLE USER"
答案 0 :(得分:0)
问题是您以错误的方式创建了授权,在您的情况下,授权应在DB角色前面加上ROLE_
,分别是ROLE_ADMIN
和ROLE_USER
(您错过了下划线)
因此,您的UserDetails
的{{1}}实现应以适当的方式扮演角色,例如:
getAuthorities()
然后在您的控制器中,@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
/* this is just a sample , you must implement bringing data from repository then prefix every string with ROLE_ */
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return authorities;
}
应该可以工作,(删除@PreAuthorize("hasRole('ADMIN')")
),
您也可以使用ROLE_