Spring Security中的hasRole()无法正常工作

时间:2019-02-05 11:30:28

标签: spring spring-security jwt

我尝试在我的应用程序中扮演角色。但是我一直都在留言。

    "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"

1 个答案:

答案 0 :(得分:0)

问题是您以错误的方式创建了授权,在您的情况下,授权应在DB角色前面加上ROLE_,分别是ROLE_ADMINROLE_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_