private static Header jwtHeader() { final Header header = new Header(); header.setAlgorithm("RS256"); header.setType("JWT"); return header; }
JsonWebSignature jws = new JsonWebSignature(); jws.setHeader("cty", "jwt");
/** * Parses the given ID token string and returns the parsed {@link GoogleIdToken}. * * @param jsonFactory JSON factory * @param idTokenString ID token string * @return parsed Google ID token */ public static GoogleIdToken parse(JsonFactory jsonFactory, String idTokenString) throws IOException { JsonWebSignature jws = JsonWebSignature.parser(jsonFactory).setPayloadClass(Payload.class).parse(idTokenString); return new GoogleIdToken(jws.getHeader(), (Payload) jws.getPayload(), jws.getSignatureBytes(), jws.getSignedContentBytes()); }
private String generateJwtAccess(URI uri) throws IOException { JsonWebSignature.Header header = new JsonWebSignature.Header(); header.setAlgorithm("RS256"); header.setType("JWT"); header.setKeyId(privateKeyId); JsonWebToken.Payload payload = new JsonWebToken.Payload(); long currentTime = clock.currentTimeMillis(); // Both copies of the email are required payload.setIssuer(clientEmail); payload.setSubject(clientEmail); payload.setAudience(uri.toString()); payload.setIssuedAtTimeSeconds(currentTime / 1000); payload.setExpirationTimeSeconds(currentTime / 1000 + LIFE_SPAN_SECS); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; String assertion; try { assertion = JsonWebSignature.signUsingRsaSha256( privateKey, jsonFactory, header, payload); } catch (GeneralSecurityException e) { throw new IOException("Error signing service account JWT access header with private key.", e); } return assertion; }
private static Payload jwtPayload(String targetAudience, String serviceAccountId, String tokenServerUrl) { final Payload payload = new Payload(); final long currentTime = System.currentTimeMillis(); payload.put("target_audience", targetAudience); payload.setIssuer(serviceAccountId); payload.setAudience(tokenServerUrl); payload.setIssuedAtTimeSeconds(currentTime / 1000); payload.setExpirationTimeSeconds(currentTime / 1000 + 3600); return payload; }
jws = JsonWebSignature.parser(JacksonFactory.getDefaultInstance()) .setPayloadClass(AttestationStatement.class).parse(signedAttestationStatment); } catch (IOException e) { System.err.println("Failure: " + signedAttestationStatment + " is not valid JWS " + cert = jws.verifySignature(); if (cert == null) { System.err.println("Failure: Signature verification failed."); AttestationStatement stmt = (AttestationStatement) jws.getPayload(); return stmt;
JsonWebSignature jws = JsonWebSignature.parser(mJFactory).setPayloadClass(Payload.class).parse(tokenString); GoogleIdToken token = new GoogleIdToken(jws.getHeader(), (Payload) jws.getPayload(), jws.getSignatureBytes(), jws.getSignedContentBytes()) { public boolean verify(GoogleIdTokenVerifier verifier) throws GeneralSecurityException, IOException { try { return verifier.verify(this); } catch (java.security.SignatureException e) { return false; } } };
private void verifyJwtAccess(Map<String, List<String>> metadata, String expectedEmail, URI expectedAudience, String expectedKeyId) throws IOException { assertNotNull(metadata); List<String> authorizations = metadata.get(AuthHttpConstants.AUTHORIZATION); assertNotNull("Authorization headers not found", authorizations); String assertion = null; for (String authorization : authorizations) { if (authorization.startsWith(JWT_ACCESS_PREFIX)) { assertNull("Multiple bearer assertions found", assertion); assertion = authorization.substring(JWT_ACCESS_PREFIX.length()); } } assertNotNull("Bearer assertion not found", assertion); JsonWebSignature signature = JsonWebSignature.parse(JSON_FACTORY, assertion); assertEquals(expectedEmail, signature.getPayload().getIssuer()); assertEquals(expectedEmail, signature.getPayload().getSubject()); assertEquals(expectedAudience.toString(), signature.getPayload().getAudience()); assertEquals(expectedKeyId, signature.getHeader().getKeyId()); }
// That other party, the receiver, can then use JsonWebEncryption to decrypt the message. JsonWebEncryption receiverJwe = new JsonWebEncryption(); // Set the compact serialization on new Json Web Encryption object //This is the received payload JWE payload receiverJwe.setCompactSerialization(result.toString()); // Symmetric encryption, like we are doing here, requires that both parties have the same key. // The key will have had to have been securely exchanged out-of-band somehow. receiverJwe.setKey(secretKeySpec); // Set the "alg" header, which indicates the key management mode for this JWE. // In this example we are using the direct key management mode, which means // the given key will be used directly as the content encryption key. //receiverJwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.DIRECT); //receiverJwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256); // Get the message that was encrypted in the JWE. This step performs the actual decryption steps. String jwsPayload = receiverJwe.getPlaintextString(); // And do whatever you need to do with the clear text message. System.out.println("plaintext: " + jwsPayload); // Create a new JsonWebSignature object JsonWebSignature jws = new JsonWebSignature(); jws.setCompactSerialization(jwsPayload); jws.setKey(secretKeySpec); boolean signatureVerified = jws.verifySignature(); // Do something useful with the result of signature verification System.out.println("JWS Signature is valid: " + signatureVerified); // Get the payload, or signed content, from the JWS String payload = jws.getPayload(); // Do something useful with the content System.out.println("JWS payload: " + payload);
JsonWebSignature jws = new JsonWebSignature(); jws.setPayload(claims.toJson()); jws.setKey(rsaJsonWebKey.getPrivateKey()); jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId()); jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256); String jwt = jws.getCompactSerialization();
private String generateJwtAccess(URI uri) throws IOException { JsonWebSignature.Header header = new JsonWebSignature.Header(); header.setAlgorithm("RS256"); header.setType("JWT"); header.setKeyId(privateKeyId); JsonWebToken.Payload payload = new JsonWebToken.Payload(); long currentTime = clock.currentTimeMillis(); // Both copies of the email are required payload.setIssuer(clientEmail); payload.setSubject(clientEmail); payload.setAudience(uri.toString()); payload.setIssuedAtTimeSeconds(currentTime / 1000); payload.setExpirationTimeSeconds(currentTime / 1000 + LIFE_SPAN_SECS); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; String assertion; try { assertion = JsonWebSignature.signUsingRsaSha256( privateKey, jsonFactory, header, payload); } catch (GeneralSecurityException e) { throw new IOException("Error signing service account JWT access header with private key.", e); } return assertion; }
/** Parses a JWT token string and extracts its headers and payload fields. */ public static FirebaseCustomAuthToken parse(JsonFactory jsonFactory, String tokenString) throws IOException { JsonWebSignature jws = JsonWebSignature.parser(jsonFactory).setPayloadClass(Payload.class).parse(tokenString); return new FirebaseCustomAuthToken( jws.getHeader(), (Payload) jws.getPayload(), jws.getSignatureBytes(), jws.getSignedContentBytes()); }
jws = JsonWebSignature.parser(JacksonFactory.getDefaultInstance()).setPayloadClass(AttestationStatement.class) .parse(signedAttestationStatment); } catch (IOException e) { System.err.println("Failure: " + signedAttestationStatment + " is not valid JWS " + "format."); try { if (tm != null) { cert = jws.verifySignature(tm); } else { cert = jws.verifySignature(); AttestationStatement stmt = (AttestationStatement) jws.getPayload(); return stmt;
JsonWebSignature jws = JsonWebSignature.parser(mJFactory).setPayloadClass(Payload.class).parse(tokenString); GoogleIdToken token = new GoogleIdToken(jws.getHeader(), (Payload) jws.getPayload(), jws.getSignatureBytes(), jws.getSignedContentBytes()) { public boolean verify(GoogleIdTokenVerifier verifier) throws GeneralSecurityException, IOException { try { return verifier.verify(this); } catch (java.security.SignatureException e) { return false; } } };
String createAssertion(JsonFactory jsonFactory, long currentTime, String audience) throws IOException { JsonWebSignature.Header header = new JsonWebSignature.Header(); header.setAlgorithm("RS256"); header.setType("JWT"); header.setKeyId(privateKeyId); JsonWebToken.Payload payload = new JsonWebToken.Payload(); payload.setIssuer(clientEmail); payload.setIssuedAtTimeSeconds(currentTime / 1000); payload.setExpirationTimeSeconds(currentTime / 1000 + 3600); payload.setSubject(serviceAccountUser); payload.put("scope", Joiner.on(' ').join(scopes)); if (audience == null) { payload.setAudience(OAuth2Utils.TOKEN_SERVER_URI.toString()); } else { payload.setAudience(audience); } String assertion; try { assertion = JsonWebSignature.signUsingRsaSha256( privateKey, jsonFactory, header, payload); } catch (GeneralSecurityException e) { throw new IOException( "Error signing service account access token request with private key.", e); } return assertion; }
static FirebaseToken parse(JsonFactory jsonFactory, String tokenString) throws IOException { try { JsonWebSignature jws = JsonWebSignature.parser(jsonFactory) .setPayloadClass(FirebaseTokenImpl.Payload.class) .parse(tokenString); return new FirebaseToken( new FirebaseTokenImpl( jws.getHeader(), (FirebaseTokenImpl.Payload) jws.getPayload(), jws.getSignatureBytes(), jws.getSignedContentBytes())); } catch (IOException e) { throw new IOException( "Decoding Firebase ID token failed. Make sure you passed the entire string JWT " + "which represents an ID token. See https://firebase.google.com/docs/auth/admin/" + "verify-id-tokens for details on how to retrieve an ID token.", e); } }
String createAssertion(JsonFactory jsonFactory, long currentTime, String audience) throws IOException { JsonWebSignature.Header header = new JsonWebSignature.Header(); header.setAlgorithm("RS256"); header.setType("JWT"); header.setKeyId(privateKeyId); JsonWebToken.Payload payload = new JsonWebToken.Payload(); payload.setIssuer(clientEmail); payload.setIssuedAtTimeSeconds(currentTime / 1000); payload.setExpirationTimeSeconds(currentTime / 1000 + 3600); payload.setSubject(serviceAccountUser); payload.put("scope", Joiner.on(' ').join(scopes)); if (audience == null) { payload.setAudience(OAuth2Utils.TOKEN_SERVER_URI.toString()); } else { payload.setAudience(audience); } String assertion; try { assertion = JsonWebSignature.signUsingRsaSha256( privateKey, jsonFactory, header, payload); } catch (GeneralSecurityException e) { throw new IOException( "Error signing service account access token request with private key.", e); } return assertion; }
JsonWebSignature.Header header = new JsonWebSignature.Header(); header.setAlgorithm("RS256"); header.setType("JWT"); header.setKeyId(serviceAccountPrivateKeyId); JsonWebToken.Payload payload = new JsonWebToken.Payload(); long currentTime = getClock().currentTimeMillis(); payload.setIssuer(serviceAccountId); payload.setAudience(getTokenServerEncodedUrl()); payload.setIssuedAtTimeSeconds(currentTime / 1000); payload.setExpirationTimeSeconds(currentTime / 1000 + 3600); payload.setSubject(serviceAccountUser); payload.put("scope", Joiner.on(' ').join(serviceAccountScopes)); try { String assertion = JsonWebSignature.signUsingRsaSha256( serviceAccountPrivateKey, getJsonFactory(), header, payload); TokenRequest request = new TokenRequest(
new JsonWebSignature.Header() .setAlgorithm("RS256") .setType("JWT") .setKeyId(getServiceAccountPrivateKeyId()); new JsonWebToken.Payload() .setIssuer(getServiceAccountId()) .setAudience(getTokenServerEncodedUrl()) .setIssuedAtTimeSeconds(currentTime / 1000) .setExpirationTimeSeconds(currentTime / 1000 + DEFAULT_TOKEN_EXPIRATION_SECONDS) .setSubject(getServiceAccountUser()); payload.put("scope", Joiner.on(' ').join(getServiceAccountScopes())); JsonWebSignature.signUsingRsaSha256( getServiceAccountPrivateKey(), getJsonFactory(), header, payload); TokenRequest request =
new JsonWebSignature.Header() .setAlgorithm("RS256") .setType("JWT") .setKeyId(getServiceAccountPrivateKeyId()); new JsonWebToken.Payload() .setIssuer(getServiceAccountId()) .setAudience(getTokenServerEncodedUrl()) .setIssuedAtTimeSeconds(currentTime / 1000) .setExpirationTimeSeconds(currentTime / 1000 + DEFAULT_TOKEN_EXPIRATION_SECONDS) .setSubject(getServiceAccountUser()); payload.put("scope", Joiner.on(' ').join(getServiceAccountScopes())); JsonWebSignature.signUsingRsaSha256( getServiceAccountPrivateKey(), getJsonFactory(), header, payload); TokenRequest request =