Java Code Examples for com.auth0.jwt.algorithms.Algorithm#RSA256

The following examples show how to use com.auth0.jwt.algorithms.Algorithm#RSA256 . 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: AuthenticationServiceJwtImpl.java    From alibaba-rsocket-broker with Apache License 2.0 8 votes vote down vote up
public String generateCredentials(String id, String[] organizations, String[] serviceAccounts, String[] roles, String[] authorities, String sub, String[] audience) throws Exception {
    Algorithm algorithmRSA256Private = Algorithm.RSA256(null, readPrivateKey());
    Arrays.sort(audience);
    Arrays.sort(organizations);
    JWTCreator.Builder builder = JWT.create()
            .withIssuer(iss)
            .withSubject(sub)
            .withAudience(audience)
            .withIssuedAt(new Date())
            .withClaim("id", id)
            .withArrayClaim("sas", serviceAccounts)
            .withArrayClaim("orgs", organizations);
    if (roles != null && roles.length > 0) {
        Arrays.sort(roles);
        builder = builder.withArrayClaim("roles", roles);
    }
    if (authorities != null && authorities.length > 0) {
        builder = builder.withArrayClaim("authorities", authorities);
    }
    return builder.sign(algorithmRSA256Private);
}
 
Example 2
Source File: RS256SignatureVerifier.java    From auth0-java with MIT License 6 votes vote down vote up
private static Algorithm getAlgorithm(final PublicKeyProvider publicKeyProvider) {
    return Algorithm.RSA256(new RSAKeyProvider() {
        @Override
        public RSAPublicKey getPublicKeyById(String keyId) {
            try {
                return publicKeyProvider.getPublicKeyById(keyId);
            } catch (PublicKeyProviderException pke) {
                throw new IdTokenValidationException(String.format("Could not find a public key for Key ID (kid) \"%s\"", keyId), pke);
            }
        }

        @Override
        public RSAPrivateKey getPrivateKey() {
            // no-op
            return null;
        }

        @Override
        public String getPrivateKeyId() {
            // no-op
            return null;
        }
    });
}
 
Example 3
Source File: TokenCreator.java    From cf-java-logging-support with Apache License 2.0 6 votes vote down vote up
public static String createToken(KeyPair keyPair, String issuer, Date issuedAt, Date expiresAt, String level)
                                                                                                              throws NoSuchAlgorithmException,
                                                                                                              NoSuchProviderException,
                                                                                                              DynamicLogLevelException {
    Algorithm rsa256 = Algorithm.RSA256((RSAPublicKey) keyPair.getPublic(), (RSAPrivateKey) keyPair.getPrivate());
    if (ALLOWED_DYNAMIC_LOGLEVELS.contains(level)) {
        return JWT.create().withIssuer(issuer).//
                  withIssuedAt(issuedAt). //
                  withExpiresAt(expiresAt).//
                  withClaim("level", level).sign(rsa256);
    } else {
        throw new DynamicLogLevelException("Dynamic Log-Level [" + level +
                                           "] provided in header is not valid. Allowed Values are " +
                                           ALLOWED_DYNAMIC_LOGLEVELS.toString());
    }
}
 
Example 4
Source File: ConstantTokenProviderTest.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
private String createToken() throws NoSuchAlgorithmException {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(2048);

    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    Algorithm algorithm = Algorithm.RSA256((
            RSAPublicKey) keyPair.getPublic(), (RSAPrivateKey) keyPair.getPrivate());

    return JWT.create()
            .withExpiresAt(Date.from(Instant.now().plusSeconds(120)))
            .withClaim("uid", "test")
            .sign(algorithm);
}
 
