Skip to content

Commit b0a1959

Browse files
maibinpivovarit
authored andcommitted
Spring Security + Thymeleaf (CSRF) (eugenp#695)
* Expression-Based Access Control PermitAll, hasRole, hasAnyRole etc. I modified classes regards to Security * Added test cases for Spring Security Expressions * Handler Interceptor - logging example * Test for logger interceptor * Removed conflicted part * UserInterceptor (adding user information to model) * Spring Handler Interceptor - session timers * Spring Security CSRF attack protection with Thymeleaf
1 parent 043a6bd commit b0a1959

8 files changed

Lines changed: 224 additions & 49 deletions

File tree

‎spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,15 @@
1414
import org.springframework.test.web.servlet.MockMvc;
1515
import org.springframework.test.web.servlet.request.RequestPostProcessor;
1616
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
17+
import org.springframework.transaction.annotation.Transactional;
1718
import org.springframework.web.context.WebApplicationContext;
1819

1920
import com.fasterxml.jackson.core.JsonProcessingException;
2021
import com.fasterxml.jackson.databind.ObjectMapper;
2122

2223
@RunWith(SpringJUnit4ClassRunner.class)
2324
@WebAppConfiguration
25+
@Transactional
2426
public class CsrfAbstractIntegrationTest {
2527

2628
@Autowired

‎spring-thymeleaf/pom.xml‎

Lines changed: 83 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -8,24 +8,24 @@
88
<properties>
99
<java-version>1.7</java-version>
1010
<!-- spring -->
11-
<org.springframework-version>4.1.8.RELEASE</org.springframework-version>
11+
<org.springframework-version>4.3.3.RELEASE</org.springframework-version>
1212
<javax.servlet-version>3.0.1</javax.servlet-version>
1313
<!-- logging -->
14-
<org.slf4j.version>1.7.12</org.slf4j.version>
15-
<logback.version>1.1.3</logback.version>
14+
<org.slf4j.version>1.7.12</org.slf4j.version>
15+
<logback.version>1.1.3</logback.version>
1616
<!-- thymeleaf -->
1717
<org.thymeleaf-version>2.1.4.RELEASE</org.thymeleaf-version>
1818
<!-- validation -->
1919
<javax.validation-version>1.1.0.Final</javax.validation-version>
2020
<org.hibernate-version>5.1.2.Final</org.hibernate-version>
21-
21+
2222
<!-- Maven plugins -->
2323
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
2424
<maven-war-plugin.version>2.6</maven-war-plugin.version>
2525
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
2626
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
2727
</properties>
28-
28+
2929
<dependencies>
3030
<!-- Spring -->
3131
<dependency>
@@ -45,6 +45,17 @@
4545
<artifactId>spring-webmvc</artifactId>
4646
<version>${org.springframework-version}</version>
4747
</dependency>
48+
<!-- Spring Security -->
49+
<dependency>
50+
<groupId>org.springframework.security</groupId>
51+
<artifactId>spring-security-web</artifactId>
52+
<version>4.1.3.RELEASE</version>
53+
</dependency>
54+
<dependency>
55+
<groupId>org.springframework.security</groupId>
56+
<artifactId>spring-security-config</artifactId>
57+
<version>4.1.3.RELEASE</version>
58+
</dependency>
4859
<!-- Thymeleaf -->
4960
<dependency>
5061
<groupId>org.thymeleaf</groupId>
@@ -57,29 +68,29 @@
5768
<version>${org.thymeleaf-version}</version>
5869
</dependency>
5970
<!-- Logging -->
60-
<!-- logging -->
61-
<dependency>
62-
<groupId>org.slf4j</groupId>
63-
<artifactId>slf4j-api</artifactId>
64-
<version>${org.slf4j.version}</version>
65-
</dependency>
66-
<dependency>
67-
<groupId>ch.qos.logback</groupId>
68-
<artifactId>logback-classic</artifactId>
69-
<version>${logback.version}</version>
70-
<!-- <scope>runtime</scope> -->
71-
</dependency>
72-
<dependency>
73-
<groupId>org.slf4j</groupId>
74-
<artifactId>jcl-over-slf4j</artifactId>
75-
<version>${org.slf4j.version}</version>
76-
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
77-
</dependency>
78-
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
79-
<groupId>org.slf4j</groupId>
80-
<artifactId>log4j-over-slf4j</artifactId>
81-
<version>${org.slf4j.version}</version>
82-
</dependency>
71+
<!-- logging -->
72+
<dependency>
73+
<groupId>org.slf4j</groupId>
74+
<artifactId>slf4j-api</artifactId>
75+
<version>${org.slf4j.version}</version>
76+
</dependency>
77+
<dependency>
78+
<groupId>ch.qos.logback</groupId>
79+
<artifactId>logback-classic</artifactId>
80+
<version>${logback.version}</version>
81+
<!-- <scope>runtime</scope> -->
82+
</dependency>
83+
<dependency>
84+
<groupId>org.slf4j</groupId>
85+
<artifactId>jcl-over-slf4j</artifactId>
86+
<version>${org.slf4j.version}</version>
87+
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
88+
</dependency>
89+
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
90+
<groupId>org.slf4j</groupId>
91+
<artifactId>log4j-over-slf4j</artifactId>
92+
<version>${org.slf4j.version}</version>
93+
</dependency>
8394
<!-- Servlet -->
8495
<dependency>
8596
<groupId>javax.servlet</groupId>
@@ -98,6 +109,31 @@
98109
<artifactId>hibernate-validator</artifactId>
99110
<version>${org.hibernate-version}</version>
100111
</dependency>
112+
<!-- test scoped -->
113+
114+
<dependency>
115+
<groupId>org.springframework</groupId>
116+
<artifactId>spring-test</artifactId>
117+
<version>4.1.3.RELEASE</version>
118+
<scope>test</scope>
119+
</dependency>
120+
121+
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-test -->
122+
<dependency>
123+
<groupId>org.springframework.security</groupId>
124+
<artifactId>spring-security-test</artifactId>
125+
<version>4.1.3.RELEASE</version>
126+
<scope>test</scope>
127+
</dependency>
128+
129+
<!-- https://mvnrepository.com/artifact/junit/junit -->
130+
<dependency>
131+
<groupId>junit</groupId>
132+
<artifactId>junit</artifactId>
133+
<version>4.12</version>
134+
<scope>test</scope>
135+
</dependency>
136+
101137
</dependencies>
102138
<build>
103139
<plugins>
@@ -129,25 +165,25 @@
129165
</systemPropertyVariables>
130166
</configuration>
131167
</plugin>
132-
<plugin>
133-
<groupId>org.codehaus.cargo</groupId>
134-
<artifactId>cargo-maven2-plugin</artifactId>
135-
<version>${cargo-maven2-plugin.version}</version>
136-
<configuration>
137-
<wait>true</wait>
138-
<container>
139-
<containerId>jetty8x</containerId>
140-
<type>embedded</type>
141-
<systemProperties>
142-
</systemProperties>
143-
</container>
144-
<configuration>
145-
<properties>
146-
<cargo.servlet.port>8082</cargo.servlet.port>
147-
</properties>
148-
</configuration>
149-
</configuration>
150-
</plugin>
168+
<plugin>
169+
<groupId>org.codehaus.cargo</groupId>
170+
<artifactId>cargo-maven2-plugin</artifactId>
171+
<version>${cargo-maven2-plugin.version}</version>
172+
<configuration>
173+
<wait>true</wait>
174+
<container>
175+
<containerId>jetty8x</containerId>
176+
<type>embedded</type>
177+
<systemProperties>
178+
</systemProperties>
179+
</container>
180+
<configuration>
181+
<properties>
182+
<cargo.servlet.port>8082</cargo.servlet.port>
183+
</properties>
184+
</configuration>
185+
</configuration>
186+
</plugin>
151187
</plugins>
152188
</build>
153189
</project>
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package com.baeldung.thymeleaf.config;
2+
3+
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
4+
5+
public class InitSecurity extends AbstractSecurityWebApplicationInitializer {
6+
7+
public InitSecurity() {
8+
super(WebMVCSecurity.class);
9+
10+
}
11+
}

‎spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ protected Class<?>[] getRootConfigClasses() {
2020

2121
@Override
2222
protected Class<?>[] getServletConfigClasses() {
23-
return new Class<?>[] { WebMVCConfig.class };
23+
return new Class<?>[] { WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class };
2424
}
2525

2626
@Override

‎spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package com.baeldung.thymeleaf.config;
22

3-
import com.baeldung.thymeleaf.formatter.NameFormatter;
43
import org.springframework.context.annotation.Bean;
54
import org.springframework.context.annotation.ComponentScan;
65
import org.springframework.context.annotation.Configuration;
@@ -14,6 +13,8 @@
1413
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
1514
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
1615

16+
import com.baeldung.thymeleaf.formatter.NameFormatter;
17+
1718
@Configuration
1819
@EnableWebMvc
1920
@ComponentScan({ "com.baeldung.thymeleaf" })
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.baeldung.thymeleaf.config;
2+
3+
import org.springframework.context.annotation.Bean;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.security.authentication.AuthenticationManager;
6+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
7+
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
8+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
9+
import org.springframework.security.config.annotation.web.builders.WebSecurity;
10+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
11+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
12+
13+
@Configuration
14+
@EnableWebSecurity
15+
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
16+
public class WebMVCSecurity extends WebSecurityConfigurerAdapter {
17+
18+
@Bean
19+
@Override
20+
public AuthenticationManager authenticationManagerBean() throws Exception {
21+
return super.authenticationManagerBean();
22+
}
23+
24+
public WebMVCSecurity() {
25+
super();
26+
}
27+
28+
@Override
29+
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
30+
auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER");
31+
}
32+
33+
@Override
34+
public void configure(final WebSecurity web) throws Exception {
35+
web.ignoring().antMatchers("/resources/**");
36+
}
37+
38+
@Override
39+
protected void configure(final HttpSecurity http) throws Exception {
40+
http
41+
.authorizeRequests()
42+
.anyRequest()
43+
.authenticated()
44+
.and()
45+
.httpBasic()
46+
.and()
47+
;
48+
}
49+
50+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
5+
</head>
6+
<body>
7+
<form action="http://localhost:8080/spring-thymeleaf/saveStudent" method="post">
8+
<input type="hidden" name="payload" value="CSRF attack!"/>
9+
<input type="submit" />
10+
</form>
11+
</body>
12+
</html>
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package org.baeldung.security.csrf;
2+
3+
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
4+
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
5+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
6+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
7+
8+
import javax.servlet.Filter;
9+
10+
import org.junit.Before;
11+
import org.junit.Test;
12+
import org.junit.runner.RunWith;
13+
import org.springframework.beans.factory.annotation.Autowired;
14+
import org.springframework.http.MediaType;
15+
import org.springframework.mock.web.MockHttpSession;
16+
import org.springframework.test.context.ContextConfiguration;
17+
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
18+
import org.springframework.test.context.web.WebAppConfiguration;
19+
import org.springframework.test.web.servlet.MockMvc;
20+
import org.springframework.test.web.servlet.request.RequestPostProcessor;
21+
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
22+
import org.springframework.web.context.WebApplicationContext;
23+
24+
import com.baeldung.thymeleaf.config.InitSecurity;
25+
import com.baeldung.thymeleaf.config.WebApp;
26+
import com.baeldung.thymeleaf.config.WebMVCConfig;
27+
import com.baeldung.thymeleaf.config.WebMVCSecurity;
28+
29+
@RunWith(SpringJUnit4ClassRunner.class)
30+
@WebAppConfiguration
31+
@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class })
32+
public class CsrfEnabledIntegrationTest {
33+
34+
@Autowired
35+
WebApplicationContext wac;
36+
@Autowired
37+
MockHttpSession session;
38+
39+
private MockMvc mockMvc;
40+
41+
@Autowired
42+
private Filter springSecurityFilterChain;
43+
44+
protected RequestPostProcessor testUser() {
45+
return user("user1").password("user1Pass").roles("USER");
46+
}
47+
48+
@Before
49+
public void setup() {
50+
mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build();
51+
}
52+
53+
@Test
54+
public void addStudentWithoutCSRF() throws Exception {
55+
mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser())).andExpect(status().isForbidden());
56+
}
57+
58+
@Test
59+
public void addStudentWithCSRF() throws Exception {
60+
mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser()).with(csrf())).andExpect(status().isOk());
61+
}
62+
63+
}

0 commit comments

Comments
 (0)