Search in sources :

Example 31 with RSASSASigner

use of com.nimbusds.jose.crypto.RSASSASigner 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 32 with RSASSASigner

use of com.nimbusds.jose.crypto.RSASSASigner in project tomee by apache.

the class TokenUtils method generateJWTString.

public static String generateJWTString(String jsonResource, String keyId) throws Exception {
    byte[] byteBuffer = new byte[16384];
    currentThread().getContextClassLoader().getResource(jsonResource).openStream().read(byteBuffer);
    JSONParser parser = new JSONParser(DEFAULT_PERMISSIVE_MODE);
    JSONObject jwtJson = (JSONObject) parser.parse(byteBuffer);
    long currentTimeInSecs = (System.currentTimeMillis() / 1000);
    long expirationTime = currentTimeInSecs + 1000;
    jwtJson.put(Claims.iat.name(), currentTimeInSecs);
    jwtJson.put(Claims.auth_time.name(), currentTimeInSecs);
    jwtJson.put(Claims.exp.name(), expirationTime);
    SignedJWT signedJWT = new SignedJWT(new JWSHeader.Builder(RS256).keyID(// /privateKey002.pem
    keyId).type(JWT).build(), parse(jwtJson));
    signedJWT.sign(new RSASSASigner(readPrivateKey(keyId)));
    return signedJWT.serialize();
}
Also used : JSONObject(net.minidev.json.JSONObject) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) JSONParser(net.minidev.json.parser.JSONParser) SignedJWT(com.nimbusds.jwt.SignedJWT)

Example 33 with RSASSASigner

use of com.nimbusds.jose.crypto.RSASSASigner in project tomee by apache.

the class BookstoreTest method token.

private String token(boolean managerUser) {
    JSONObject claims = new JSONObject();
    claims.put(Claims.iss.name(), "https://server.example.com");
    claims.put(Claims.upn.name(), managerUser ? "alice@example.com" : "bob@exmaple.com");
    long currentTimeInSecs = System.currentTimeMillis() / 1000;
    claims.put(Claims.iat.name(), currentTimeInSecs);
    claims.put(Claims.auth_time.name(), currentTimeInSecs);
    claims.put(Claims.exp.name(), currentTimeInSecs + 300);
    claims.put(Claims.jti.name(), "a-123");
    claims.put(Claims.sub.name(), "24400320");
    claims.put(Claims.preferred_username.name(), managerUser ? "alice" : "bob");
    claims.put(Claims.aud.name(), "s6BhdRkqt3");
    List<String> groups = new ArrayList<>();
    if (managerUser) {
        groups.add("manager");
        groups.add("reader");
    } else {
        groups.add("reader");
    }
    claims.put(Claims.groups.name(), groups);
    try {
        PrivateKey pk = readPrivateKey("/privateKey.pem");
        JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("/privateKey.pem").type(JOSEObjectType.JWT).build();
        JWTClaimsSet claimsSet = JWTClaimsSet.parse(claims);
        SignedJWT jwt = new SignedJWT(header, claimsSet);
        jwt.sign(new RSASSASigner(pk));
        return jwt.serialize();
    } catch (Exception e) {
        throw new RuntimeException("Could not sign JWT");
    }
}
Also used : TokenUtils.readPrivateKey(org.superbiz.bookstore.TokenUtils.readPrivateKey) PrivateKey(java.security.PrivateKey) ArrayList(java.util.ArrayList) SignedJWT(com.nimbusds.jwt.SignedJWT) JSONObject(net.minidev.json.JSONObject) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 34 with RSASSASigner

use of com.nimbusds.jose.crypto.RSASSASigner in project tomee by apache.

the class Tokens method asToken.

public String asToken(final String claims) throws Exception {
    try {
        final JWSHeader header = new JWSHeader.Builder(new JWSAlgorithm("RS" + hashSize, Requirement.OPTIONAL)).type(JOSEObjectType.JWT).build();
        final JWTClaimsSet claimsSet = JWTClaimsSet.parse(claims);
        final SignedJWT jwt = new SignedJWT(header, claimsSet);
        jwt.sign(new RSASSASigner(privateKey));
        return jwt.serialize();
    } catch (Exception e) {
        throw new RuntimeException("Could not sign JWT");
    }
}
Also used : JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 35 with RSASSASigner

use of com.nimbusds.jose.crypto.RSASSASigner in project Payara by payara.

the class AzureSecretsConfigSource method bootstrap.

@Override
public void bootstrap() {
    StringBuilder contentBuilder = new StringBuilder();
    try {
        final File tokenFile = getPrivateKeyFile();
        if (tokenFile == null) {
            LOGGER.warning("Couldn't find private key file, make sure it's configured.");
        } else {
            try (Stream<String> stream = Files.lines(tokenFile.toPath())) {
                stream.forEach(s -> contentBuilder.append(s));
            }
        }
    } catch (Exception ex) {
        LOGGER.log(Level.WARNING, "Couldn't find or read the private key file, make sure it exists.", ex);
    }
    Map<String, String> data = new HashMap<>();
    String tenantId = configuration.getTenantId();
    String clientId = configuration.getClientId();
    if (tenantId == null || clientId == null) {
        LOGGER.warning("An error occurred while authenticating Azure to get a token, makes sure Azure Config Source has been configured with correct  configuration options.");
    } else {
        data.put("grant_type", "client_credentials");
        data.put("client_id", clientId);
        data.put("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
        data.put("scope", SCOPE_URL);
        try {
            final SignedJWT jwt = buildJwt(clientId, String.format(AUTH_URL, tenantId), configuration.getThumbprint());
            jwt.sign(new RSASSASigner(parsePrivateKey(contentBuilder.toString())));
            data.put("client_assertion", jwt.serialize());
        } catch (NoSuchAlgorithmException | InvalidKeySpecException | JOSEException e) {
            LOGGER.log(Level.WARNING, "An error occurred while signing the Azure auth token", e);
        }
        this.authClient = new OAuth2Client(String.format(AUTH_URL, tenantId), data);
    }
}
Also used : HashMap(java.util.HashMap) OAuth2Client(fish.payara.microprofile.config.extensions.oauth.OAuth2Client) SignedJWT(com.nimbusds.jwt.SignedJWT) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) JOSEException(com.nimbusds.jose.JOSEException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) File(java.io.File) JOSEException(com.nimbusds.jose.JOSEException)

Aggregations

RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)37 SignedJWT (com.nimbusds.jwt.SignedJWT)23 JWSHeader (com.nimbusds.jose.JWSHeader)20 JWSSigner (com.nimbusds.jose.JWSSigner)15 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)13 JSONObject (net.minidev.json.JSONObject)10 JWSObject (com.nimbusds.jose.JWSObject)9 Payload (com.nimbusds.jose.Payload)9 PrivateKey (java.security.PrivateKey)6 JOSEException (com.nimbusds.jose.JOSEException)5 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 MockResponse (okhttp3.mockwebserver.MockResponse)4 MockWebServer (okhttp3.mockwebserver.MockWebServer)4 Test (org.junit.jupiter.api.Test)4 Authentication (org.springframework.security.core.Authentication)4 JOSEObjectType (com.nimbusds.jose.JOSEObjectType)3 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)3 RSASSAVerifier (com.nimbusds.jose.crypto.RSASSAVerifier)3 Date (java.util.Date)3