Development Environment:
- Spring Framework 3.2.3
- JJWT 0.12.3 (This issue also applies to the latest version 0.12.6)
The issue I’m facing is about “allowing special characters in JWT.”
A JWT consists of a header, payload, and signature, and it is formatted as xxxx.yyyy.zzzz
However, if special characters like ?@!#
are added to the end of the JWT, the server does not handle this as an error but instead processes the token normally.
ex, xxxx.yyyy.zzzz@!
I tried searching for a solution on Google but couldn’t find anything relevant, so I am posting my question here.
I’ve searched many places, but it was hard to find any writing on this… I’m wondering if this is a known issue and if there are any other solutions!
Below is the code I wrote.
((In the code below, the JwtProvider.java
class includes the isBase64URL
method, which checks whether the token contains only Base64URL-encoded characters, effectively preventing the use of special characters.))
/*
This is code that issues a JWT.
*/
@Component
public class JwtProvider {
private final SecretKey secretKey;
private final long accessExpiration;
private final long refreshExpiration;
private final String issuer;
public JwtUtil(@Value("${spring.jwt.secret}") String SECRET_KEY,
@Value("${spring.jwt.access-expiration}") long accessExpiration,
@Value("${spring.jwt.refresh-expiration}") long refreshExpiration,
@Value("${spring.jwt.issuer}") String issuer) {
this.secretKey = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), Jwts.SIG.HS256.key().build().getAlgorithm());
this.accessExpiration = accessExpiration;
this.refreshExpiration = refreshExpiration;
this.issuer = issuer;
}
public String generateAccessToken(String role, String username) {
return createJwt(createClaims(role, "access"), username, accessExpiration);
}
public String generateRefreshToken(String role, String username) {
return createJwt(createClaims(role, "refresh"), username, refreshExpiration);
}
private Map<String, Object> createClaims(String role, String category) {
Map<String, Object> claims = new HashMap<>();
claims.put("role", role);
claims.put("category", category);
return claims;
}
private String createJwt(Map<String, Object> claims, String subject, Long expirationTime) {
return Jwts.builder()
.subject(subject)
.claims(claims)
.issuer(issuer)
.issuedAt(new Date(System.currentTimeMillis()))
.expiration(new Date(System.currentTimeMillis() + expirationTime))
.signWith(secretKey)
.compact();
}
private Claims parseClaims(String token){
return Jwts.parser()
.verifyWith(secretKey)
.build()
.parseSignedClaims(token)
.getPayload();
}
public String getUsername(String token) {
return parseClaims(token).getSubject();
}
public String getRole(String token) {
return parseClaims(token).get("role", String.class);
}
public String getCategory(String token) {
return parseClaims(token).get("category", String.class);
}
public boolean isExpired(String token) {
return parseClaims(token).getExpiration().before(new Date());
}
public boolean isBase64URL(String token) {
return token.matches("^[0-9A-Za-z-_.]+$");
}
}
/*
This is code that handles JWT authentication. I only brought a part of it.
*/
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final UserDetailsService userDetailsService;
private final JwtProvider jwtProvider;
private final ObjectMapper objectMapper;
private final TokenBlackListService tokenBlackListService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String accessTokenGetHeader = request.getHeader(ACCESS_HEADER_VALUE);
if(accessTokenGetHeader == null || !accessTokenGetHeader.startsWith(TOKEN_PREFIX)) {
filterChain.doFilter(request, response);
return;
}
String accessToken = resolveAccessToken(response, accessTokenGetHeader);
if (accessToken == null)
return;
Authentication auth = getAuthentication(accessToken);
SecurityContextHolder.getContext().setAuthentication(auth);
filterChain.doFilter(request, response);
}
private String resolveAccessToken(HttpServletResponse response, String accessTokenGetHeader) throws IOException {
String accessToken = accessTokenGetHeader.substring(TOKEN_PREFIX.length()).trim();
if (!jwtProvider.isBase64URL(accessToken)) {
handleExceptionToken(response, ErrorCode.INVALID_ACCESS_TOKEN);
return null;
}
return accessToken;
}
}
The above is the solution I implemented using jwtProvider.isBase64URL()
, and below is the code that was originally used. I will provide screenshots showing the token value received through the logs and confirm that it worked successfully.
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String accessTokenGetHeader = request.getHeader(ACCESS_HEADER_VALUE);
if(accessTokenGetHeader == null || !accessTokenGetHeader.startsWith(TOKEN_PREFIX)) {
filterChain.doFilter(request, response);
return;
}
String accessToken = resolveAccessToken(response, accessTokenGetHeader);
if (accessToken == null)
return;
Authentication auth = getAuthentication(accessToken);
SecurityContextHolder.getContext().setAuthentication(auth);
log.info("success Authentication");
filterChain.doFilter(request, response);
}
private String resolveAccessToken(HttpServletResponse response, String accessTokenGetHeader) throws IOException {
String accessToken = accessTokenGetHeader.substring(TOKEN_PREFIX.length()).trim();
log.info("naccessToken: {}", accessToken);
return accessToken;
}
Results:
- When a valid token is entered,
send accessToken Like this. (No special characters)
Bearer eyJhbGciOiJlUzlNiJ9.eyJzdWiOiJOZXNKeyOliwicm9sZSI6|k9XTkVSliwiY2FOZWdvcnkiOiJhY2NIc3MiLCJ1c2VySWQiOjEsImlhdCI6MTcyNTQyNjQONywiZXhwljoxNZI1NDI4Mj@3fQ.eGNWj4xPgWuSPb_hUWrpDCo9iG4mfWjr-YMLyWKF1Js
log -> Bearer eyJhbGciOiJlUzlNiJ9.eyJzdWiOiJOZXNKeyOliwicm9sZSI6|k9XTkVSliwiY2FOZWdvcnkiOiJhY2NIc3MiLCJ1c2VySWQiOjEsImlhdCI6MTcyNTQyNjQONywiZXhwljoxNZI1NDI4Mj@3fQ.eGNWj4xPgWuSPb_hUWrpDCo9iG4mfWjr-YMLyWKF1Js
success Authentication
below, picture.
PostMan Api. send accessToken
token log
- When a special character is added to the token (used ‘@’ in the test),
send accessToken Like this. (I added the special character @@
to the end of the token.)
Bearer eyJhbGciOiJlUzlNiJ9.eyJzdWiOiJOZXNKeyOliwicm9sZSI6|k9XTkVSliwiY2FOZWdvcnkiOiJhY2NIc3MiLCJ1c2VySWQiOjEsImlhdCI6MTcyNTQyNjQONywiZXhwljoxNZI1NDI4Mj@3fQ.eGNWj4xPgWuSPb_hUWrpDCo9iG4mfWjr-YMLyWKF1Js@@
log -> Bearer eyJhbGciOiJlUzlNiJ9.eyJzdWiOiJOZXNKeyOliwicm9sZSI6|k9XTkVSliwiY2FOZWdvcnkiOiJhY2NIc3MiLCJ1c2VySWQiOjEsImlhdCI6MTcyNTQyNjQONywiZXhwljoxNZI1NDI4Mj@3fQ.eGNWj4xPgWuSPb_hUWrpDCo9iG4mfWjr-YMLyWKF1Js@@
success Authentication
below, picture.
PostMan Api. send accessToken
token log
This was done using an API platform called Postman, and it works correctly not only on this API platform but also when accessed directly from the website.
I experimented with placing various special characters in different parts of a JWT and observed how it behaves. I found that it only works correctly when the special characters are added at the end.
I would like to hear your thoughts on this!
5