我有几个用户角色,比如说:user和admin。
我只想授予具有角色管理员的用户对某些路由的访问权限。例如,此路线:
@GetMapping("/all")
public ResponseEntity getAll(){
List<User> users = this.userRepository.findAll();
return new ResponseEntity<>(users, HttpStatus.OK);
}
如何在Spring中创建不同的中间件,以便我可以使用它们来限制对特定用户角色的访问?
这是我的用户模型:
@Entity
@Table(name = "users")
public class User implements Serializable {
private static final long serialVersionUID = -7643506746013338699L;
public User() { }
public User(String username, String email, String password, String firstName, String lastName) {
this.username = username;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
@Id
@NotEmpty
@Size(min = 5, max = 15)
@Column(name = "username")
private String username;
@Email
@NotEmpty
@Column(name = "email")
private String email;
@NotEmpty
@Size(min = 5)
@Column(name = "password")
private String password;
//some more user properties
...
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "username"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
// getters and setters
...
}
我实现了JWT身份验证。请让我知道是否也应该上传它。
谢谢!
答案 0 :(得分:1)
您可以在spring安全配置中的该路由“ / all”上使用hasRole(“ ADMIN”) https://github.com/spring-projects/spring-security/blob/master/samples/boot/oauth2resourceserver/src/main/java/sample/OAuth2ResourceServerSecurityConfiguration.java
否则,您可以像这样从Jwt中提取角色并测试正确的角色: