Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bearer token failure MockMvc test Java Spring Boot

I'm failing to understand why this does not work. I'm assuming it's something simple that I'm overlooking. All other other test methods not utilizing a token work fine. There is no expiration currently on the token, and I can use it fine with Postman.

@Test
public void getUser() throws Exception {

    String token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJsd2lsbGlhbXMxNiIsInJvbGVzIjoidXNlciIsImlhdCI6MTUxNDQ0OTgzM30.WKMQ_oPPiDcc6sGtMJ1Y9hlrAAc6U3xQLuEHyAnM1FU";
    MvcResult mvcResult = mockMvc.perform(

            MockMvcRequestBuilders.get("/api/users/lwilliams16")
            .header("authentication", "Bearer " + token))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andDo(print())
            .andReturn();

    System.out.println(mvcResult.getResponse().getContentAsString());
}
like image 758
Leo Williams Avatar asked Oct 19 '25 03:10

Leo Williams


1 Answers

I was utilizing the word Authentication instead of Authorization. It's late. Also, the correct response type is APPLICATION_JSON_UTF8.

@Test
public void getUser() throws Exception {

    String token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJsd2lsbGlhbXMxNiIsInJvbGVzIjoidXNlciIsImlhdCI6MTUxNDQ0OTgzM30.WKMQ_oPPiDcc6sGtMJ1Y9hlrAAc6U3xQLuEHyAnM1FU";
    MvcResult mvcResult = mockMvc.perform(

            MockMvcRequestBuilders.get("/api/users/lwilliams16")
            .header("authorization", "Bearer " + token))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andDo(print())
            .andReturn();

    System.out.println(mvcResult.getResponse().getContentAsString());
}
like image 78
Leo Williams Avatar answered Oct 20 '25 16:10

Leo Williams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!