View Javadoc
1   package org.oxerr.spring.security.otp.samples.helloworld;
2   
3   import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
4   import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
5   import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
6   import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
7   import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern;
8   import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
9   
10  import org.junit.jupiter.api.Test;
11  import org.springframework.beans.factory.annotation.Autowired;
12  import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
13  import org.springframework.boot.test.context.SpringBootTest;
14  import org.springframework.security.test.context.support.WithMockUser;
15  import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.FormLoginRequestBuilder;
16  import org.springframework.test.web.servlet.MockMvc;
17  
18  @SpringBootTest
19  @AutoConfigureMockMvc
20  class ApplicationTests {
21  
22  	@Autowired
23  	private MockMvc mockMvc;
24  
25  	@Test
26  	void loginWithValidUserThenAuthenticated() throws Exception {
27  		FormLoginRequestBuilder login = formLogin()
28  			.user("user")
29  			.password("password");
30  
31  		mockMvc.perform(login)
32  			.andExpect(authenticated().withUsername("user"));
33  	}
34  
35  	@Test
36  	void loginWithInvalidUserThenUnauthenticated() throws Exception {
37  		FormLoginRequestBuilder login = formLogin()
38  			.user("invalid")
39  			.password("invalidpassword");
40  
41  		mockMvc.perform(login)
42  			.andExpect(unauthenticated());
43  	}
44  
45  	@Test
46  	void accessUnsecuredResourceThenOk() throws Exception {
47  		mockMvc.perform(get("/"))
48  			.andExpect(status().isOk());
49  	}
50  
51  	@Test
52  	void accessSecuredResourceUnauthenticatedThenRedirectsToLogin() throws Exception {
53  		mockMvc.perform(get("/hello"))
54  			.andExpect(status().is3xxRedirection())
55  			.andExpect(redirectedUrlPattern("**/login"));
56  	}
57  
58  	@Test
59  	@WithMockUser
60  	void accessSecuredResourceAuthenticatedThenOk() throws Exception {
61  		mockMvc.perform(get("/hello"))
62  				.andExpect(status().isOk());
63  	}
64  
65  }