This library provides a wrapper for generating JWTs using Vonage-specific claims. It is mainly used by the Vonage Java Server SDK.
Learn more about Authenticating with JSON Web Tokens.
For Gradle:
dependencies {
implementation 'com.vonage:jwt:2.0.0'
}
For Maven:
<dependency>
<groupId>com.vonage</groupId>
<artifactId>jwt</artifactId>
<version>2.0.0</version>
</dependency>
The JWT library provides a Jwt.Builder
which can be used to construct a Jwt
representation.
The Jwt
class contains a generate()
method for generating JSON Web Signatures that can then
be used to authenticate with the API.
The API requires an application_id
claim, and the token needs to be signed with a private key.
The corresponding public key is uploaded to Vonage for signature verification.
The library expects you to provide a PKCS#8
key contents or file path.
To generate a JWT with these properties you can use:
var jws = Jwt.builder()
.applicationId("your-application-uuid")
.privateKeyContents("private key contents")
.build().generate();
You can also provide a Path
to the location of your private key:
var jws = Jwt.builder()
.applicationId("your-application-id")
.privateKeyPath("/path/to/private.key")
.build().generate();
All token claims (both standard and custom) can be set
using the builder's methods before calling .build()
. You can also leverage the underlying
Auth0 JWT library's builder using the withProperties
method. For example, to set the nbf
("not before") and exp
("expires at") claims as a
Date
or Instant
, you can do:
var jws = Jwt.builder()
.applicationId("your-application-id")
.privateKeyPath("/path/to/private.key")
.withProperties(jb -> jb
.withNotBefore(Instant.now())
.withExpiresAt(Instant.now().plus(Duration.ofHours(6)))
)
.build().generate();
In some instances, you might want to define custom claims.
// Add them individually using addClaim
var jws = Jwt.builder()
.applicationId("your-application-id")
.privateKeyPath("/path/to/private.key")
.addClaim("foo", "bar")
.addClaim("bat", "baz")
.build().generate();
// Or add multiples using a map
var jws = Jwt.builder()
.applicationId("your-application-id")
.privateKeyPath("/path/to/private.key")
.claims(Map.of("foo", "bar", "bat", "baz"))
.build().generate();
// Or add using the Auth0 builder
var jws = Jwt.builder()
.applicationId("your-application-id")
.privateKeyPath("/path/to/private.key")
.withProperties(jb -> jb.withClaim("claim-name", claimValue))
.build().generate();