0

I am creating a JWT using the following code:

long now = Instant.now().getEpochSecond();
long exp = now + TimeUnit.HOURS.toSeconds(1);
long nbf = now - TimeUnit.MINUTES.toSeconds(5);

String jwt = Jwts.builder()
                .setSubject("d45049c3-3441-40ef-ab4d-b9cd86a17225")
                .claim("iss", "d45049c3-3441-40ef-ab4d-b9cd86a17225")
                .claim("aud", "https://apporchard.epic.com/interconnect-aocurprd-oauth/oauth2/token")
                .claim("jti", UUID.randomUUID().toString())
                .claim("exp", exp)
                .claim("nbf", nbf)
                .claim("iat", now)
                .signWith(key, SignatureAlgorithm.RS384)
                .compact();

but when I look at the JSON version of the created JWT the header is

{
  "alg": "RS384"
}

and it is missing the "typ" field. I thought this field was mandatory.

jim
  • 41
  • 2

1 Answers1

2

The typ header is optional per RFC 7519, Section 5.1 (bold emphases are mine):

This is intended for use by the JWT application when values that are not JWTs could also be present in an application data structure that can contain a JWT object; the application can use this value to disambiguate among the different kinds of objects that might be present. It will typically not be used by applications when it is already known that the object is a JWT. This parameter is ignored by JWT implementations; any processing of this parameter is performed by the JWT application.

So, per the last bold line, JJWT (as a JWT implementation) will not set or read it because implementations ignore it.

You (as the JWT application in the above vernacular) can set the value yourself if you wish:

Jwts.builder().setHeaderParam("typ", yourMediaTypeValue)
    ...

but again, as the spec says, you don't need to do this if you already know that the string you're working with a jwt. You only really need to set that value if the JWT is embedded in other content and you need to tell the difference between the jwt and other content.

It is typically used for non-compact (full JSON) JWT documents and not compact JWS or JWE values where full JSON objects need to be disambiguated from other (non-compact) JSON values.

Community
  • 1
  • 1
Les Hazlewood
  • 18,480
  • 13
  • 68
  • 76