如何添加新角色?

时间:2019-02-22 16:50:33

标签: spring

我有一个具有管理员和用户角色的用户,现在我需要添加ROLE_SUPPORT并将该角色限制为仅读取用户列表,我该怎么做?

public class UserController {

@Autowired
UserService userService;

@RequestMapping(value = "getAll", method = RequestMethod.POST)
public List<User> getUsers() throws IOException {
    return userService.getUsers();
}

@PostMapping("save")
@ResponseStatus(HttpStatus.OK)
public void save(@RequestBody User user) {
    userService.save(user);
}

@RequestMapping(value = "delete", method = RequestMethod.POST)
public void delete(@RequestBody User user) {
    userService.delete(user);
}



@RequestMapping(value = "getUser", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public User getUser(@RequestBody RequestDto requestDto) throws IOException {
    return userService.getUser(requestDto.getId());
}

我想应该向该控制器添加一个新方法,但是我可能是错的

public class User extends BaseEntity<Integer> {


public enum Roles {
    ADMIN
}

private String firstName;
private String lastName;
@Column(name = "username")
private String username;
@Convert(converter = PurshasedProductConverter.class)
private List<PurshasedProduct> purshasedProducts;


private String email;
private String activationCode;

@Convert(converter = AttachmentConverter.class)
private Attachment userAvatar;
public Attachment getUserAvatar() {
    return userAvatar;
}

public void setUserAvatar(Attachment userAvatar) {
    this.userAvatar = userAvatar;
}


@JsonProperty(access = Access.WRITE_ONLY)
private String password;
@JsonProperty(access = Access.WRITE_ONLY)
private String temporaryPassword;

@Convert(converter = StringArrayConverter.class)
private String[] roles;

private Date lastPasswordReset;

private Date dateCreated;
private Date dateUpdated;
private Date validatyTime;
private Boolean active;

public User() {
    lastPasswordReset = dateCreated = dateUpdated = new Date();
    roles = new String[]{"USER"};
}

也就是说,当请求支持角色时,应该返回用户列表。

1 个答案:

答案 0 :(得分:0)

Spring-Security只需添加@PreAuthorize注释即可提供此支持

@RequestMapping(value = "getAll", method = RequestMethod.GET)
**@PreAuthorize("hasRole('ROLE_SUPPORT')")**
public List<User> getUsers() throws IOException {
    return userService.getUsers();
}