Skip to content

Commit 38e829e

Browse files
committed
Added JWT CSRF expired handling.
1 parent f1630a0 commit 38e829e

8 files changed

Lines changed: 91 additions & 16 deletions

File tree

‎jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/CSRFConfig.java‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package io.jsonwebtoken.jjwtfun.config;
22

3-
import org.slf4j.Logger;
4-
import org.slf4j.LoggerFactory;
53
import org.springframework.beans.factory.annotation.Value;
64
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
75
import org.springframework.context.annotation.Bean;
@@ -11,9 +9,6 @@
119
@Configuration
1210
public class CSRFConfig {
1311

14-
15-
private static final Logger log = LoggerFactory.getLogger(CSRFConfig.class);
16-
1712
@Value("#{ @environment['jjwtfun.secret'] ?: 'secret' }")
1813
String secret;
1914

‎jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/JWTCsrfTokenRepository.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@
1717

1818
public class JWTCsrfTokenRepository implements CsrfTokenRepository {
1919

20-
private static final Logger log = LoggerFactory.getLogger(JWTCsrfTokenRepository.class);
2120
private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = CSRFConfig.class.getName().concat(".CSRF_TOKEN");
2221

22+
private static final Logger log = LoggerFactory.getLogger(JWTCsrfTokenRepository.class);
2323
private String secret;
2424

2525
public JWTCsrfTokenRepository(String secret) {
@@ -32,7 +32,7 @@ public CsrfToken generateToken(HttpServletRequest request) {
3232
String id = UUID.randomUUID().toString().replace("-", "");
3333

3434
Date now = new Date();
35-
Date exp = new Date(System.currentTimeMillis() + (1000*60)); // 1 minute
35+
Date exp = new Date(System.currentTimeMillis() + (1000*30)); // 30 seconds
3636

3737
String token;
3838
try {
@@ -68,7 +68,7 @@ public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletRe
6868
@Override
6969
public CsrfToken loadToken(HttpServletRequest request) {
7070
HttpSession session = request.getSession(false);
71-
if (session == null) {
71+
if (session == null || "GET".equals(request.getMethod())) {
7272
return null;
7373
}
7474
return (CsrfToken) session.getAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME);
Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,72 @@
11
package io.jsonwebtoken.jjwtfun.config;
22

3+
import io.jsonwebtoken.JwtException;
4+
import io.jsonwebtoken.Jwts;
35
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.beans.factory.annotation.Qualifier;
7+
import org.springframework.beans.factory.annotation.Value;
48
import org.springframework.context.annotation.Configuration;
59
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
610
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
11+
import org.springframework.security.web.csrf.CsrfFilter;
12+
import org.springframework.security.web.csrf.CsrfToken;
713
import org.springframework.security.web.csrf.CsrfTokenRepository;
14+
import org.springframework.web.filter.OncePerRequestFilter;
15+
16+
import javax.servlet.FilterChain;
17+
import javax.servlet.RequestDispatcher;
18+
import javax.servlet.ServletException;
19+
import javax.servlet.http.HttpServletRequest;
20+
import javax.servlet.http.HttpServletResponse;
21+
import java.io.IOException;
822

923
@Configuration
1024
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
1125

26+
@Value("#{ @environment['jjwtfun.secret'] ?: 'secret' }")
27+
String secret;
28+
1229
@Autowired
1330
CsrfTokenRepository jwtCsrfTokenRepository;
1431

1532
@Override
1633
protected void configure(HttpSecurity http) throws Exception {
1734
http
18-
.csrf().csrfTokenRepository(jwtCsrfTokenRepository).and()
19-
.authorizeRequests()
20-
.antMatchers("/**")
21-
.permitAll();
35+
.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class)
36+
.csrf()
37+
.csrfTokenRepository(jwtCsrfTokenRepository)
38+
.ignoringAntMatchers("/dynamic-builder-general")
39+
.ignoringAntMatchers("/dynamic-builder-specific")
40+
.and().authorizeRequests()
41+
.antMatchers("/**")
42+
.permitAll();
43+
}
44+
45+
private class JwtCsrfValidatorFilter extends OncePerRequestFilter {
46+
47+
@Override
48+
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
49+
// NOTE: A real implementation should have a nonce cache so the token cannot be reused
50+
51+
CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
52+
53+
// CsrfFilter already made sure the token matched.
54+
// Here, we'll make sure it's not expired
55+
if ("POST".equals(request.getMethod()) && token != null) {
56+
try {
57+
Jwts.parser()
58+
.setSigningKey(secret.getBytes("UTF-8"))
59+
.parseClaimsJws(token.getToken());
60+
} catch (JwtException e) {
61+
// most likely an ExpiredJwtException, but this will handle any
62+
request.setAttribute("exception", e);
63+
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
64+
RequestDispatcher dispatcher = request.getRequestDispatcher("expired-jwt");
65+
dispatcher.forward(request, response);
66+
}
67+
}
68+
69+
filterChain.doFilter(request, response);
70+
}
2271
}
2372
}

‎jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/FormController.java‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,12 @@ public String csrfFormGet() {
1818

1919
@RequestMapping(value = "/jwt-csrf-form", method = POST)
2020
public String csrfFormPost(@RequestParam(name = "_csrf") String csrf, Model model) {
21-
2221
model.addAttribute("csrf", csrf);
23-
2422
return "jwt-csrf-form-result";
2523
}
24+
25+
@RequestMapping("/expired-jwt")
26+
public String expiredJwt() {
27+
return "expired-jwt";
28+
}
2629
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<html xmlns:th="http://www.thymeleaf.org">
2+
<head>
3+
<!--/*/ <th:block th:include="fragments/head :: head"/> /*/-->
4+
</head>
5+
<body>
6+
<div class="container-fluid">
7+
<div class="row">
8+
<div class="box col-md-6 col-md-offset-3">
9+
<h1>JWT CSRF Token expired</h1>
10+
<h3 th:text="${exception.message}"></h3>
11+
12+
<a href="/jwt-csrf-form" class="btn btn-primary">Back</a>
13+
</div>
14+
</div>
15+
</div>
16+
</body>
17+
</html>

‎jjwt/src/main/resources/templates/fragments/head.html‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,17 @@
88
<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"/>
99
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
1010

11+
<style>
12+
body {
13+
margin-top: 60px;
14+
}
15+
.box {
16+
padding: 50px;
17+
text-align: center;
18+
vertical-align: middle;
19+
}
20+
</style>
21+
1122
<!--[if lt IE 9]>
1223
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
1324
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>

‎jjwt/src/main/resources/templates/jwt-csrf-form-result.html‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
<body>
77
<div class="container-fluid">
88
<div class="row">
9-
<div class="box col-md-6 col-md-offset-1">
9+
<div class="box col-md-6 col-md-offset-3">
1010
<h1>You made it!</h1>
1111
<div style="overflow: scroll">
1212
<h4 th:text="${csrf}">BLARG</h4>

‎jjwt/src/main/resources/templates/jwt-csrf-form.html‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
<body>
77
<div class="container-fluid">
88
<div class="row">
9-
<div class="box col-md-6 col-md-offset-1">
9+
<div class="box col-md-6 col-md-offset-3">
1010
<p/>
1111
<form method="post" th:action="@{/jwt-csrf-form}">
1212
<input type="submit" class="btn btn-primary" value="Click Me!"/>

0 commit comments

Comments
 (0)