JwtGenerator { public Jwt generateToken(String identity) throws CryptoException { JwtHeaderContent jwtHeaderContent = new JwtHeaderContent(apiPublicKeyIdentifier); JwtBodyContent jwtBodyContent = new JwtBodyContent(appId, identity, ttl, new Date()); Jwt jwtToken = new Jwt(jwtHeaderContent, jwtBodyContent); byte[] signature = this.accessTokenSigner .generateTokenSignature(ConvertionUtils.toBytes(jwtToken.unsigned()), apiKey); return new Jwt(jwtToken.stringRepresentation() + "." + Base64Url.encode(signature)); } JwtGenerator(String appId, VirgilPrivateKey apiKey, String apiPublicKeyIdentifier, TimeSpan ttl,
                      VirgilAccessTokenSigner accessTokenSigner); Jwt generateToken(String identity); Jwt generateToken(String identity, Map<String, String> additionalData);  }
@Test public void generateToken_autohandle_of_expireAt() throws CryptoException, InterruptedException { FakeDataFactory fake = new FakeDataFactory(); VirgilAccessTokenSigner signer = new VirgilAccessTokenSigner(); String appId = fake.getApplicationId(); VirgilPrivateKey privateKey = fake.getApiPrivateKey(); final String apiPublicKeyId = fake.getApiPublicKeyId(); JwtGenerator generator = new JwtGenerator(appId, privateKey, apiPublicKeyId, TimeSpan.fromTime(2, TimeUnit.SECONDS), signer); Jwt jwt = generator.generateToken(this.identity); assertFalse(jwt.isExpired()); Thread.sleep(3 * 1000); assertTrue(jwt.isExpired()); Jwt jwt2 = generator.generateToken(this.identity); assertFalse(jwt2.isExpired()); Thread.sleep(3 * 1000); assertTrue(jwt2.isExpired()); }
@Test public void generateToken_byIdentity() throws CryptoException { Jwt jwt = this.generator.generateToken(this.identity); assertNotNull(jwt); assertEquals(this.identity, jwt.getIdentity()); assertTrue(signer.verifyTokenSignature(jwt.getSignatureData(), ConvertionUtils.toBytes(jwt.unsigned()), fake.getApiPublicKey())); }
@Test public void generateToken_byIdentity_nullIdentity() throws CryptoException { Jwt jwt = this.generator.generateToken(null); assertNotNull(jwt); assertNull(jwt.getIdentity()); assertTrue(signer.verifyTokenSignature(jwt.getSignatureData(), ConvertionUtils.toBytes(jwt.unsigned()), fake.getApiPublicKey())); }