How to test a Spring Controller that is secured - java

I currently have an app built with Spring Boot 2, Spring MVC, Spring Data/JPA and Thymeleaf.
I'm writing some unit/integration tests and I'd like to test the controller, which is secured by SpringSecurity backed by a database with registered users.
What would be the best approach here to test it? I've unsuccessfully tried a few of them like using annotations like #WithMockUser.
Edit: Just a reminder that I'm not testing #RestControllers. I'm directly injecting a #Controller on my test class and calling its methods. It works just fine without Spring Security.
One example:
#Controller
public class SecuredController {
#GetMapping("/")
public String index() {
return "index";
}
}
The / path is secured by Spring Security and would normally redirect to /login to authenticate the user.
My unit test would look like this:
#WebMvcTest(controllers = SecuredController.class)
class SecuredControllerTest {
#Autowired
private SecuredController controller;
#Autowired
private MockMvc mockMvc;
#Test
#WithMockUser(username = "user", password = "pass", roles = {"USER"})
public void testAuthenticatedIndex() throws Exception {
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andDo(print());
}
}
The first errors I get is that is asks me to inject my UserDetailsService implementation, which is something that I'd like to avoid. But if I do inject the service, the test works, but returns 404 instead of 200.
Any ideas?

You will need to add your security configurations to the Spring context by importing your WebSecurityConfigurerAdapter class.
#WebMvcTest(controllers = SecuredController.class)
#Import(SecuredControllerTest.Config.class)
class SecuredControllerTest {
#Configuration
#EnableWebSecurity
static class Config extends MyWebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("pa$$").roles("USER");
auth.inMemoryAuthentication().withUser("admin").password("pa$$").roles("ADMIN");
}
}
...
}
The embedded static class Config is just to change where we get the users from, in this case an inMemoryAuthentication will be enough.

In test class, use annotations
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
in setup test method
#Before
In real test method
#WithMockUser("spring")
#Test
Testing Spring Security like these examples
https://spring.io/blog/2014/05/23/preview-spring-security-test-web-security
https://www.baeldung.com/spring-security-integration-tests

Related

How to test Spring Boot #WebFluxTest with Spring Security #Secured annotation

I'm having troubles testing a Spring WebFlux controller secured by Spring Security's #Secured annotation. Here is my controller code :
#RestController
#RequestMapping("/endpoint")
public class MyController {
#GetMapping()
#Secured("ADMIN")
public Flux<MyOutputDto> getOutputDtos() {
return myService.getOutputDtos();
}
}
And here is my test code :
#WebFluxTest(MyController.class)
class MyControllerTest {
#Autowired
WebTestClient webTestClient;
#Test
#WithApplicationUser(roles = "ADMIN")
void should_work_fine() {
webTestClient.get()
.uri("/endpoint")
.exchange()
.expectStatus().isOk();
}
#Test
void should_return_401_unauthorized() {
webTestClient.get()
.uri("/endpoint")
.exchange()
.expectStatus().isUnauthorized();
}
#Test
#WithApplicationUser
void should_return_403_forbidden() {
webTestClient.get()
.uri("/endpoint")
.exchange()
.expectStatus().isForbidden();
}
}
The #WithApplicationUser annotation is a custom annotation that injects a mock authentication object in the security context with provided roles. If no roles are provided (like in the third test) then it defaults to no role at all.
The problem here is that the first 2 tests work fine, but the third fails by returning 200 OK instead of 403 Forbidden. My first thought went for Spring Security not processing #Secured annotation, so I followed many Spring WebFlux/Spring Security documentation and online articles, but none worked.
Does someone have an idea for this ? Thanks in advance
Okay so I figured out what was going on.
First, the #Secured annotation seems to not be processed by Spring Security for reactive applications (i.e Spring WebFlux). With #EnableReactiveMethodSecurity you must use #PreAuthorize annotations.
Then, I had to create a test configuration and import it to my test and it worked like a charm.
#TestConfiguration
#EnableReactiveMethodSecurity
public class WebFluxControllerSecurityTestConfig {
}
#WebFluxTest(MyController.class)
#Import(WebFluxControllerSecurityTestConfig.class)
class MyControllerTest {
// Same tests
}

Spring Testing Mock MVC doesn't apply custom RequestMappingHandlerMapping

I have created a Custom annotation to version my APIs.
Everything works when running the application.
However when I try to test my controllers using MockMvc, the custom RequestMappingHandlerMapping I wrote isn't being applied.
I'm initializing MockMvc like this
#Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.apply(documentationConfiguration(this.restDocumentation))
.apply(springSecurity())
.build();
}
I override the defaults to use my custom RequestMappingHandlerMapping like this
#Configuration
public class RoutingConfig {
#Bean
public WebMvcRegistrations webMvcRegistrationsPathHandlerMapping() {
return new WebMvcRegistrations() {
#Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
return new APIPathRequestHandlerMapping();
}
};
}
}
Any idea what's going on? I thought the web application context initialization of the MockMvc would pick up all the configuration changes by default.
EDIT 1:
I should also add that I'm using Spring Boot 2.1.2.RELEASE
EDIT 2:
To clarify, the versioning annotation when applied to a controller accepts request that starts with the version, i.e: /users becomes /v1/users
This works with normal requests are coming up, but for tests only /users work, /v1/users returns a 404 (Not found)
I've placed debug points in the configs and the custom RequestMappingHandlerMapping and am sure that this is not being picked up by MockMvc.
I've tried to autowire MockMvc, but the same behaviour persists, with the additional issue of not being able to configure Spring RestDocs.
#AutoConfigureMockMvc Annotation that can be applied to a test class to enable and configure auto-configuration of MockMvc.
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class DemoApplicationTests {
#Autowired
private MockMvc mockMvc;
#Test
public void contextLoads() {
System.out.println("test "+mockMvc);
}
}
Note: I applied custom RequestMappingHandlerMapping, it is getting applied with MockMvc autoconfiguration successfully.