Example 5
Source File: JWTUtils.java    From docusign-java-client with MIT License 6 votes vote down vote up
/**
 * Helper method to create a JWT token for the JWT flow
 * @param rsaPrivateKey the byte contents of the RSA private key
 * @param oAuthBasePath DocuSign OAuth base path (account-d.docusign.com for the developer sandbox
and account.docusign.com for the production platform)
 * @param clientId DocuSign OAuth Client Id (AKA Integrator Key)
 * @param userId DocuSign user Id to be impersonated (This is a UUID)
 * @param expiresIn number of seconds remaining before the JWT assertion is considered as invalid
 * @param scopes space-separated string that represents the list of scopes to grant to the OAuth token.
 * @return a fresh JWT token
 * @throws IllegalArgumentException if one of the arguments is invalid
 * @throws JWTCreationException if not able to create a JWT token from the input parameters
 * @throws IOException if there is an issue with either the public or private file
 */
public static String generateJWTAssertionFromByteArray(byte[] rsaPrivateKey, String oAuthBasePath, String clientId, String userId, long expiresIn, String scopes) throws IllegalArgumentException, JWTCreationException, IOException {
	if (expiresIn <= 0L) {
		throw new IllegalArgumentException("expiresIn should be a non-negative value");
	}
	if (rsaPrivateKey == null || rsaPrivateKey.length == 0) {
		throw new IllegalArgumentException("rsaPrivateKey byte array is empty");
	}
	if (oAuthBasePath == null || "".equals(oAuthBasePath) || clientId == null || "".equals(clientId)) {
		throw new IllegalArgumentException("One of the arguments is null or empty");
	}
	
	RSAPrivateKey privateKey = readPrivateKeyFromByteArray(rsaPrivateKey, "RSA");
	Algorithm algorithm = Algorithm.RSA256(null, privateKey);
	long now = System.currentTimeMillis();
	JWTCreator.Builder builder = JWT.create()
			.withIssuer(clientId)
			.withAudience(oAuthBasePath)
			.withIssuedAt(new Date(now))
			.withClaim("scope", scopes)
			.withExpiresAt(new Date(now + expiresIn * 1000));
	if (userId != null && userId != "") {
		builder = builder.withSubject(userId);
	}
	return builder.sign(algorithm);
}
 
Example 6
Source File: JwtAuthenticationServiceImpl.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public JwtAuthenticationServiceImpl() throws Exception {
    File keyFile = new File(System.getProperty("user.home"), ".rsocket/jwt_rsa.pub");
    if (keyFile.exists()) {
        Algorithm algorithmRSA256Public = Algorithm.RSA256(readPublicKey(keyFile), null);
        this.verifiers.add(JWT.require(algorithmRSA256Public).withIssuer(iss).build());
    }
}
 
Example 7
Source File: AuthenticationServiceJwtImpl.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public AuthenticationServiceJwtImpl() throws Exception {
    File rsocketKeysDir = new File(System.getProperty("user.home"), ".rsocket");
    File publicKeyFile = new File(rsocketKeysDir, "jwt_rsa.pub");
    // generate RSA key pairs automatically
    if (!publicKeyFile.exists()) {
        if (!rsocketKeysDir.exists()) {
            //noinspection ResultOfMethodCallIgnored
            rsocketKeysDir.mkdir();
        }
        generateRSAKeyPairs(rsocketKeysDir);
    }
    Algorithm algorithmRSA256Public = Algorithm.RSA256(readPublicKey(), null);
    this.verifiers.add(JWT.require(algorithmRSA256Public).withIssuer(iss).build());
}
 
Example 8
Source File: JwtTokenExtractorTests.java    From botbuilder-java with MIT License 5 votes vote down vote up
private static String createTokenForCertificate(X509Certificate cert, PrivateKey privateKey, Date issuedAt) {
    RSAPublicKey publicKey = (RSAPublicKey) cert.getPublicKey();
    Algorithm algorithm = Algorithm.RSA256(publicKey, (RSAPrivateKey) privateKey);
    return com.auth0.jwt.JWT.create()
        .withIssuer("https://api.botframework.com")
        .withIssuedAt(issuedAt)
        .withNotBefore(issuedAt)
        .withExpiresAt(new Date(issuedAt.getTime() + 300000L))
        .sign(algorithm);
}
 
