use of com.nimbusds.jose.JWSSigner in project java-docs-samples by GoogleCloudPlatform.
the class BuildIapRequest method getSignedJwt.
private static String getSignedJwt(ServiceAccountCredentials credentials, String iapClientId) throws Exception {
Instant now = Instant.now(clock);
long expirationTime = now.getEpochSecond() + EXPIRATION_TIME_IN_SECONDS;
// generate jwt signed by service account
// header must contain algorithm ("alg") and key ID ("kid")
JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(credentials.getPrivateKeyId()).build();
// set required claims
JWTClaimsSet claims = new JWTClaimsSet.Builder().audience(OAUTH_TOKEN_URI).issuer(credentials.getClientEmail()).subject(credentials.getClientEmail()).issueTime(Date.from(now)).expirationTime(Date.from(Instant.ofEpochSecond(expirationTime))).claim("target_audience", iapClientId).build();
// sign using service account private key
JWSSigner signer = new RSASSASigner(credentials.getPrivateKey());
SignedJWT signedJwt = new SignedJWT(jwsHeader, claims);
signedJwt.sign(signer);
return signedJwt.serialize();
}
use of com.nimbusds.jose.JWSSigner in project knox by apache.
the class DefaultTokenAuthorityService method issueToken.
@Override
public JWT issueToken(Principal p, List<String> audiences, String algorithm, long expires) throws TokenServiceException {
String[] claimArray = new String[4];
claimArray[0] = "KNOXSSO";
claimArray[1] = p.getName();
claimArray[2] = null;
if (expires == -1) {
claimArray[3] = null;
} else {
claimArray[3] = String.valueOf(expires);
}
JWT token = null;
if (SUPPORTED_SIG_ALGS.contains(algorithm)) {
token = new JWTToken(algorithm, claimArray, audiences);
RSAPrivateKey key;
char[] passphrase = null;
try {
passphrase = getSigningKeyPassphrase();
} catch (AliasServiceException e) {
throw new TokenServiceException(e);
}
try {
key = (RSAPrivateKey) ks.getSigningKey(getSigningKeyAlias(), passphrase);
JWSSigner signer = new RSASSASigner(key);
token.sign(signer);
} catch (KeystoreServiceException e) {
throw new TokenServiceException(e);
}
} else {
throw new TokenServiceException("Cannot issue token - Unsupported algorithm");
}
return token;
}
use of com.nimbusds.jose.JWSSigner in project tomee by apache.
the class TokenUtils method generateTokenString.
/**
* Utility method to generate a JWT string from a JSON resource file that is signed by the privateKey.pem
* test resource key, possibly with invalid fields.
*
* @param jsonResName - name of test resources file
* @param invalidClaims - the set of claims that should be added with invalid values to test failure modes
* @param timeClaims - used to return the exp, iat, auth_time claims
* @return the JWT string
* @throws Exception on parse failure
*/
public static String generateTokenString(String jsonResName, Set<InvalidClaims> invalidClaims, Map<String, Long> timeClaims) throws Exception {
if (invalidClaims == null) {
invalidClaims = Collections.emptySet();
}
InputStream contentIS = TokenUtils.class.getResourceAsStream(jsonResName);
byte[] tmp = new byte[4096];
int length = contentIS.read(tmp);
byte[] content = new byte[length];
System.arraycopy(tmp, 0, content, 0, length);
JSONParser parser = new JSONParser(DEFAULT_PERMISSIVE_MODE);
JSONObject jwtContent = (JSONObject) parser.parse(content);
// Change the issuer to INVALID_ISSUER for failure testing if requested
if (invalidClaims.contains(InvalidClaims.ISSUER)) {
jwtContent.put(Claims.iss.name(), "INVALID_ISSUER");
}
long currentTimeInSecs = currentTimeInSecs();
long exp = currentTimeInSecs + 300;
// Check for an input exp to override the default of now + 300 seconds
if (timeClaims != null && timeClaims.containsKey(Claims.exp.name())) {
exp = timeClaims.get(Claims.exp.name());
}
jwtContent.put(Claims.iat.name(), currentTimeInSecs);
jwtContent.put(Claims.auth_time.name(), currentTimeInSecs);
// If the exp claim is not updated, it will be an old value that should be seen as expired
if (!invalidClaims.contains(InvalidClaims.EXP)) {
jwtContent.put(Claims.exp.name(), exp);
}
if (timeClaims != null) {
timeClaims.put(Claims.iat.name(), currentTimeInSecs);
timeClaims.put(Claims.auth_time.name(), currentTimeInSecs);
timeClaims.put(Claims.exp.name(), exp);
}
PrivateKey pk;
if (invalidClaims.contains(InvalidClaims.SIGNER)) {
// Generate a new random private key to sign with to test invalid signatures
KeyPair keyPair = generateKeyPair(2048);
pk = keyPair.getPrivate();
} else {
// Use the test private key associated with the test public key for a valid signature
pk = readPrivateKey("/privateKey.pem");
}
// Create RSA-signer with the private key
JWSSigner signer = new RSASSASigner(pk);
JWTClaimsSet claimsSet = JWTClaimsSet.parse(jwtContent);
JWSAlgorithm alg = JWSAlgorithm.RS256;
if (invalidClaims.contains(InvalidClaims.ALG)) {
alg = JWSAlgorithm.HS256;
SecureRandom random = new SecureRandom();
BigInteger secret = BigInteger.probablePrime(256, random);
signer = new MACSigner(secret.toByteArray());
}
JWSHeader jwtHeader = new JWSHeader.Builder(alg).keyID("/privateKey.pem").type(JOSEObjectType.JWT).build();
SignedJWT signedJWT = new SignedJWT(jwtHeader, claimsSet);
signedJWT.sign(signer);
return signedJWT.serialize();
}
use of com.nimbusds.jose.JWSSigner in project SEPA by arces-wot.
the class SecurityManagerTest method generateToken.
private SignedJWT generateToken(DigitalIdentity identity, String password) throws ParseException, KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, JOSEException, SEPASecurityException {
// Prepare JWT with claims set
JWTClaimsSet.Builder claimsSetBuilder = new JWTClaimsSet.Builder();
// Define validity period
Date now = new Date();
long exp = 0;
if (identity.getClass().equals(DeviceIdentity.class)) {
exp = auth.getDeviceExpiringPeriod();
} else if (identity.getClass().equals(ApplicationIdentity.class)) {
exp = auth.getApplicationExpiringPeriod();
} else
exp = auth.getDefaultExpiringPeriod();
Date expires = new Date(now.getTime() + exp * 1000);
claimsSetBuilder.issuer("http://issuer");
claimsSetBuilder.subject("http://subject");
ArrayList<String> audience = new ArrayList<String>();
audience.add("https://audience");
audience.add("wss://audience");
claimsSetBuilder.audience(audience);
claimsSetBuilder.expirationTime(expires);
claimsSetBuilder.issueTime(now);
claimsSetBuilder.jwtID(identity.getUid() + ":" + password + ":" + UUID.randomUUID());
JWTClaimsSet jwtClaims = claimsSetBuilder.build();
// ******************************
// Sign JWT with private RSA key
// ******************************
SignedJWT signedJWT;
signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), JWTClaimsSet.parse(jwtClaims.toString()));
// // Load the key from the key store
// KeyStore keystore = KeyStore.getInstance("JKS");
//
// keystore.load(new FileInputStream(jksFile), storePass.toCharArray());
// RSAKey jwk = RSAKey.load(keystore, alias, keyPass.toCharArray());
RSAKey jwk = configurationProvider.getRsaKey();
// Get the private and public keys to sign and verify
RSAPrivateKey privateKey = jwk.toRSAPrivateKey();
// Create RSA-signer with the private key
JWSSigner signer = new RSASSASigner(privateKey);
signedJWT.sign(signer);
return signedJWT;
}
use of com.nimbusds.jose.JWSSigner in project iaf by ibissource.
the class ApiListenerServletTest method createJWT.
private String createJWT() throws Exception {
JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).build();
JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
builder.issuer("JWTPipeTest");
builder.subject("UnitTest");
builder.audience("Framework");
builder.jwtID("1234");
SignedJWT signedJWT = new SignedJWT(jwsHeader, builder.build());
KeyStore keystore = PkiUtil.createKeyStore(TestFileUtils.getTestFileURL("/JWT/jwt_keystore.p12"), "geheim", KeystoreType.PKCS12, "Keys for signing");
KeyManager[] keymanagers = PkiUtil.createKeyManagers(keystore, "geheim", null);
X509KeyManager keyManager = (X509KeyManager) keymanagers[0];
PrivateKey privateKey = keyManager.getPrivateKey("1");
PublicKey publicKey = keystore.getCertificate("1").getPublicKey();
JWK jwk = new RSAKey.Builder((RSAPublicKey) publicKey).privateKey(privateKey).keyUse(KeyUse.SIGNATURE).keyOperations(Collections.singleton(KeyOperation.SIGN)).algorithm(JWSAlgorithm.RS256).keyStore(keystore).build();
DefaultJWSSignerFactory factory = new DefaultJWSSignerFactory();
JWSSigner jwsSigner = factory.createJWSSigner(jwk, JWSAlgorithm.RS256);
signedJWT.sign(jwsSigner);
return signedJWT.serialize();
}
Aggregations