Spring REST通过用户角色限制用户访问

时间:2018-11-01 17:50:06

标签: java spring spring-security

我有几个用户角色,比如说: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身份验证。请让我知道是否也应该上传它。

谢谢!