Example 9
Source File: SecureServerComms.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
private void verifyToken(String token) throws JWTVerificationException, IOException{
	String file = path + pubKey;
	try {
		RSAPublicKey publicKey = readPublicKey(file); //Get the key instance
	    Algorithm algorithm = Algorithm.RSA256(publicKey, null);
	    JWTVerifier verifier = JWT.require(algorithm)
	        .withIssuer(agid)
	        .build(); //Reusable verifier instance
	    DecodedJWT jwt = verifier.verify(token);
	    logger.fine("Token expires at: " + jwt.getExpiresAt().toString());
	} catch (Exception e) {
    	e.printStackTrace();
	}
}
 
Example 10
Source File: Auth0VerifierTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Override
protected void validateToken(String token, RSAPublicKey publicKey, String issuer, int expGracePeriodSecs) throws Exception {
    Algorithm algorithm = Algorithm.RSA256(publicKey, null);
    Verification builder = JWT.require(algorithm)
        .withIssuer(issuer);
    if(expGracePeriodSecs > 0) {
        builder = builder.acceptLeeway(expGracePeriodSecs);
    }
    JWTVerifier verifier = builder.build();
    DecodedJWT jwt = verifier.verify(token);
}
 
Example 11
Source File: AlgorithmLinker.java    From JWT4B with GNU General Public License v3.0 5 votes vote down vote up
private static Algorithm getAlgorithm(String algo, String key, boolean IsKeyASignerKey)
		throws IllegalArgumentException, UnsupportedEncodingException {
	if (algo.equals(HS256.getAlgorithm())) {
		return Algorithm.HMAC256(key);
	}
	if (algo.equals(HS384.getAlgorithm())) {
		return Algorithm.HMAC384(key);
	}
	if (algo.equals(HS512.getAlgorithm())) {
		return Algorithm.HMAC512(key);
	}
	if (algo.equals(ES256.getAlgorithm())) {
		return Algorithm.ECDSA256((ECKey) getKeyInstance(key, "EC", IsKeyASignerKey));
	}
	if (algo.equals(ES384.getAlgorithm())) {
		return Algorithm.ECDSA384((ECKey) getKeyInstance(key, "EC", IsKeyASignerKey));
	}
	if (algo.equals(ES512.getAlgorithm())) {
		return Algorithm.ECDSA512((ECKey) getKeyInstance(key, "EC",IsKeyASignerKey));
	}
	if (algo.equals(RS256.getAlgorithm())) {
		return Algorithm.RSA256((RSAKey) getKeyInstance(key, "RSA", IsKeyASignerKey));
	}
	if (algo.equals(RS384.getAlgorithm())) {
		return Algorithm.RSA384((RSAKey) getKeyInstance(key, "RSA", IsKeyASignerKey));
	}
	if (algo.equals(RS512.getAlgorithm())) {
		return Algorithm.RSA512((RSAKey) getKeyInstance(key, "RSA", IsKeyASignerKey));
	}

	return Algorithm.none();
}
 
Example 12
Source File: AsymmetricSignatureVerifier.java    From auth0-java-mvc-common with MIT License 5 votes vote down vote up
private static JWTVerifier createJWTVerifier(final JwkProvider jwkProvider) {
    Algorithm alg = Algorithm.RSA256(new RSAKeyProvider() {
        @Override
        public RSAPublicKey getPublicKeyById(String keyId) {
            try {
                Jwk jwk = jwkProvider.get(keyId);
                return (RSAPublicKey) jwk.getPublicKey();
            } catch (JwkException ignored) {
                // JwkException handled by Algorithm verify implementation from java-jwt
            }
            return null;
        }

        @Override
        public RSAPrivateKey getPrivateKey() {
            //NO-OP
            return null;
        }

        @Override
        public String getPrivateKeyId() {
            //NO-OP
            return null;
        }
    });
    return JWT.require(alg)
            .ignoreIssuedAt()
            .build();
}
 