#WebMvcTest creating more than one Controller for some reason

I'm trying to create a controller test with #WebMvcTest, and as I understand, when I put #WebMvcTest(ClientController.class) annotation of the test class it should not create a whole lot of beans, but just ones that this controller requires.
I'm mocking the bean this controller requires with #MockBean, but somehow it fails with an exception that there's 'No qualifying bean' of another service that does not required by this controller but by another.
So this test is failing:
#RunWith(SpringRunner.class)
#WebMvcTest(controllers = ClientController.class)
public class ClientControllerTest {
#MockBean
ClientService clientService;
#Test
public void getClient() {
assertEquals(1,1);
}
}
I've created an empty Spring Boot project of the same version (2.0.1) and tried to create test over there. It worked perfectly.
So my problem might be because of the dependencies that my project has many, but maybe there's some common practice where to look in this situation? What can mess #WebMvcTest logic?
I've found a workaround. Not to use #WebMvcTest and #MockBean, but to create everything by hand:
//#WebMvcTest(ClientController.class)
#RunWith(SpringRunner.class)
public class ClientControllerTest {
private MockMvc mockMvc;
#Mock
ClientService clientService;
#Before
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(
new ClientController(clientService)
).build();
}
works with Spring 1.4.X and with Spring Boot 2.X (had different exception there and there), but still doesn't explain why #WebMvcTest doesn't work

Spring Boot Exclude DataSource Configuration

I have a small application that when live, makes a database connection, and stores and persists some data.
I'm currently in the midsts of trying to write some tests, and I'm wanting to completely cut off the database part of the application, and just mock it in the tests.
The Datasource is setup with a configuration class.
#Component
#Configuration
public class DataSourceConfiguration {
#Bean
public DataSource myDataSource() { ... }
}
and a test boostrap that currently looks similar to
#RunWith(SpringRunner.class)
#EnableAutoConfiguration(exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class
})
public class MyTest {
}
When running the test, I can see that Spring is trying to instantiate Hibernate, and a connection to the db, I assume because of my config class. How can I stop Spring from doing this?
No Need to use : #EnableAutoConfiguration
We can narrow down the tests to just the web layer by using #WebMvcTest as below,
#RunWith(SpringRunner.class)
#WebMvcTest
public class WebLayerTest {
#Autowired
private MockMvc mockMvc;
#Test
public void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
}
}
Refer how to test spring application with only web or using complete application context loading : https://spring.io/guides/gs/testing-web/ refer mocking example : http://www.lucassaldanha.com/unit-and-integration-tests-in-spring-boot/

Spring MVC Controller testing, and mocking many classes

We have many Controllers in our system, and many Spring Data repositories.
I would like to write tests for my controllers that run through my MVC context.
However, it seems pretty cumbersome, and just not right, to have to, by hand, mock every service and repository in my system, so that I can test the controllers
e.g.
FooControllerTest.java
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextHierarchy(value = {
#ContextConfiguration(classes = { MockServices.class }),
#ContextConfiguration({ "classpath:/META-INF/spring/mvc-servlet-context.xml" }),
})
public class FooControllerTest {
#Autowired
private WebApplicationContext wac;
private MockMvc mvc;
#Autowired
private FooRepository fooRepository;
#Autowired
private FooService fooService;
#Before
public void setUp() throws Exception {
mvc = webAppContextSetup(wac).build();
}
#Test
public final void list() {
when(fooRepository.findAll()).thenReturn(...);
mvc.perform(get("/foo"))...
}
#Test
public final void create() {
Foo fixture = ...
when(fooService.create(fixture)).thenReturn(...);
mvc.perform(post("/foo"))...
}
}
MockServices.java
#Configuration
public class MockServices {
#Bean
public FooRespository fooRepositiory() {
return Mockito.mock(FooRespository.class);
}
#Bean
public FooService fooService() {
return Mockito.mock(FooService.class);
}
//even though we are "only" testing FooController, we still need to mock BarController's dependencies, because BarController is loaded by the web app context.
#Bean
public BarService barService() {
return Mockito.mock(FooService.class);
}
//many more "mocks"
}
I do not really want to use standaloneSetup() (want to use the production configuration, eg conversion services, error handlers, etc)
is this just the price I have to pay for writing controller tests so far down the line?
Seems there should be something like mock every class annotated with #Service or mock every interface that extends JpaRepository
An MVC Controller is implemented normally like a glue code that integrates the Model with the View. For example, when invoking an EJB from the Controller and then updating the View model.
So, a Controller test may have sence when indeed you mock all your dependencies and verify that this integration or "glue code" is working as expected. In general, if an integration test implies too many components, maybe a modularization of the whole sut may be necessary for the system to be actually testable.
Anyway, if you find integration test laborious, maybe you can try to get the most coverage for each standalone component and let functional tests get the Controller coverage.

Categories