Java Code Examples for org.jose4j.jws.JsonWebSignature#setHeader()

The following examples show how to use org.jose4j.jws.JsonWebSignature#setHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JwtSignatureImpl.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
private String signInternal(Key signingKey) {
    JwtBuildUtils.setDefaultJwtClaims(claims);
    JsonWebSignature jws = new JsonWebSignature();
    for (Map.Entry<String, Object> entry : headers.entrySet()) {
        jws.setHeader(entry.getKey(), entry.getValue());
    }
    if (!headers.containsKey("typ")) {
        jws.setHeader("typ", "JWT");
    }
    String algorithm = (String) headers.get("alg");
    if (algorithm == null) {
        algorithm = keyAlgorithm(headers, signingKey);
        jws.setAlgorithmHeaderValue(algorithm);
    }
    if ("none".equals(algorithm)) {
        jws.setAlgorithmConstraints(AlgorithmConstraints.ALLOW_ONLY_NONE);
    }
    jws.setPayload(claims.toJson());
    if (signingKey instanceof RSAPrivateKey && algorithm.startsWith("RS")
            && ((RSAPrivateKey) signingKey).getModulus().bitLength() < 2048) {
        throw ImplMessages.msg.signKeySizeMustBeHigher(algorithm);
    }
    jws.setKey(signingKey);
    try {
        return jws.getCompactSerialization();
    } catch (Exception ex) {
        throw ImplMessages.msg.signJwtTokenFailed(ex.getMessage(), ex);
    }
}
 
Example 2
Source File: JwtGenerator.java    From cloud-iot-core-androidthings with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting()
JwtGenerator(
        @NonNull KeyPair keyPair,
        @NonNull String jwtAudience,
        @NonNull Duration tokenLifetime,
        @NonNull Clock clock) {
    checkNotNull(keyPair, "keypair");
    checkNotNull(jwtAudience, "JWT audience");
    checkNotNull(tokenLifetime, "Token lifetime");
    checkNotNull(clock, "Clock");

    String algorithm = keyPair.getPrivate().getAlgorithm();
    if (!algorithm.equals(RSA_ALGORITHM) && !algorithm.equals(EC_ALGORITHM)) {
        throw new IllegalArgumentException("Keys use unsupported algorithm.");
    }

    mTokenLifetime = tokenLifetime;
    mClock = clock;

    mJws = new JsonWebSignature();
    mJws.setAlgorithmHeaderValue(algorithm.equals("RSA")
            ? AlgorithmIdentifiers.RSA_USING_SHA256
            : AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256);
    mJws.setHeader("typ", "JWT");
    mJws.setKey(keyPair.getPrivate());

    mClaims = new JwtClaims();
    mClaims.setAudience(jwtAudience);
}
 
Example 3
Source File: TokenUtils.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to generate a JWT string from a JSON resource file that is signed by the private key
 * using either RS256 or ES256 algorithm, possibly with invalid fields.
 *
 * @param pk - the private key to sign the token with
 * @param kid - the kid claim to assign to the token
 * @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 signClaims(PrivateKey pk, String kid, String jsonResName,
    Set<InvalidClaims> invalidClaims, Map<String, Long> timeClaims) throws Exception {

    if (invalidClaims == null) {
        invalidClaims = Collections.emptySet();
    }
    JwtClaims claims = createJwtClaims(jsonResName, invalidClaims, timeClaims);
    
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    if (kid != null) {
        jws.setKeyIdHeaderValue(kid);
    }
    jws.setHeader("typ", "JWT");
    
    if (invalidClaims.contains(InvalidClaims.ALG)) {
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
        jws.setKey(KeyGenerator.getInstance("HMACSHA256").generateKey());
    }
    else {
        jws.setAlgorithmHeaderValue(pk instanceof RSAPrivateKey ? AlgorithmIdentifiers.RSA_USING_SHA256
            : AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256);
        if (invalidClaims.contains(InvalidClaims.SIGNER)) {
            // Generate a new random private key to sign with to test invalid signatures
            pk = generateKeyPair(2048).getPrivate();
        }
        jws.setKey(pk);   
    }
    return jws.getCompactSerialization();
}
 
Example 4
Source File: JwtToken.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Generates base64 representation of JWT token sign using "RS256" algorithm
 *
 * getHeader().toBase64UrlEncode() + "." + getClaim().toBase64UrlEncode() + "." + sign
 *
 * @return base64 representation of JWT token
 */
public String sign() {
    for(JwtTokenDecorator decorator: JwtTokenDecorator.all()){
        decorator.decorate(this);
    }

    for(JwtSigningKeyProvider signer: JwtSigningKeyProvider.all()){
        SigningKey k = signer.select(this);
        if (k!=null) {
            try {
                JsonWebSignature jsonWebSignature = new JsonWebSignature();
                jsonWebSignature.setPayload(claim.toString());
                jsonWebSignature.setKey(k.getKey());
                jsonWebSignature.setKeyIdHeaderValue(k.getKid());
                jsonWebSignature.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
                jsonWebSignature.setHeader(HeaderParameterNames.TYPE, "JWT");

                return jsonWebSignature.getCompactSerialization();
            } catch (JoseException e) {
                String msg = "Failed to sign JWT token: " + e.getMessage();
                LOGGER.log(Level.SEVERE, "Failed to sign JWT token", e);
                throw new ServiceException.UnexpectedErrorException(msg, e);
            }
        }
    }

    throw new IllegalStateException("No key is available to sign a token");
}
 
