uriBuilder.addParameter("request", jwt.serialize());
out.write(signed.serialize());
form.add("client_assertion", jwt.serialize()); } else {
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(); }
@Override public String toString() { return jwt.serialize(); }
public String toString() { return jwt.serialize(); }
private void succesHandler(HttpServletResponse response, User user, final SignedJWT token) { if (user != null && token != null) { Map<String, Object> result = new HashMap<>(); try { HashMap<String, Object> jwt = new HashMap<>(); jwt.put("access_token", token.serialize()); jwt.put("refresh", token.getJWTClaimsSet().getLongClaim("refresh")); jwt.put("expires", token.getJWTClaimsSet().getExpirationTime().getTime()); result.put("jwt", jwt); result.put("user", user); } catch (ParseException ex) { logger.info("Unable to parse JWT.", ex); RestUtils.returnStatusResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad token."); } RestUtils.returnObjectResponse(response, result); } else { RestUtils.returnStatusResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Null token."); } }
// Generate random 256-bit (32-byte) shared secret SecureRandom random = new SecureRandom(); byte[] sharedSecret = new byte[32]; random.nextBytes(sharedSecret); // Create HMAC signer JWSSigner signer = new MACSigner(sharedSecret); // Prepare JWT with claims set JWTClaimsSet claimsSet = new JWTClaimsSet(); claimsSet.setSubject("alice"); claimsSet.setIssuer("https://c2id.com"); claimsSet.setExpirationTime(new Date(new Date().getTime() + 60 * 1000)); SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet); // Apply the HMAC protection signedJWT.sign(signer); // Serialize to compact form, produces something like // eyJhbGciOiJIUzI1NiJ9.SGVsbG8sIHdvcmxkIQ.onO9Ihudz3WkiauDO2Uhyuz0Y18UASXlSc1eS0NkWyA String s = signedJWT.serialize();
private void succesHandler(HttpServletResponse response, User user, final SignedJWT token) { if (user != null && token != null) { Map<String, Object> result = new HashMap<>(); try { HashMap<String, Object> jwt = new HashMap<>(); jwt.put("access_token", token.serialize()); jwt.put("refresh", token.getJWTClaimsSet().getLongClaim("refresh")); jwt.put("expires", token.getJWTClaimsSet().getExpirationTime().getTime()); result.put("jwt", jwt); result.put("user", user); } catch (ParseException ex) { logger.info("Unable to parse JWT.", ex); RestUtils.returnStatusResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad token."); } RestUtils.returnObjectResponse(response, result); } else { RestUtils.returnStatusResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Null token."); } }
/** * {@inheritDoc} */ @Override public String rsaSignAndSerialize(RSAPrivateKey rsaPrivateKey, JWTClaimsSet claimsSet) throws APIManagementException { if (rsaPrivateKey == null) { throw new IllegalArgumentException("The private key must not be null"); } if (claimsSet == null) { throw new IllegalArgumentException("The JWTClaimsSet must not be null"); } JWSSigner signer = new RSASSASigner(rsaPrivateKey); SignedJWT jwt = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet); try { jwt.sign(signer); } catch (JOSEException e) { throw new APIManagementException("Error signing JWT ", e); } return jwt.serialize(); }
/** * {@inheritDoc} */ @Override public String rsaSignAndSerialize(RSAPrivateKey rsaPrivateKey, JWTClaimsSet claimsSet) throws APIManagementException { if (rsaPrivateKey == null) { throw new IllegalArgumentException("The private key must not be null"); } if (claimsSet == null) { throw new IllegalArgumentException("The JWTClaimsSet must not be null"); } JWSSigner signer = new RSASSASigner(rsaPrivateKey); SignedJWT jwt = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet); try { jwt.sign(signer); } catch (JOSEException e) { throw new APIManagementException("Error signing JWT ", e); } return jwt.serialize(); }
@Test public void testExpiredJWT() throws Exception { try { handler.setPublicKey(publicKey); Properties props = getProperties(); handler.init(props); SignedJWT jwt = getJWT("bob", new Date(new Date().getTime() - 1000), privateKey); Cookie cookie = new Cookie("hadoop-jwt", jwt.serialize()); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getCookies()).thenReturn(new Cookie[] { cookie }); Mockito.when(request.getRequestURL()).thenReturn( new StringBuffer(SERVICE_URL)); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(response.encodeRedirectURL(SERVICE_URL)).thenReturn( SERVICE_URL); AuthenticationToken token = handler.alternateAuthenticate(request, response); Mockito.verify(response).sendRedirect(REDIRECT_LOCATION); } catch (ServletException se) { fail("alternateAuthentication should NOT have thrown a ServletException"); } catch (AuthenticationException ae) { fail("alternateAuthentication should NOT have thrown a AuthenticationException"); } }
@Test public void testExpiredJWT() throws Exception { try { handler.setPublicKey(publicKey); Properties props = getProperties(); handler.init(props); SignedJWT jwt = getJWT("bob", new Date(new Date().getTime() - 1000), privateKey); Cookie cookie = new Cookie("hadoop-jwt", jwt.serialize()); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getCookies()).thenReturn(new Cookie[] { cookie }); Mockito.when(request.getRequestURL()).thenReturn( new StringBuffer(SERVICE_URL)); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(response.encodeRedirectURL(SERVICE_URL)).thenReturn( SERVICE_URL); AuthenticationToken token = handler.authenticate(request, response); Mockito.verify(response).sendRedirect(REDIRECT_LOCATION); } catch (ServletException se) { fail("alternateAuthentication should NOT have thrown a ServletException"); } catch (AuthenticationException ae) { fail("alternateAuthentication should NOT have thrown a AuthenticationException"); } }
private static String signJWT(String uid, PrivateKey privateKey) { final JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build(); final JWTClaimsSet payload = new JWTClaimsSet.Builder().claim("uid", uid).build(); final SignedJWT signedJWT = new SignedJWT(header, payload); try { signedJWT.sign(new RSASSASigner(privateKey)); return signedJWT.serialize(); } catch (JOSEException e) { throw new RuntimeException(e); } }
private static String signJWT(String uid, PrivateKey privateKey) { final JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build(); final JWTClaimsSet payload = new JWTClaimsSet.Builder().claim("uid", uid).build(); final SignedJWT signedJWT = new SignedJWT(header, payload); try { signedJWT.sign(new RSASSASigner(privateKey)); return signedJWT.serialize(); } catch (JOSEException e) { throw new RuntimeException(e); } }
@Test public void testNoPublicKeyJWT() throws Exception { try { Properties props = getProperties(); handler.init(props); SignedJWT jwt = getJWT("bob", new Date(new Date().getTime() + 5000), privateKey); Cookie cookie = new Cookie("hadoop-jwt", jwt.serialize()); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getCookies()).thenReturn(new Cookie[] { cookie }); Mockito.when(request.getRequestURL()).thenReturn( new StringBuffer(SERVICE_URL)); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(response.encodeRedirectURL(SERVICE_URL)).thenReturn( SERVICE_URL); AuthenticationToken token = handler.alternateAuthenticate(request, response); fail("alternateAuthentication should have thrown a ServletException"); } catch (ServletException se) { assertTrue(se.getMessage().contains( "Public key for signature validation must be provisioned")); } catch (AuthenticationException ae) { fail("alternateAuthentication should NOT have thrown a AuthenticationException"); } }
@Test public void testValidJWT() throws Exception { try { handler.setPublicKey(publicKey); Properties props = getProperties(); handler.init(props); SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 5000), privateKey); Cookie cookie = new Cookie("hadoop-jwt", jwt.serialize()); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getCookies()).thenReturn(new Cookie[] { cookie }); Mockito.when(request.getRequestURL()).thenReturn( new StringBuffer(SERVICE_URL)); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(response.encodeRedirectURL(SERVICE_URL)).thenReturn( SERVICE_URL); AuthenticationToken token = handler.alternateAuthenticate(request, response); Assert.assertNotNull("Token should not be null.", token); Assert.assertEquals("alice", token.getUserName()); } catch (ServletException se) { fail("alternateAuthentication should NOT have thrown a ServletException."); } catch (AuthenticationException ae) { fail("alternateAuthentication should NOT have thrown an AuthenticationException"); } }
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(); }
@Test public void testNoExpirationJWT() throws Exception { try { handler.setPublicKey(publicKey); Properties props = getProperties(); handler.init(props); SignedJWT jwt = getJWT("bob", null, privateKey); Cookie cookie = new Cookie("hadoop-jwt", jwt.serialize()); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getCookies()).thenReturn(new Cookie[] { cookie }); Mockito.when(request.getRequestURL()).thenReturn( new StringBuffer(SERVICE_URL)); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(response.encodeRedirectURL(SERVICE_URL)).thenReturn( SERVICE_URL); AuthenticationToken token = handler.alternateAuthenticate(request, response); Assert.assertNotNull("Token should not be null.", token); Assert.assertEquals("bob", token.getUserName()); } catch (ServletException se) { fail("alternateAuthentication should NOT have thrown a ServletException"); } catch (AuthenticationException ae) { fail("alternateAuthentication should NOT have thrown a AuthenticationException"); } }
@Test public void testNoExpirationJWT() throws Exception { try { handler.setPublicKey(publicKey); Properties props = getProperties(); handler.init(props); SignedJWT jwt = getJWT("bob", null, privateKey); Cookie cookie = new Cookie("hadoop-jwt", jwt.serialize()); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getCookies()).thenReturn(new Cookie[] { cookie }); Mockito.when(request.getRequestURL()).thenReturn( new StringBuffer(SERVICE_URL)); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(response.encodeRedirectURL(SERVICE_URL)).thenReturn( SERVICE_URL); AuthenticationToken token = handler.authenticate(request, response); Assert.assertNotNull("Token should not be null.", token); Assert.assertEquals("bob", token.getUserName()); } catch (ServletException se) { fail("alternateAuthentication should NOT have thrown a ServletException"); } catch (AuthenticationException ae) { fail("alternateAuthentication should NOT have thrown a AuthenticationException"); } }