I want to make test class for my endpoints. It wasnt problem with GET methods but POST is secure by spring security. My error massage:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /books
Parameters = {}
Headers = {}
Handler:
Type = null
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 403
Error message = Could not verify the provided CSRF token because your session was not found.
Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = [[Cookie@45e1aa48 name = 'XSRF-TOKEN', value = '333edde7-e271-41df-a169-03336cd05fc4', comment = [null], domain = [null], maxAge = -1, path = '/', secure = false, version = 0, httpOnly = false]]
java.lang.AssertionError: Status
Expected :200
Actual :403
<Click to see difference>
Test class:
@RunWith(SpringRunner.class)
@WebMvcTest(BookEndpoint.class)
@Import(SecurityConfig.class)
public class BookEndpointTest {
BookDto bookNumberOne;
BookDto bookNumberTwo;
@Autowired
private MockMvc mockMvc;
@MockBean
private BookFacade bookFacade;
@Before
public void setUp() throws Exception {
bookNumberOne = BookDto.builder()
.id(1L)
.title("Testowa1")
.author("Anonim1")
.isbn("1234567890")
.build();
bookNumberTwo = BookDto.builder()
.id(2L)
.title("Testowa2")
.author("Anonim2")
.isbn("1234567890")
.build();
}
@Test
public void add() throws Exception {
given(bookFacade.add(bookNumberOne)).willReturn(bookNumberOne);
mockMvc.perform(post("/books"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("Testowa1")));
}
}
Security class:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.authorizeRequests()
.antMatchers(HttpMethod.POST).authenticated().and()
.formLogin().and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
So first I want to test only POST methods with spring security. Ofcourse later I want to figure how to test it with my User Roles in Database :) But small steps... I dont know how to set authorize session. App is on spring boot 1.5.4.
Any advice or example on git will be usefull! My project is also on my github: http://ift.tt/2sdlv47
Aucun commentaire:
Enregistrer un commentaire