Skip to content

Commit 7653328

Browse files
committed
csrf test
1 parent 6846997 commit 7653328

6 files changed

Lines changed: 171 additions & 1 deletion

File tree

‎spring-security-rest/pom.xml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,13 @@
153153
<scope>test</scope>
154154
</dependency>
155155

156+
<dependency>
157+
<groupId>org.springframework.security</groupId>
158+
<artifactId>spring-security-test</artifactId>
159+
<version>${org.springframework.security.version}</version>
160+
</dependency>
161+
162+
156163
<dependency>
157164
<groupId>com.jayway.restassured</groupId>
158165
<artifactId>rest-assured</artifactId>

‎spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ protected void configure(final HttpSecurity http) throws Exception {// @formatte
4242
.authenticationEntryPoint(restAuthenticationEntryPoint)
4343
.and()
4444
.authorizeRequests()
45-
.antMatchers("/api/**").authenticated()
45+
.antMatchers("/**").authenticated()
4646
.and()
4747
.formLogin()
4848
.successHandler(authenticationSuccessHandler)
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package org.baeldung.spring;
2+
3+
import org.baeldung.security.MySavedRequestAwareAuthenticationSuccessHandler;
4+
import org.baeldung.security.RestAuthenticationEntryPoint;
5+
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.context.annotation.Bean;
7+
import org.springframework.context.annotation.ComponentScan;
8+
import org.springframework.context.annotation.Configuration;
9+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
10+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
11+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
12+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
13+
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
14+
15+
@Configuration
16+
@EnableWebSecurity
17+
@ComponentScan("org.baeldung.security")
18+
public class SecurityWithCsrfConfig extends WebSecurityConfigurerAdapter {
19+
20+
@Autowired
21+
private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
22+
23+
@Autowired
24+
private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;
25+
26+
public SecurityWithCsrfConfig() {
27+
super();
28+
}
29+
30+
//
31+
32+
@Override
33+
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
34+
auth.inMemoryAuthentication().withUser("temporary").password("temporary").roles("ADMIN").and().withUser("user").password("userPass").roles("USER");
35+
}
36+
37+
@Override
38+
protected void configure(final HttpSecurity http) throws Exception {// @formatter:off
39+
http
40+
.exceptionHandling()
41+
.authenticationEntryPoint(restAuthenticationEntryPoint)
42+
.and()
43+
.authorizeRequests()
44+
.antMatchers("/**").authenticated()
45+
.and()
46+
.formLogin()
47+
.successHandler(authenticationSuccessHandler)
48+
.failureHandler(new SimpleUrlAuthenticationFailureHandler())
49+
.and()
50+
.logout();
51+
} // @formatter:on
52+
53+
@Bean
54+
public MySavedRequestAwareAuthenticationSuccessHandler mySuccessHandler() {
55+
return new MySavedRequestAwareAuthenticationSuccessHandler();
56+
}
57+
58+
@Bean
59+
public SimpleUrlAuthenticationFailureHandler myFailureHandler() {
60+
return new SimpleUrlAuthenticationFailureHandler();
61+
}
62+
63+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package org.baeldung.csrf;
2+
3+
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
4+
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
5+
6+
import javax.servlet.Filter;
7+
8+
import org.baeldung.persistence.model.Foo;
9+
import org.junit.Before;
10+
import org.junit.runner.RunWith;
11+
import org.springframework.beans.factory.annotation.Autowired;
12+
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
13+
import org.springframework.test.context.web.WebAppConfiguration;
14+
import org.springframework.test.web.servlet.MockMvc;
15+
import org.springframework.test.web.servlet.request.RequestPostProcessor;
16+
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
17+
import org.springframework.web.context.WebApplicationContext;
18+
19+
import com.fasterxml.jackson.core.JsonProcessingException;
20+
import com.fasterxml.jackson.databind.ObjectMapper;
21+
22+
@RunWith(SpringJUnit4ClassRunner.class)
23+
@WebAppConfiguration
24+
public class CsrfAbstractIntegrationTest {
25+
@Autowired
26+
private WebApplicationContext context;
27+
28+
@Autowired
29+
private Filter springSecurityFilterChain;
30+
31+
protected MockMvc mvc;
32+
33+
@Before
34+
public void setup() {
35+
mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();
36+
}
37+
38+
protected RequestPostProcessor testUser() {
39+
return user("user").password("userPass").roles("USER");
40+
}
41+
42+
protected String createFoo() throws JsonProcessingException {
43+
return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6)));
44+
}
45+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package org.baeldung.csrf;
2+
3+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
4+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
5+
6+
import org.baeldung.spring.ClientWebConfig;
7+
import org.baeldung.spring.SecurityJavaConfig;
8+
import org.baeldung.spring.SwaggerConfig;
9+
import org.baeldung.spring.WebConfig;
10+
import org.junit.Test;
11+
import org.springframework.http.MediaType;
12+
import org.springframework.test.context.ContextConfiguration;
13+
14+
@ContextConfiguration(classes = { SecurityJavaConfig.class, ClientWebConfig.class, WebConfig.class, SwaggerConfig.class })
15+
public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest {
16+
17+
@Test
18+
public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception {
19+
mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized());
20+
}
21+
22+
@Test
23+
public void givenAuth_whenAddFoo_thenCreated() throws Exception {
24+
mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated());
25+
}
26+
27+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package org.baeldung.csrf;
2+
3+
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
4+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
5+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
6+
7+
import org.baeldung.spring.ClientWebConfig;
8+
import org.baeldung.spring.SecurityWithCsrfConfig;
9+
import org.baeldung.spring.SwaggerConfig;
10+
import org.baeldung.spring.WebConfig;
11+
import org.junit.Test;
12+
import org.springframework.http.MediaType;
13+
import org.springframework.test.context.ContextConfiguration;
14+
15+
@ContextConfiguration(classes = { SecurityWithCsrfConfig.class, ClientWebConfig.class, WebConfig.class, SwaggerConfig.class })
16+
public class CsrfEnabledIntegrationTest extends CsrfAbstractIntegrationTest {
17+
18+
@Test
19+
public void givenNoCsrf_whenAddFoo_thenForbidden() throws Exception {
20+
mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isForbidden());
21+
}
22+
23+
@Test
24+
public void givenCsrf_whenAddFoo_thenCreated() throws Exception {
25+
mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser()).with(csrf())).andExpect(status().isCreated());
26+
}
27+
28+
}

0 commit comments

Comments
 (0)