【发布时间】:2020-01-27 21:35:30
【问题描述】:
我有一个 rest api,它可以基于角色访问其 http POST 方法。它使用 spring-security 仅对授权用户访问 api。
我有 2 个问题,
外部客户端如何传递请求正文和用户对象 (@AuthenticationPrincipal) 来进行此 api 调用
-
如何编写 junit 来测试下面的代码,
@PreAuthorize("hasAuthority('ADMIN')") @PostMapping("/api/access/submit") public ResponseEntity<OrderAdminResponse> create(@RequestBody OrderAdminRequest orderAdminSubmitRequest,@AuthenticationPrincipal UserObject user) { return ResponseEntity.accepted().body(orderService.submit(orderAdminSubmitRequest)); }
我的用户对象在下面,
公共类用户对象 {
私有最终字符串名称;
私有最终字符串 id;
私人最终字符串电子邮件;
私人用户对象(字符串名称,int id,字符串电子邮件){
this.name = 名称;这个.id = id; this.email = 电子邮件
}
公共集合 getRoles() {
返回
(集合)this.getAuthorities().stream()
.map(GrantedAuthority::getAuthority).collect(Collectors.toList());
}
公共布尔isUserInRole(字符串角色){
返回 this.getAuthorities().stream().anyMatch((a) -> {
返回 a.getAuthority().equals(role);
})
}
}
【问题讨论】:
标签: java rest spring-boot junit spring-security