Skip to content

Have unit test OAuth2 authentication configured with annotations #6559

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

Have unit test OAuth2 authentication configured with annotations #6559

ch4mpy opened this issue Feb 24, 2019 · 1 comment

Comments

@ch4mpy
Copy link
Contributor

ch4mpy commented Feb 24, 2019

Summary

Default token store has no knowledge of test configured authentication

Actual Behavior

OAuth2Athentication is anonymous, whatever I try to configure it with @WithMockUser or alike

Expected Behavior

When a test is decorated with authentication meta-data, OAuth2Athentication should be set-up accordingly

linked requests

As mentioned in other requests, I ended with a solution involving a parent class for all my controllers unit tests, which mocks TokenStore so that it recognizes a specific Authorization header and creates OAuth2Authorization according to what is configured with @WithMockOAuth2Client and @WithMockOAuth2User

Sample

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 Have unit test TokenStore set-up OAuth2 authentication as configured with test annotations Have unit test OAuth2 authentication configured with annotations 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