java - Postman 中的 Spring Boot MultiValueMap 参数

标签 java spring spring-boot junit postman

我已经在 Spring boot 中实现了 OAuth2。在 JUnit 中测试它时效果很好,但当我在 postman 中尝试该 API 时,我总是遇到未经授权的情况。

JUnit 中的测试函数:

private String obtainAccessToken(String username, String password) throws Exception {
    final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", "password");
    params.add("client_id", CLIENT_ID);
    params.add("username", username);
    params.add("password", password);


    ResultActions result = mockMvc.perform(post("/oauth/token")
            .params(params)
            .with(httpBasic(CLIENT_ID, CLIENT_SECRET))
            .accept(CONTENT_TYPE))
            .andExpect(status().isOk())
            .andExpect(content().contentType(CONTENT_TYPE));


    String resultString = result.andReturn().getResponse().getContentAsString();

    JacksonJsonParser jsonParser = new JacksonJsonParser();
    return jsonParser.parseMap(resultString).get("access_token").toString();
}

我在 postman 中尝试了以下 API:

POST 类型 http://localhost:8080/oauth/token 内容类型为 application/json 在正文部分我选择了 raw 和 JSON :

{
    "grant_type":"password",
    "client_id":"clientIdPassword",
    "username":"a",
    "password":"a"
}

显示401未经授权。然后我也尝试了这样的:

内容类型为application/json的帖子类型,http://localhost:8080/oauth/token?grant_type=password&client_id=clientIdPassword&username=a&password=a。这也显示 401 Unauthorized。

我的问题是如何在 Postman 中将 MultiValueMap 设置为参数?

最佳答案

您应该使用 postman 的授权选项卡来根据您的喜好发送身份验证 header 以及请求正文。 PFA 样本图像 enter image description here

关于java - Postman 中的 Spring Boot MultiValueMap 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49141182/

相关文章:

java - 如何在 Spring Boot 2.2.4 中将 @ConstructorBinding 和 @PropertySource 与 @ConfigurationProperties 一起使用?

java - @Transactional 注解 Spring boot 2.0 和 hibernate LazyInitializationException

java - org.hibernate.PersistentObjectException 与 Spring、Maven 和 Hibernate 的组合

java - 避免@Secured 注解的重复值

java - Kafka Consumer仅在产生 'enough'数据后才读取

java - java arraylist中的数字按升序排序

java - 如何在猜谜游戏中使用 JOption?

java - Spring-boot,JUnit 测试使用不同的配置文件

java - Spring REST security - 以不同方式保护不同的 URL

java - 如何手动使 Spring Batch 作业失败?