Java Code Examples for com.nimbusds.jose.JWSAlgorithm#RS256
The following examples show how to use
com.nimbusds.jose.JWSAlgorithm#RS256 .
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: BootstrapTests.java From authmore-framework with Apache License 2.0 | 7 votes |
@Test public void testJSONWebTokenManager() throws ParseException, JOSEException, BadJOSEException { JSONWebTokenManager tokens = new JSONWebTokenManager(clients, keyPair); ClientDetails client = clients.findAll().get(0); String userId = "user_1"; TokenResponse tokenResponse = tokens.create(client, userId, Collections.emptySet()); String accessToken; assertNotNull(tokenResponse); assertNotNull(accessToken = tokenResponse.getAccess_token()); ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); JWKSource<SecurityContext> keySource = new ImmutableJWKSet<>(jwkSet); JWSAlgorithm expectedJWSAlg = JWSAlgorithm.RS256; JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(expectedJWSAlg, keySource); jwtProcessor.setJWSKeySelector(keySelector); JWTClaimsSet claimsSet = jwtProcessor.process(accessToken, null); assertEquals(userId, claimsSet.getClaim(OAuthProperties.TOKEN_USER_ID)); }
Example 2
Source File: KnoxServiceTest.java From nifi with Apache License 2.0 | 6 votes |
@Test(expected = InvalidAuthenticationException.class) public void testInvalidAudience() throws Exception { final String subject = "user-1"; final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS)); final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); final KeyPair pair = keyGen.generateKeyPair(); final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate(); final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic(); final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, "incorrect-audience", expiration); final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey, null, null); final KnoxConfiguration configuration = getConfiguration(publicKey); final KnoxService service = new KnoxService(configuration); Assert.assertEquals(subject, service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize())); }
Example 3
Source File: KnoxServiceTest.java From nifi with Apache License 2.0 | 6 votes |
@Test public void testRequiredAudience() throws Exception { final String subject = "user-1"; final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS)); final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); final KeyPair pair = keyGen.generateKeyPair(); final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate(); final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic(); final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, AUDIENCE, expiration); final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey, null, null); final KnoxConfiguration configuration = getConfiguration(publicKey); when(configuration.getAudiences()).thenReturn(null); final KnoxService service = new KnoxService(configuration); Assert.assertEquals(subject, service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize())); }
Example 4
Source File: JwkKeyPairManager.java From OAuth-2.0-Cookbook with MIT License | 6 votes |
public String getSignedContent(String content) { Payload contentPayload = new Payload(content); try { RSASSASigner rsa = new RSASSASigner((RSAPrivateKey) clientJwk); JWSAlgorithm alg = JWSAlgorithm.RS256; JWSHeader header = new JWSHeader.Builder(alg) .keyID(clientJwk.getKeyID()) .build(); JWSObject jws = new JWSObject(header, contentPayload); jws.sign(rsa); return jws.serialize(); } catch (Exception e) { throw new RuntimeException(e); } }
Example 5
Source File: EncryptionUtility.java From amex-api-java-client-core with Apache License 2.0 | 6 votes |
public String sign(String algorithm, String kid, String keyStr, String dataToSign) { try { Key key = getKey(algorithm, keyStr); JWSHeader.Builder jwsBuilder = new JWSHeader.Builder("HS256".equals(algorithm) ? JWSAlgorithm.HS256 : JWSAlgorithm.RS256); jwsBuilder.keyID(kid); JWSHeader signingHeader = jwsBuilder.build(); JWSSigner signer = "HS256".equals(algorithm) ? new MACSigner(key.getEncoded()) : new RSASSASigner((RSAPrivateKey) key); JWSObject jwsObject = new JWSObject(signingHeader, new Payload(dataToSign)); jwsObject.sign(signer); checkObject(jwsObject); String parts[] = jwsObject.serialize().split("\\."); return "{\"protected\":\"" + parts[0] + "\", \"payload\":\"" + parts[1] + "\", \"signature\":\"" + parts[2] + "\"}"; } catch (Exception e) { throw new CryptoException("Exception signing data: " + e.getMessage(), e); } }
Example 6
Source File: KnoxServiceTest.java From nifi with Apache License 2.0 | 6 votes |
@Test(expected = InvalidAuthenticationException.class) public void testExpiredJwt() throws Exception { final String subject = "user-1"; // token expires in 1 sec final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(1, TimeUnit.SECONDS)); final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); final KeyPair pair = keyGen.generateKeyPair(); final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate(); final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic(); // wait 2 sec Thread.sleep(TimeUnit.MILLISECONDS.convert(2, TimeUnit.SECONDS)); final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, AUDIENCE, expiration); final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey, null, null); final KnoxConfiguration configuration = getConfiguration(publicKey); final KnoxService service = new KnoxService(configuration); service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize()); }
Example 7
Source File: TokenUtil.java From peer-os with Apache License 2.0 | 6 votes |
public static String createTokenRSA( PrivateKey privateKey, String claimJson ) { try { JWSSigner signer = new RSASSASigner( ( RSAPrivateKey ) privateKey ); Payload pl = new Payload( claimJson ); JWSObject jwsObject = new JWSObject( new JWSHeader( JWSAlgorithm.RS256 ), pl ); jwsObject.sign( signer ); return jwsObject.serialize(); } catch ( Exception e ) { LOG.error( "Error creating RSA token", e.getMessage() ); return ""; } }
Example 8
Source File: TokenUtil.java From peer-os with Apache License 2.0 | 6 votes |
public static boolean verifyTokenRSA( PublicKey pKey, String token ) { try { Payload pl = new Payload( token ); JWSObject jwsObject = new JWSObject( new JWSHeader( JWSAlgorithm.RS256 ), pl ); JWSVerifier verifier = new RSASSAVerifier( ( RSAPublicKey ) pKey ); return jwsObject.verify( verifier ); } catch ( JOSEException e ) { LOG.warn( "Error verifying RSA token", e.getMessage() ); return false; } }
Example 9
Source File: KnoxServiceTest.java From nifi with Apache License 2.0 | 6 votes |
@Test(expected = InvalidAuthenticationException.class) public void testBadSignedJwt() throws Exception { final String subject = "user-1"; final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS)); final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); final KeyPair pair1 = keyGen.generateKeyPair(); final RSAPrivateKey privateKey1 = (RSAPrivateKey) pair1.getPrivate(); final KeyPair pair2 = keyGen.generateKeyPair(); final RSAPublicKey publicKey2 = (RSAPublicKey) pair2.getPublic(); // sign the jwt with pair 1 final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, AUDIENCE, expiration); final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey1, null, null); // attempt to verify it with pair 2 final KnoxConfiguration configuration = getConfiguration(publicKey2); final KnoxService service = new KnoxService(configuration); service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize()); }
Example 10
Source File: JWTAccessTokenBuilder.java From msf4j with Apache License 2.0 | 6 votes |
/** * This method map signature algorithm define in identity.xml to nimbus * signature algorithm * format, Strings are defined inline hence there are not being used any * where * * @param signatureAlgorithm * @return * @throws IdentityOAuth2Exception */ protected JWSAlgorithm mapSignatureAlgorithm(String signatureAlgorithm) throws IdentityOAuth2Exception { if (NONE.equals(signatureAlgorithm)) { return new JWSAlgorithm(JWSAlgorithm.NONE.getName()); } else if (SHA256_WITH_RSA.equals(signatureAlgorithm)) { return JWSAlgorithm.RS256; } else if (SHA384_WITH_RSA.equals(signatureAlgorithm)) { return JWSAlgorithm.RS384; } else if (SHA512_WITH_RSA.equals(signatureAlgorithm)) { return JWSAlgorithm.RS512; } else if (SHA256_WITH_HMAC.equals(signatureAlgorithm)) { return JWSAlgorithm.HS256; } else if (SHA384_WITH_HMAC.equals(signatureAlgorithm)) { return JWSAlgorithm.HS384; } else if (SHA512_WITH_HMAC.equals(signatureAlgorithm)) { return JWSAlgorithm.HS512; } else if (SHA256_WITH_EC.equals(signatureAlgorithm)) { return JWSAlgorithm.ES256; } else if (SHA384_WITH_EC.equals(signatureAlgorithm)) { return JWSAlgorithm.ES384; } else if (SHA512_WITH_EC.equals(signatureAlgorithm)) { return JWSAlgorithm.ES512; } throw new IdentityOAuth2Exception("Unsupported Signature Algorithm in identity.xml"); }
Example 11
Source File: DefaultIDTokenBuilder.java From carbon-identity with Apache License 2.0 | 6 votes |
/** * This method map signature algorithm define in identity.xml to nimbus * signature algorithm * format, Strings are defined inline hence there are not being used any * where * * @param signatureAlgorithm * @return * @throws IdentityOAuth2Exception */ protected JWSAlgorithm mapSignatureAlgorithm(String signatureAlgorithm) throws IdentityOAuth2Exception { if (NONE.equals(signatureAlgorithm)) { return new JWSAlgorithm(JWSAlgorithm.NONE.getName()); } else if (SHA256_WITH_RSA.equals(signatureAlgorithm)) { return JWSAlgorithm.RS256; } else if (SHA384_WITH_RSA.equals(signatureAlgorithm)) { return JWSAlgorithm.RS384; } else if (SHA512_WITH_RSA.equals(signatureAlgorithm)) { return JWSAlgorithm.RS512; } else if (SHA256_WITH_HMAC.equals(signatureAlgorithm)) { return JWSAlgorithm.HS256; } else if (SHA384_WITH_HMAC.equals(signatureAlgorithm)) { return JWSAlgorithm.HS384; } else if (SHA512_WITH_HMAC.equals(signatureAlgorithm)) { return JWSAlgorithm.HS512; } else if (SHA256_WITH_EC.equals(signatureAlgorithm)) { return JWSAlgorithm.ES256; } else if (SHA384_WITH_EC.equals(signatureAlgorithm)) { return JWSAlgorithm.ES384; } else if (SHA512_WITH_EC.equals(signatureAlgorithm)) { return JWSAlgorithm.ES512; } throw new IdentityOAuth2Exception("Unsupported Signature Algorithm in identity.xml"); }
Example 12
Source File: ClientCredentialsGrantHandler.java From attic-stratos with Apache License 2.0 | 6 votes |
protected JWSAlgorithm mapSignatureAlgorithm(String signatureAlgorithm) throws IdentityOAuth2Exception { if ("SHA256withRSA".equals(signatureAlgorithm)) { return JWSAlgorithm.RS256; } else if ("SHA384withRSA".equals(signatureAlgorithm)) { return JWSAlgorithm.RS384; } else if ("SHA512withRSA".equals(signatureAlgorithm)) { return JWSAlgorithm.RS512; } else if ("SHA256withHMAC".equals(signatureAlgorithm)) { return JWSAlgorithm.HS256; } else if ("SHA384withHMAC".equals(signatureAlgorithm)) { return JWSAlgorithm.HS384; } else if ("SHA512withHMAC".equals(signatureAlgorithm)) { return JWSAlgorithm.HS512; } else if ("SHA256withEC".equals(signatureAlgorithm)) { return JWSAlgorithm.ES256; } else if ("SHA384withEC".equals(signatureAlgorithm)) { return JWSAlgorithm.ES384; } else if ("SHA512withEC".equals(signatureAlgorithm)) { return JWSAlgorithm.ES512; } log.error("Unsupported Signature Algorithm in identity.xml"); throw new IdentityOAuth2Exception("Unsupported Signature Algorithm in identity.xml"); }
Example 13
Source File: JWTGenerator.java From msf4j with Apache License 2.0 | 5 votes |
protected String generateJWT(User user) throws Exception { RSAPrivateKey privateKey = getPrivateKey(keyStore, keyStorePassword, alias); // Create RSA-signer with the private key JWSSigner signer = new RSASSASigner(privateKey); // Prepare JWT with claims set JWTClaimsSet claimsSet = new JWTClaimsSet(); claimsSet.setSubject(user.getName()); claimsSet.setClaim("email", user.getEmail()); claimsSet.setClaim("roles", user.getRoles()); claimsSet.setIssuer("wso2.org/products/msf4j"); claimsSet.setExpirationTime(new Date(new Date().getTime() + 60 * 60 * 1000)); //60 min SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet); // Compute the RSA signature signedJWT.sign(signer); // To serialize to compact form, produces something like // eyJhbGciOiJSUzI1NiJ9.SW4gUlNBIHdlIHRydXN0IQ.IRMQENi4nJyp4er2L // mZq3ivwoAjqa1uUkSBKFIX7ATndFF5ivnt-m8uApHO4kfIFOrW7w2Ezmlg3Qd // maXlS9DhN0nUk_hGI3amEjkKd0BWYCB8vfUbUv0XGjQip78AI4z1PrFRNidm7 // -jPDm5Iq0SZnjKjCNS5Q15fokXZc8u0A return signedJWT.serialize(); }
Example 14
Source File: KnoxServiceTest.java From nifi with Apache License 2.0 | 5 votes |
@Test public void testSignedJwt() throws Exception { final String subject = "user-1"; final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS)); final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); final KeyPair pair = keyGen.generateKeyPair(); final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate(); final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic(); final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, AUDIENCE, expiration); final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey, null, null); final KnoxConfiguration configuration = getConfiguration(publicKey); final KnoxService service = new KnoxService(configuration); Assert.assertEquals(subject, service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize())); }
Example 15
Source File: JWTTokenGenerator.java From carbon-identity with Apache License 2.0 | 5 votes |
/** * This method map signature algorithm define in identity.xml to nimbus * signature algorithm * format, Strings are defined inline hence there are not being used any * where * * @param signatureAlgorithm * @return * @throws IdentityOAuth2Exception */ protected JWSAlgorithm mapSignatureAlgorithm(String signatureAlgorithm) throws IdentityOAuth2Exception { if ("SHA256withRSA".equals(signatureAlgorithm)) { return JWSAlgorithm.RS256; } else if ("SHA384withRSA".equals(signatureAlgorithm)) { return JWSAlgorithm.RS384; } else if ("SHA512withRSA".equals(signatureAlgorithm)) { return JWSAlgorithm.RS512; } else if ("SHA256withHMAC".equals(signatureAlgorithm)) { return JWSAlgorithm.HS256; } else if ("SHA384withHMAC".equals(signatureAlgorithm)) { return JWSAlgorithm.HS384; } else if ("SHA512withHMAC".equals(signatureAlgorithm)) { return JWSAlgorithm.HS512; } else if ("SHA256withEC".equals(signatureAlgorithm)) { return JWSAlgorithm.ES256; } else if ("SHA384withEC".equals(signatureAlgorithm)) { return JWSAlgorithm.ES384; } else if ("SHA512withEC".equals(signatureAlgorithm)) { return JWSAlgorithm.ES512; } else if(NONE.equals(signatureAlgorithm)){ return new JWSAlgorithm(JWSAlgorithm.NONE.getName()); } log.error("Unsupported Signature Algorithm in identity.xml"); throw new IdentityOAuth2Exception("Unsupported Signature Algorithm in identity.xml"); }
Example 16
Source File: SessionUtilKeyPair.java From snowflake-jdbc with Apache License 2.0 | 5 votes |
public String issueJwtToken() throws SFException { JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder(); String sub = String.format(SUBJECT_FMT, this.accountName, this.userName); String iss = String.format(ISSUER_FMT, this.accountName, this.userName, this.calculatePublicKeyFingerprint(this.publicKey)); // iat is now Date iat = new Date(System.currentTimeMillis()); // expiration is 60 seconds later Date exp = new Date(iat.getTime() + 60L * 1000); JWTClaimsSet claimsSet = builder.issuer(iss) .subject(sub) .issueTime(iat) .expirationTime(exp) .build(); SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet); JWSSigner signer = new RSASSASigner(this.privateKey); try { signedJWT.sign(signer); } catch (JOSEException e) { throw new SFException(e, ErrorCode.FAILED_TO_GENERATE_JWT); } return signedJWT.serialize(); }
Example 17
Source File: JWTUtils.java From java-11-examples with Apache License 2.0 | 5 votes |
public static JWToken issue(String subject, String keyId, PrivateKey privateKey, Long expires) throws JOSEException { JSONObject payload = new JSONObject(); JWSHeader header = new JWSHeader(JWSAlgorithm.RS256, JOSEObjectType.JWT, null, null, null, null, null, null, null, null, keyId, null, null); payload.put("sub", subject); payload.put("exp", expires); JWSObject jwsObject = new JWSObject(header, new Payload(payload)); jwsObject.sign(new RSASSASigner(privateKey)); return new JWToken(jwsObject.serialize()); }
Example 18
Source File: SecurityManager.java From snowflake-ingest-java with Apache License 2.0 | 4 votes |
/** * regenerateToken - Regenerates our Token given our current user, * account and keypair */ private void regenerateToken() { //create our JWT claim builder object JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder(); //set the subject to the fully qualified username String subject = String.format("%s.%s", account, user); LOGGER.info("Creating Token with subject {}", subject); //set the issuer String publicKeyFPInJwt = calculatePublicKeyFp(keyPair); String issuer = String.format("%s.%s.%s", account, user, publicKeyFPInJwt); LOGGER.info("Creating Token with issuer {}", issuer); // iat set to now Date iat = new Date(System.currentTimeMillis()); // expiration in 59 minutes Date exp = new Date(iat.getTime() + 59 * 60 * 1000); // build claim set JWTClaimsSet claimsSet = builder.issuer(issuer) .subject(subject) .issueTime(iat) .expirationTime(exp) .build(); SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet); JWSSigner signer = new RSASSASigner(this.keyPair.getPrivate()); String newToken; try { signedJWT.sign(signer); newToken = signedJWT.serialize(); } catch (JOSEException e) { regenFailed.set(true); LOGGER.error("Failed to regenerate token! Exception is as follows : {}", e.getMessage()); throw new SecurityException(); } //atomically update the string LOGGER.info("Created new JWT"); token.set(newToken); }
Example 19
Source File: TokenUtils.java From Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile with MIT License | 4 votes |
/** * Utility method to generate a JWT string from a JSON resource file that is signed by the pk * test resource key, 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 timeClaims - used to return the exp, iat, auth_time claims * @return the JWT string * @throws Exception on parse failure */ public static String generateTokenString(PrivateKey pk, String kid, String jsonResName, Map<String, Long> timeClaims) throws Exception { InputStream contentIS = TokenUtils.class.getResourceAsStream(jsonResName); if (contentIS == null) { throw new IllegalStateException("Failed to find resource: " + 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 = parser.parse(content, JSONObject.class); long currentTimeInSecs = currentTimeInSecs(); long exp = currentTimeInSecs + DEFAULT_DURATION; // If exp was passed in, use it if (timeClaims.containsKey(Claims.exp.name())) { exp = timeClaims.get(Claims.exp.name()); } System.out.printf("Setting exp: %d / %s\n", exp, new Date(1000*exp)); long iat = currentTimeInSecs; long authTime = currentTimeInSecs; jwtContent.put(Claims.exp.name(), exp); jwtContent.put(Claims.iat.name(), iat); jwtContent.put(Claims.auth_time.name(), authTime); // Return the token time values if requested if (timeClaims != null) { timeClaims.put(Claims.iat.name(), iat); timeClaims.put(Claims.auth_time.name(), authTime); timeClaims.put(Claims.exp.name(), exp); } // Create RSA-signer with the private key JWSSigner signer = new RSASSASigner(pk); JWTClaimsSet claimsSet = JWTClaimsSet.parse(jwtContent); for (String claim : claimsSet.getClaims().keySet()) { Object claimValue = claimsSet.getClaim(claim); System.out.printf("\tAdded claim: %s, value: %s\n", claim, claimValue); } JWSAlgorithm alg = JWSAlgorithm.RS256; JWSHeader jwtHeader = new JWSHeader.Builder(alg) .keyID(kid) .type(JOSEObjectType.JWT) .build(); SignedJWT signedJWT = new SignedJWT(jwtHeader, claimsSet); signedJWT.sign(signer); return signedJWT.serialize(); }