Question regarding handling special characters in JWT

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:

  1. 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

  1. 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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật