Search in sources :

Example 16 with JWSSigner

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();
}
Also used : JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Instant(java.time.Instant) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSSigner(com.nimbusds.jose.JWSSigner) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 17 with JWSSigner

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;
}
Also used : JWT(org.apache.knox.gateway.services.security.token.impl.JWT) AliasServiceException(org.apache.knox.gateway.services.security.AliasServiceException) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) KeystoreServiceException(org.apache.knox.gateway.services.security.KeystoreServiceException) JWTToken(org.apache.knox.gateway.services.security.token.impl.JWTToken) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWSSigner(com.nimbusds.jose.JWSSigner) TokenServiceException(org.apache.knox.gateway.services.security.token.TokenServiceException)

Example 18 with JWSSigner

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();
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) MACSigner(com.nimbusds.jose.crypto.MACSigner) InputStream(java.io.InputStream) SecureRandom(java.security.SecureRandom) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) JSONObject(net.minidev.json.JSONObject) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) BigInteger(java.math.BigInteger) JSONParser(net.minidev.json.parser.JSONParser) JWSSigner(com.nimbusds.jose.JWSSigner) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 19 with JWSSigner

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;
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) ApplicationIdentity(it.unibo.arces.wot.sepa.engine.dependability.authorization.identities.ApplicationIdentity) ArrayList(java.util.ArrayList) SignedJWT(com.nimbusds.jwt.SignedJWT) Date(java.util.Date) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWSSigner(com.nimbusds.jose.JWSSigner) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 20 with JWSSigner

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();
}
Also used : PrivateKey(java.security.PrivateKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) URIBuilder(org.apache.http.client.utils.URIBuilder) MultipartEntityBuilder(nl.nn.adapterframework.http.mime.MultipartEntityBuilder) SignedJWT(com.nimbusds.jwt.SignedJWT) KeyStore(java.security.KeyStore) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) DefaultJWSSignerFactory(com.nimbusds.jose.crypto.factories.DefaultJWSSignerFactory) X509KeyManager(javax.net.ssl.X509KeyManager) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager) JWSSigner(com.nimbusds.jose.JWSSigner) JWSHeader(com.nimbusds.jose.JWSHeader) JWK(com.nimbusds.jose.jwk.JWK)

Aggregations

JWSSigner (com.nimbusds.jose.JWSSigner)29 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)21 JWSHeader (com.nimbusds.jose.JWSHeader)18 SignedJWT (com.nimbusds.jwt.SignedJWT)18 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)13 JOSEException (com.nimbusds.jose.JOSEException)5 MACSigner (com.nimbusds.jose.crypto.MACSigner)5 PrivateKey (java.security.PrivateKey)5 Date (java.util.Date)4 JOSEObjectType (com.nimbusds.jose.JOSEObjectType)3 JWSObject (com.nimbusds.jose.JWSObject)3 Payload (com.nimbusds.jose.Payload)3 JWK (com.nimbusds.jose.jwk.JWK)3 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)3 JsonArrayBuilder (javax.json.JsonArrayBuilder)3 JsonObjectBuilder (javax.json.JsonObjectBuilder)3 TokenServiceException (org.apache.knox.gateway.services.security.token.TokenServiceException)3 JWT (org.apache.knox.gateway.services.security.token.impl.JWT)3 JWTToken (org.apache.knox.gateway.services.security.token.impl.JWTToken)3 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)2