Skip to content

Commit 6b99ced

Browse files
author
Eugen
authored
Merge pull request eugenp#469 from dogeared/master
Add JJWT tutorial code to the tutorials repo
2 parents d577830 + 674471d commit 6b99ced

22 files changed

Lines changed: 838 additions & 0 deletions

‎jjwt/.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
.idea
2+
target
3+
*.iml

‎jjwt/README.md‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
## JWT Fun
2+
3+
This tutorial walks you through the various features supported by the [JJWT](https://github.com/jwtk/jjwt) library - a fluent interface Java JWT building and parsing library.
4+
5+
### Build and Run
6+
7+
It's super easy to build and exercise this tutorial.
8+
9+
```
10+
mvn clean install
11+
java -jar target/*.jar
12+
```
13+
14+
That's it!
15+
16+
You can hit the home endpoint with your favorite command-line http client. My favorite is: [httpie](https://github.com/jkbrzt/httpie)
17+
18+
`http localhost:8080`
19+
20+
```
21+
Available commands (assumes httpie - https://github.com/jkbrzt/httpie):
22+
23+
http http://localhost:8080/
24+
This usage message
25+
26+
http http://localhost:8080/static-builder
27+
build JWT from hardcoded claims
28+
29+
http POST http://localhost:8080/dynamic-builder-general claim-1=value-1 ... [claim-n=value-n]
30+
build JWT from passed in claims (using general claims map)
31+
32+
http POST http://localhost:8080/dynamic-builder-specific claim-1=value-1 ... [claim-n=value-n]
33+
build JWT from passed in claims (using specific claims methods)
34+
35+
http POST http://localhost:8080/dynamic-builder-compress claim-1=value-1 ... [claim-n=value-n]
36+
build DEFLATE compressed JWT from passed in claims
37+
38+
http http://localhost:8080/parser?jwt=<jwt>
39+
Parse passed in JWT
40+
41+
http http://localhost:8080/parser-enforce?jwt=<jwt>
42+
Parse passed in JWT enforcing the 'iss' registered claim and the 'hasMotorcycle' custom claim
43+
```
44+
45+
The Baeldung post that compliments this repo can be found [here](http://www.baeldung.com/)

‎jjwt/pom.xml‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
6+
<groupId>io.jsonwebtoken</groupId>
7+
<artifactId>jjwtfun</artifactId>
8+
<version>0.0.1-SNAPSHOT</version>
9+
<packaging>jar</packaging>
10+
11+
<name>jjwtfun</name>
12+
<description>Exercising the JJWT</description>
13+
14+
<parent>
15+
<groupId>org.springframework.boot</groupId>
16+
<artifactId>spring-boot-starter-parent</artifactId>
17+
<version>1.3.5.RELEASE</version>
18+
<relativePath/> <!-- lookup parent from repository -->
19+
</parent>
20+
21+
<properties>
22+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23+
<java.version>1.8</java.version>
24+
</properties>
25+
26+
<dependencies>
27+
<dependency>
28+
<groupId>org.springframework.boot</groupId>
29+
<artifactId>spring-boot-devtools</artifactId>
30+
</dependency>
31+
32+
<dependency>
33+
<groupId>org.springframework.boot</groupId>
34+
<artifactId>spring-boot-starter-thymeleaf</artifactId>
35+
</dependency>
36+
37+
<dependency>
38+
<groupId>org.springframework.boot</groupId>
39+
<artifactId>spring-boot-starter-security</artifactId>
40+
</dependency>
41+
42+
<dependency>
43+
<groupId>org.springframework.boot</groupId>
44+
<artifactId>spring-boot-starter-test</artifactId>
45+
<scope>test</scope>
46+
</dependency>
47+
48+
<dependency>
49+
<groupId>io.jsonwebtoken</groupId>
50+
<artifactId>jjwt</artifactId>
51+
<version>0.6.0</version>
52+
</dependency>
53+
</dependencies>
54+
55+
<build>
56+
<plugins>
57+
<plugin>
58+
<groupId>org.springframework.boot</groupId>
59+
<artifactId>spring-boot-maven-plugin</artifactId>
60+
</plugin>
61+
</plugins>
62+
</build>
63+
64+
65+
</project>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package io.jsonwebtoken.jjwtfun;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
public class JJWTFunApplication {
8+
9+
public static void main(String[] args) {
10+
SpringApplication.run(JJWTFunApplication.class, args);
11+
}
12+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package io.jsonwebtoken.jjwtfun.config;
2+
3+
import io.jsonwebtoken.jjwtfun.service.SecretService;
4+
import org.springframework.beans.factory.annotation.Autowired;
5+
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
6+
import org.springframework.context.annotation.Bean;
7+
import org.springframework.context.annotation.Configuration;
8+
import org.springframework.security.web.csrf.CsrfTokenRepository;
9+
10+
@Configuration
11+
public class CSRFConfig {
12+
13+
@Autowired
14+
SecretService secretService;
15+
16+
@Bean
17+
@ConditionalOnMissingBean
18+
public CsrfTokenRepository jwtCsrfTokenRepository() {
19+
return new JWTCsrfTokenRepository(secretService.getHS256SecretBytes());
20+
}
21+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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.util.Date;
15+
import java.util.UUID;
16+
17+
public class JWTCsrfTokenRepository implements CsrfTokenRepository {
18+
19+
private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = CSRFConfig.class.getName().concat(".CSRF_TOKEN");
20+
21+
private static final Logger log = LoggerFactory.getLogger(JWTCsrfTokenRepository.class);
22+
private byte[] secret;
23+
24+
public JWTCsrfTokenRepository(byte[] secret) {
25+
this.secret = secret;
26+
}
27+
28+
@Override
29+
public CsrfToken generateToken(HttpServletRequest request) {
30+
String id = UUID.randomUUID().toString().replace("-", "");
31+
32+
Date now = new Date();
33+
Date exp = new Date(System.currentTimeMillis() + (1000*30)); // 30 seconds
34+
35+
String token = Jwts.builder()
36+
.setId(id)
37+
.setIssuedAt(now)
38+
.setNotBefore(now)
39+
.setExpiration(exp)
40+
.signWith(SignatureAlgorithm.HS256, secret)
41+
.compact();
42+
43+
return new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", token);
44+
}
45+
46+
@Override
47+
public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
48+
if (token == null) {
49+
HttpSession session = request.getSession(false);
50+
if (session != null) {
51+
session.removeAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME);
52+
}
53+
}
54+
else {
55+
HttpSession session = request.getSession();
56+
session.setAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME, token);
57+
}
58+
}
59+
60+
@Override
61+
public CsrfToken loadToken(HttpServletRequest request) {
62+
HttpSession session = request.getSession(false);
63+
if (session == null || "GET".equals(request.getMethod())) {
64+
return null;
65+
}
66+
return (CsrfToken) session.getAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME);
67+
}
68+
}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package io.jsonwebtoken.jjwtfun.config;
2+
3+
import io.jsonwebtoken.JwtException;
4+
import io.jsonwebtoken.Jwts;
5+
import io.jsonwebtoken.jjwtfun.service.SecretService;
6+
import org.springframework.beans.factory.annotation.Autowired;
7+
import org.springframework.context.annotation.Configuration;
8+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
9+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
10+
import org.springframework.security.web.csrf.CsrfFilter;
11+
import org.springframework.security.web.csrf.CsrfToken;
12+
import org.springframework.security.web.csrf.CsrfTokenRepository;
13+
import org.springframework.web.filter.OncePerRequestFilter;
14+
15+
import javax.servlet.FilterChain;
16+
import javax.servlet.RequestDispatcher;
17+
import javax.servlet.ServletException;
18+
import javax.servlet.http.HttpServletRequest;
19+
import javax.servlet.http.HttpServletResponse;
20+
import java.io.IOException;
21+
import java.util.Arrays;
22+
23+
@Configuration
24+
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
25+
26+
@Autowired
27+
CsrfTokenRepository jwtCsrfTokenRepository;
28+
29+
@Autowired
30+
SecretService secretService;
31+
32+
// ordered so we can use binary search below
33+
private String[] ignoreCsrfAntMatchers = {
34+
"/dynamic-builder-compress",
35+
"/dynamic-builder-general",
36+
"/dynamic-builder-specific",
37+
"/set-secrets"
38+
};
39+
40+
@Override
41+
protected void configure(HttpSecurity http) throws Exception {
42+
http
43+
.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class)
44+
.csrf()
45+
.csrfTokenRepository(jwtCsrfTokenRepository)
46+
.ignoringAntMatchers(ignoreCsrfAntMatchers)
47+
.and().authorizeRequests()
48+
.antMatchers("/**")
49+
.permitAll();
50+
}
51+
52+
private class JwtCsrfValidatorFilter extends OncePerRequestFilter {
53+
54+
@Override
55+
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
56+
// NOTE: A real implementation should have a nonce cache so the token cannot be reused
57+
58+
CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
59+
60+
if (
61+
// only care if it's a POST
62+
"POST".equals(request.getMethod()) &&
63+
// ignore if the request path is in our list
64+
Arrays.binarySearch(ignoreCsrfAntMatchers, request.getServletPath()) < 0 &&
65+
// make sure we have a token
66+
token != null
67+
) {
68+
// CsrfFilter already made sure the token matched. Here, we'll make sure it's not expired
69+
try {
70+
Jwts.parser()
71+
.setSigningKeyResolver(secretService.getSigningKeyResolver())
72+
.parseClaimsJws(token.getToken());
73+
} catch (JwtException e) {
74+
// most likely an ExpiredJwtException, but this will handle any
75+
request.setAttribute("exception", e);
76+
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
77+
RequestDispatcher dispatcher = request.getRequestDispatcher("expired-jwt");
78+
dispatcher.forward(request, response);
79+
}
80+
}
81+
82+
filterChain.doFilter(request, response);
83+
}
84+
}
85+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package io.jsonwebtoken.jjwtfun.controller;
2+
3+
import io.jsonwebtoken.JwtException;
4+
import io.jsonwebtoken.MalformedJwtException;
5+
import io.jsonwebtoken.SignatureException;
6+
import io.jsonwebtoken.jjwtfun.model.JwtResponse;
7+
import org.springframework.http.HttpStatus;
8+
import org.springframework.web.bind.annotation.ExceptionHandler;
9+
import org.springframework.web.bind.annotation.ResponseStatus;
10+
11+
public class BaseController {
12+
13+
@ResponseStatus(HttpStatus.BAD_REQUEST)
14+
@ExceptionHandler({SignatureException.class, MalformedJwtException.class, JwtException.class})
15+
public JwtResponse exception(Exception e) {
16+
JwtResponse response = new JwtResponse();
17+
response.setStatus(JwtResponse.Status.ERROR);
18+
response.setMessage(e.getMessage());
19+
response.setExceptionType(e.getClass().getName());
20+
21+
return response;
22+
}
23+
}

0 commit comments

Comments
 (0)