Example 5
Source File: Operation.java    From pingid-api-playground with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private String buildRequestToken(JSONObject requestBody) {
	
	JSONObject requestHeader = buildRequestHeader();
	
	JSONObject payload = new JSONObject();
	payload.put("reqHeader", requestHeader);
	payload.put("reqBody", requestBody);
	
	JsonWebSignature jws = new JsonWebSignature();

	jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
	jws.setHeader("orgAlias", this.orgAlias);
	jws.setHeader("token", this.token);
	
	jws.setPayload(payload.toJSONString());
	
    // Set the verification key
    HmacKey key = new HmacKey(Base64.decode(this.useBase64Key));
    jws.setKey(key);
	
	String jwsCompactSerialization = null;
	try {
		jwsCompactSerialization = jws.getCompactSerialization();
	} catch (JoseException e) {
		e.printStackTrace();
	}
	
	this.requestToken = jwsCompactSerialization;
			
	return jwsCompactSerialization;
}
 
Example 6
Source File: BoxDeveloperEditionAPIConnection.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
private String constructJWTAssertion(NumericDate now) {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(this.getClientID());
    claims.setAudience(JWT_AUDIENCE);
    if (now == null) {
        claims.setExpirationTimeMinutesInTheFuture(0.5f);
    } else {
        now.addSeconds(30L);
        claims.setExpirationTime(now);
    }
    claims.setSubject(this.entityID);
    claims.setClaim("box_sub_type", this.entityType.toString());
    claims.setGeneratedJwtId(64);

    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(this.decryptPrivateKey());
    jws.setAlgorithmHeaderValue(this.getAlgorithmIdentifier());
    jws.setHeader("typ", "JWT");
    if ((this.publicKeyID != null) && !this.publicKeyID.isEmpty()) {
        jws.setHeader("kid", this.publicKeyID);
    }

    String assertion;

    try {
        assertion = jws.getCompactSerialization();
    } catch (JoseException e) {
        throw new BoxAPIException("Error serializing JSON Web Token assertion.", e);
    }

    return assertion;
}
 
Example 7
Source File: PushService.java    From org.openhab.ui.habot with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Send a notification and wait for the response.
 *
 * @param notification
 * @return
 * @throws GeneralSecurityException
 * @throws IOException
 * @throws JoseException
 * @throws ExecutionException
 * @throws InterruptedException
 */
public Future<Response> send(Notification notification)
        throws GeneralSecurityException, IOException, JoseException, ExecutionException, InterruptedException {
    assert (verifyKeyPair());

    BaseEncoding base64url = BaseEncoding.base64Url();

    Encrypted encrypted = encrypt(notification.getPayload(), notification.getUserPublicKey(),
            notification.getUserAuth(), notification.getPadSize());

    byte[] dh = Utils.savePublicKey((ECPublicKey) encrypted.getPublicKey());
    byte[] salt = encrypted.getSalt();

    Invocation.Builder invocationBuilder = ClientBuilder.newClient().target(notification.getEndpoint()).request();
    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>();
    headers.add("TTL", String.valueOf(notification.getTTL()));

    if (notification.hasPayload()) {
        headers.add("Content-Type", "application/octet-stream");
        headers.add("Content-Encoding", "aesgcm");
        headers.add("Encryption", "salt=" + base64url.omitPadding().encode(salt));
        headers.add("Crypto-Key", "dh=" + base64url.encode(dh));
    }

    if (notification.isGcm()) {
        if (gcmApiKey == null) {
            throw new IllegalStateException(
                    "An GCM API key is needed to send a push notification to a GCM endpoint.");
        }

        headers.add("Authorization", "key=" + gcmApiKey);
    }

    if (vapidEnabled() && !notification.isGcm()) {
        JwtClaims claims = new JwtClaims();
        claims.setAudience(notification.getOrigin());
        claims.setExpirationTimeMinutesInTheFuture(12 * 60);
        claims.setSubject(subject);

        JsonWebSignature jws = new JsonWebSignature();
        jws.setHeader("typ", "JWT");
        jws.setHeader("alg", "ES256");
        jws.setPayload(claims.toJson());
        jws.setKey(privateKey);
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256);

        headers.add("Authorization", "WebPush " + jws.getCompactSerialization());

        byte[] pk = Utils.savePublicKey((ECPublicKey) publicKey);

        if (headers.containsKey("Crypto-Key")) {
            headers.putSingle("Crypto-Key",
                    headers.getFirst("Crypto-Key") + ";p256ecdsa=" + base64url.omitPadding().encode(pk));
        } else {
            headers.add("Crypto-Key", "p256ecdsa=" + base64url.encode(pk));
        }
    }

    invocationBuilder.headers(headers);

    if (notification.hasPayload()) {
        return invocationBuilder.async().post(Entity.entity(encrypted.getCiphertext(),
                new Variant(MediaType.APPLICATION_OCTET_STREAM_TYPE, (String) null, "aesgcm")));
    } else {
        return invocationBuilder.async().post(null);
    }
}