【问题标题】:calling rest api with requestbody and authenticationprincipal使用 requestbody 和 authenticationprincipal 调用 rest api
【发布时间】:2020-01-27 21:35:30
【问题描述】:

我有一个 rest api,它可以基于角色访问其 http POST 方法。它使用 spring-security 仅对授权用户访问 api。

我有 2 个问题,

  1. 外部客户端如何传递请求正文和用户对象 (@AuthenticationPrincipal) 来进行此 api 调用

  2. 如何编写 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


    【解决方案1】:

    当您向经过身份验证的用户发出请求时,控制器将自动填充身份验证主体。
    例如,如果您使用 HTTP 基本身份验证来保护您的端点,那么主体将从 Authorization 标头填充。无论您是否提取主体,您的请求正文都保持不变。

    测试控制器的一种简单方法是使用 Spring Security 提供的支持。
    如果您使用的是MockMvc,则一种选择是使用后处理器来调用您的端点与不同类型的用户。

    this.mvc.perform(post("/api/access/submit")
        .content("...")
        .with(user("user").roles("USER")))
        .andExpect(status().isUnauthorized());
    
    this.mvc.perform(post("/api/access/submit")
        .content("...")
        .with(user("admin").roles("ADMIN")))
        .andExpect(status().isOk());
    

    您可以在文档here 中了解有关 Spring Security 测试支持的更多信息。

    【讨论】:

    • 谢谢...我想我们已经很接近了。我在 ".with(user("admin").roles("ADMIN")))" 部分遇到问题。我收到“RequestPostProcessor”类的类型转换错误。
    • 我已经添加了我的 UserObject 类以供参考。
    猜你喜欢
    • 2018-06-29
    • 1970-01-01
    • 2012-11-01
    • 2018-10-12
    • 2021-12-24
    • 2021-05-07
    • 2022-01-17
    • 2019-02-16
    • 1970-01-01
    相关资源
    最近更新 更多