Skip to content

Commit f1630a0

Browse files
committed
Added support for JWT CSRF in Spring Security
1 parent 6a057f3 commit f1630a0

8 files changed

Lines changed: 213 additions & 0 deletions

File tree

‎jjwt/pom.xml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,17 @@
2828
<groupId>org.springframework.boot</groupId>
2929
<artifactId>spring-boot-devtools</artifactId>
3030
</dependency>
31+
3132
<dependency>
3233
<groupId>org.springframework.boot</groupId>
3334
<artifactId>spring-boot-starter-thymeleaf</artifactId>
3435
</dependency>
3536

37+
<dependency>
38+
<groupId>org.springframework.boot</groupId>
39+
<artifactId>spring-boot-starter-security</artifactId>
40+
</dependency>
41+
3642
<dependency>
3743
<groupId>org.springframework.boot</groupId>
3844
<artifactId>spring-boot-starter-test</artifactId>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package io.jsonwebtoken.jjwtfun.config;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
import org.springframework.beans.factory.annotation.Value;
6+
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
7+
import org.springframework.context.annotation.Bean;
8+
import org.springframework.context.annotation.Configuration;
9+
import org.springframework.security.web.csrf.CsrfTokenRepository;
10+
11+
@Configuration
12+
public class CSRFConfig {
13+
14+
15+
private static final Logger log = LoggerFactory.getLogger(CSRFConfig.class);
16+
17+
@Value("#{ @environment['jjwtfun.secret'] ?: 'secret' }")
18+
String secret;
19+
20+
@Bean
21+
@ConditionalOnMissingBean
22+
public CsrfTokenRepository jwtCsrfTokenRepository() {
23+
return new JWTCsrfTokenRepository(secret);
24+
}
25+
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package io.jsonwebtoken.jjwtfun.config;
2+
3+
import io.jsonwebtoken.Jwts;
4+
import io.jsonwebtoken.SignatureAlgorithm;
5+
import org.slf4j.Logger;
6+
import org.slf4j.LoggerFactory;
7+
import org.springframework.security.web.csrf.CsrfToken;
8+
import org.springframework.security.web.csrf.CsrfTokenRepository;
9+
import org.springframework.security.web.csrf.DefaultCsrfToken;
10+
11+
import javax.servlet.http.HttpServletRequest;
12+
import javax.servlet.http.HttpServletResponse;
13+
import javax.servlet.http.HttpSession;
14+
import java.io.UnsupportedEncodingException;
15+
import java.util.Date;
16+
import java.util.UUID;
17+
18+
public class JWTCsrfTokenRepository implements CsrfTokenRepository {
19+
20+
private static final Logger log = LoggerFactory.getLogger(JWTCsrfTokenRepository.class);
21+
private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = CSRFConfig.class.getName().concat(".CSRF_TOKEN");
22+
23+
private String secret;
24+
25+
public JWTCsrfTokenRepository(String secret) {
26+
this.secret = secret;
27+
}
28+
29+
@Override
30+
public CsrfToken generateToken(HttpServletRequest request) {
31+
32+
String id = UUID.randomUUID().toString().replace("-", "");
33+
34+
Date now = new Date();
35+
Date exp = new Date(System.currentTimeMillis() + (1000*60)); // 1 minute
36+
37+
String token;
38+
try {
39+
token = Jwts.builder()
40+
.setId(id)
41+
.setIssuedAt(now)
42+
.setNotBefore(now)
43+
.setExpiration(exp)
44+
.signWith(SignatureAlgorithm.HS256, secret.getBytes("UTF-8"))
45+
.compact();
46+
} catch (UnsupportedEncodingException e) {
47+
log.error("Unable to create CSRf JWT: {}", e.getMessage(), e);
48+
token = id;
49+
}
50+
51+
return new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", token);
52+
}
53+
54+
@Override
55+
public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
56+
if (token == null) {
57+
HttpSession session = request.getSession(false);
58+
if (session != null) {
59+
session.removeAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME);
60+
}
61+
}
62+
else {
63+
HttpSession session = request.getSession();
64+
session.setAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME, token);
65+
}
66+
}
67+
68+
@Override
69+
public CsrfToken loadToken(HttpServletRequest request) {
70+
HttpSession session = request.getSession(false);
71+
if (session == null) {
72+
return null;
73+
}
74+
return (CsrfToken) session.getAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME);
75+
}
76+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package io.jsonwebtoken.jjwtfun.config;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
6+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
7+
import org.springframework.security.web.csrf.CsrfTokenRepository;
8+
9+
@Configuration
10+
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
11+
12+
@Autowired
13+
CsrfTokenRepository jwtCsrfTokenRepository;
14+
15+
@Override
16+
protected void configure(HttpSecurity http) throws Exception {
17+
http
18+
.csrf().csrfTokenRepository(jwtCsrfTokenRepository).and()
19+
.authorizeRequests()
20+
.antMatchers("/**")
21+
.permitAll();
22+
}
23+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package io.jsonwebtoken.jjwtfun.controller;
2+
3+
import org.springframework.stereotype.Controller;
4+
import org.springframework.ui.Model;
5+
import org.springframework.web.bind.annotation.RequestMapping;
6+
import org.springframework.web.bind.annotation.RequestParam;
7+
8+
import static org.springframework.web.bind.annotation.RequestMethod.GET;
9+
import static org.springframework.web.bind.annotation.RequestMethod.POST;
10+
11+
@Controller
12+
public class FormController {
13+
14+
@RequestMapping(value = "/jwt-csrf-form", method = GET)
15+
public String csrfFormGet() {
16+
return "jwt-csrf-form";
17+
}
18+
19+
@RequestMapping(value = "/jwt-csrf-form", method = POST)
20+
public String csrfFormPost(@RequestParam(name = "_csrf") String csrf, Model model) {
21+
22+
model.addAttribute("csrf", csrf);
23+
24+
return "jwt-csrf-form-result";
25+
}
26+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<!DOCTYPE html>
2+
<html xmlns:th="http://www.thymeleaf.org">
3+
<head th:fragment="head">
4+
<meta charset="utf-8"/>
5+
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
6+
<meta name="viewport" content="width=device-width, initial-scale=1"/>
7+
<meta name="viewport" content="width=device-width"/>
8+
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,300,400italic,400,600italic,600,700italic,700,800italic,800" rel="stylesheet" type="text/css"/>
9+
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
10+
11+
<!--[if lt IE 9]>
12+
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
13+
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
14+
<![endif]-->
15+
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
16+
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
17+
</head>
18+
<body>
19+
<p>Nothing to see here, move along.</p>
20+
</body>
21+
</html>
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<!DOCTYPE html>
2+
<html lang="en" xmlns:th="http://www.thymeleaf.org">
3+
<head>
4+
<!--/*/ <th:block th:include="fragments/head :: head"/> /*/-->
5+
</head>
6+
<body>
7+
<div class="container-fluid">
8+
<div class="row">
9+
<div class="box col-md-6 col-md-offset-1">
10+
<h1>You made it!</h1>
11+
<div style="overflow: scroll">
12+
<h4 th:text="${csrf}">BLARG</h4>
13+
</div>
14+
</div>
15+
</div>
16+
</div>
17+
</body>
18+
</html>
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<!DOCTYPE html>
2+
<html lang="en" xmlns:th="http://www.thymeleaf.org">
3+
<head>
4+
<!--/*/ <th:block th:include="fragments/head :: head"/> /*/-->
5+
</head>
6+
<body>
7+
<div class="container-fluid">
8+
<div class="row">
9+
<div class="box col-md-6 col-md-offset-1">
10+
<p/>
11+
<form method="post" th:action="@{/jwt-csrf-form}">
12+
<input type="submit" class="btn btn-primary" value="Click Me!"/>
13+
</form>
14+
</div>
15+
</div>
16+
</div>
17+
</body>
18+
</html>

0 commit comments

Comments
 (0)