我有几个用户角色,比如说:用户和管理员。我只想将某些路由的访问权限授予具有管理员角色的用户。例如对于这条路线:@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 身份验证。请让我知道我是否也应该上传它。
1 回答
芜湖不芜
TA贡献1796条经验 获得超7个赞
您可以在 spring 安全配置https://github.com/spring-projects/spring-security/blob/master/samples/boot/oauth2resourceserver/src/main/ 中的路由“/all”上使用 hasRole("ADMIN") java/sample/OAuth2ResourceServerSecurityConfiguration.java
否则你可以像这样从 Jwt 中提取角色并测试正确的角色:
添加回答
举报
0/150
提交
取消