2

I have created a Spring Boot application containing various endpoints. Except for signup and login endpoints I've added a filter for other requests. All other requests should have:

Authorization Bearer <token>

and requests goes through Spring Security filter chain which checks the user exists in the table or not via UserDetailService.

I would like to know how can I write unit tests for any GET/POST API with Spring Security in place ?

One way i have in mind is to generate the actual token by calling signup API and then call other APIs with the Authorization token generated by Signup API.

OR

There might be some way to mock or skip the Authorization Bearer for unit tests

I wanted to know what is this the correct/best approach that's followed across?

1 Answer 1

2

For my applications i have been using a conbination of MockUser annotation with a MockMvc bean. MockUser is able to populate Spring SecurityContext with a user and his principal, which includes his User object and GrantedAuthority (aka ROLEs). With this you can test your controllers without needing to create any token. It is easier and more decoupled from your autthentication process.

Like this:

@Test
@WithMockUser("admin")  
void testAuthorize() throws Exception {
    this.mockMvc.perform(get("/objects")).andExpect(status().isOk());
}

In Spring docs you can read more about. And you also have @WithAnonymousUser, to simulate anonnymouser, @WithUserDetails to put a custom UserDetailsService.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.