Example 13
Source File: GoogleJwtClient.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a signed JSON Web Token using a Google API Service Account
 * utilizes com.auth0.jwt.
 */
public static String generateJwt(final String saKeyfile, final String saEmail,
    final String audience, final int expiryLength)
    throws FileNotFoundException, IOException {

  Date now = new Date();
  Date expTime = new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(expiryLength));

  // Build the JWT payload
  JWTCreator.Builder token = JWT.create()
      .withIssuedAt(now)
      // Expires after 'expiraryLength' seconds
      .withExpiresAt(expTime)
      // Must match 'issuer' in the security configuration in your
      // swagger spec (e.g. service account email)
      .withIssuer(saEmail)
      // Must be either your Endpoints service name, or match the value
      // specified as the 'x-google-audience' in the OpenAPI document
      .withAudience(audience)
      // Subject and email should match the service account's email
      .withSubject(saEmail)
      .withClaim("email", saEmail);

  // Sign the JWT with a service account
  FileInputStream stream = new FileInputStream(saKeyfile);
  ServiceAccountCredentials cred = ServiceAccountCredentials.fromStream(stream);
  RSAPrivateKey key = (RSAPrivateKey) cred.getPrivateKey();
  Algorithm algorithm = Algorithm.RSA256(null, key);
  return token.sign(algorithm);
}
 
Example 14
Source File: ConcurrentVerifyTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldPassRSA256Verification() throws Exception {
    String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.dxXF3MdsyW-AuvwJpaQtrZ33fAde9xWxpLIg9cO2tMLH2GSRNuLAe61KsJusZhqZB9Iy7DvflcmRz-9OZndm6cj_ThGeJH2LLc90K83UEvvRPo8l85RrQb8PcanxCgIs2RcZOLygERizB3pr5icGkzR7R2y6zgNCjKJ5_NJ6EiZsGN6_nc2PRK_DbyY-Wn0QDxIxKoA5YgQJ9qafe7IN980pXvQv2Z62c3XR8dYuaXBqhthBj-AbaFHEpZapN-V-TmuLNzR2MCB6Xr7BYMuCaqWf_XU8og4XNe8f_8w9Wv5vvgqMM1KhqVpG5VdMJv4o_L4NoCROHhtUQSLRh2M9cA";
    Algorithm algorithm = Algorithm.RSA256((RSAKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA"));
    JWTVerifier verifier = JWTVerifier.init(algorithm).withIssuer("auth0").build();

    concurrentVerify(verifier, token);
}
 
Example 15
Source File: SecureServerComms.java    From vicinity-gateway-api with GNU General Public License v3.0 4 votes vote down vote up
private String generateToken() {
	String token = "";
	String file = path + privKey;
	try {
		
		RSAPrivateKey privateKey = readPrivateKey(file);
	    Algorithm algorithm = Algorithm.RSA256(null, privateKey);
	    
		// Current time in milliseconds converted to date
		long nowMillis = System.currentTimeMillis();
	    Date now = new Date(nowMillis);
	    
	    // Set expiration date
	    long expMillis = nowMillis + ttl;
	    Date expires = new Date(expMillis);
	    
	    // Set headers
	    Map<String, Object> headerClaims = new HashMap();
	    headerClaims.put("alg", "RS256");
	    headerClaims.put("typ", "JWT");
	    
	    token = JWT.create()
	    	.withHeader(headerClaims)
	        .withIssuer(agid)
	        .withAudience("NM")
	        .withExpiresAt(expires)
	        .withIssuedAt(now)
	        .sign(algorithm);
	    
	    storeToken(token);
	    
	    // Store token and expiration in memory
	    platform_token = token;
	    platform_token_expiration = expMillis;
	    		   		    	    
    } catch (JWTCreationException jwte){
        //Invalid Signing configuration / Couldn't convert Claims.
    	logger.warning("Token could not be generated...");
    	jwte.printStackTrace();
    } catch (IOException ioe) {
    	logger.warning("Token could not be stored...");
    	ioe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
	return token;
}