Skip to content

@WithMockUser alike annotations for OAuth2 #6558

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
ch4mpy opened this issue Feb 24, 2019 · 1 comment
Closed

@WithMockUser alike annotations for OAuth2 #6558

ch4mpy opened this issue Feb 24, 2019 · 1 comment

Comments

@ch4mpy
Copy link
Contributor

ch4mpy commented Feb 24, 2019

Summary

Provide with tooling to set-up properly mocked OAuth2Authentication when writing unit tests

Actual Behavior

@WithMockUser is not quite enough to mock Auth2 authentication

Expected Behavior

When I write controller unit tests, I wish I could mock any aspect of OAuth2 authentication (being direct client auth or on behalf of an end-user)

linked requests

Sample

As described in this request, I came-up with a solution: @WithMockOAuth2Client to mock direct client connection and @WithMockOAuth2User to mock a client connected on behalf of an end-user (relies on both @WithMockOAuth2Client and @WithMockUser).

Overall result in controller unit tests:

@WebMvcTest(UserController.class)
@Import({ResourceServerConfig.class})
@EnableSpringDataWebSupport
public class UserControllerTest extends OAuth2ControllerTest {

    @MockBean
    UserRepository userRepo;

    @Test
    @WithMockOAuth2User(user = @WithMockUser(username = "admin", authorities = "READ_USERS"))
    public void whenAuthenticatedWithReadUserPrivilegeThenListUsersReturnsUsersPage() throws Exception {
        final List<User> users = Arrays.asList(admin, user);
        when(userRepo.findAll(any(Pageable.class))).thenAnswer(invocation ->
                new PageImpl<>(users, (Pageable) invocation.getArguments()[0], users.size()));

        api.get("/users/")
                .andExpect(status().isOk())
                .andExpect(jsonPath("$._embedded.elements", hasSize(users.size())))
                .andDo(document("users-collection",
                        ignorePage(responseFields(), "elements"),
                        links()));
    }
}
@ch4mpy ch4mpy changed the title @WithMockUser alike annotations for OAuth2 authentications @WithMockUser alike annotations for OAuth2 authentications Feb 24, 2019
@ch4mpy ch4mpy changed the title @WithMockUser alike annotations for OAuth2 authentications @WithMockUser alike annotations for OAuth2 Feb 24, 2019
@ch4mpy
Copy link
Contributor Author

ch4mpy commented Feb 24, 2019

merged 4 requests in first to better preserve the big picture of the need

@ch4mpy ch4mpy closed this as completed Feb 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant