Refine search
.audience(Lists.newArrayList(client.getClientId())) .issuer(configBean.getIssuer()) .issueTime(new Date()) .expirationTime(token.getExpiration()) JWSHeader header = new JWSHeader(signingAlg, null, null, null, null, null, null, null, null, null, jwtService.getDefaultSignerKeyId(), null, null); SignedJWT signed = new SignedJWT(header, claims);
@Override public void signJwt(SignedJWT jwt, JWSAlgorithm alg) { JWSSigner signer = null; for (JWSSigner s : signers.values()) { if (s.supportedJWSAlgorithms().contains(alg)) { signer = s; break; } } if (signer == null) { //If we can't find an algorithm that matches, we can't sign logger.error("No matching algirthm found for alg=" + alg); } try { jwt.sign(signer); } catch (JOSEException e) { logger.error("Failed to sign JWT, error was: ", e); } }
Date exp = new Date(System.currentTimeMillis() + (60 * 1000)); // auth good for 60 seconds claimsSet.expirationTime(exp); Date now = new Date(System.currentTimeMillis()); claimsSet.issueTime(now); claimsSet.notBeforeTime(now); JWSHeader header = new JWSHeader(alg, null, null, null, null, null, null, null, null, null, signer.getDefaultSignerKeyId(), null, null); SignedJWT jwt = new SignedJWT(header, claimsSet.build()); form.add("client_assertion", jwt.serialize()); } else { if (idClaims.getIssuer() == null) { throw new AuthenticationServiceException("Id Token Issuer is null"); } else if (!idClaims.getIssuer().equals(serverConfig.getIssuer())){ throw new AuthenticationServiceException("Issuers do not match, expected " + serverConfig.getIssuer() + " got " + idClaims.getIssuer()); } else { Date now = new Date(System.currentTimeMillis() - (timeSkewAllowance * 1000)); if (now.after(idClaims.getExpirationTime())) { throw new AuthenticationServiceException("Id Token is expired: " + idClaims.getExpirationTime());
/** * Validate the jwt signature. * * @param jwtToken knox jwt * @return whether this jwt signature is valid * @throws JOSEException if the jws object couldn't be verified */ private boolean validateSignature(final SignedJWT jwtToken) throws JOSEException { boolean valid = false; // ensure the token is signed if (JWSObject.State.SIGNED.equals(jwtToken.getState())) { // ensure the signature is present if (jwtToken.getSignature() != null) { // verify the token valid = jwtToken.verify(verifier); } } if (!valid) { logger.error("The Knox JWT has an invalid signature."); } return valid; }
/** * Extracts the authentication from the token and verify it. * * @param jwt signed jwt string * @return the user authentication * @throws ParseException if the payload of the jwt doesn't represent a valid json object and a jwt claims set * @throws JOSEException if the JWS object couldn't be verified */ public String getAuthenticationFromToken(final String jwt) throws ParseException, JOSEException { if (!configuration.isKnoxEnabled()) { throw new IllegalStateException("Apache Knox SSO is not enabled."); } // attempt to parse the signed jwt final SignedJWT signedJwt = SignedJWT.parse(jwt); // validate the token if (validateToken(signedJwt)) { final JWTClaimsSet claimsSet = signedJwt.getJWTClaimsSet(); if (claimsSet == null) { logger.info("Claims set is missing from Knox JWT."); throw new InvalidAuthenticationException("The Knox JWT token is not valid."); } // extract the user identity from the token return claimsSet.getSubject(); } else { throw new InvalidAuthenticationException("The Knox JWT token is not valid."); } }
@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"); } }
private JWT generateAuthenticationJwt() { // Create RSA-signer with the private key JWSSigner signer = new RSASSASigner(this.rsaPrivateKey); // Prepare JWT with claims set JWTClaimsSet claimsSet = new JWTClaimsSet(); claimsSet.setIssuer(issuer); claimsSet.setSubject(subject); claimsSet.setAudience(audience); claimsSet.setIssueTime(new Date()); claimsSet.setExpirationTime(new Date(new Date().getTime() + durationSeconds * 1000)); claimsSet.setJWTID(tokenReference); SignedJWT signedJWT = new SignedJWT(new com.nimbusds.jose.JWSHeader(JWSAlgorithm.RS256), claimsSet); try { signedJWT.sign(signer); } catch (JOSEException jose_ex) { throw new RuntimeException("Error signing JSON Web Token.", jose_ex); } return signedJWT; } }
protected SignedJWT getJWT(String sub, Date expires, RSAPrivateKey privateKey) throws Exception { JWTClaimsSet claimsSet = new JWTClaimsSet(); claimsSet.setSubject(sub); claimsSet.setIssueTime(new Date(new Date().getTime())); claimsSet.setIssuer("https://c2id.com"); claimsSet.setCustomClaim("scope", "openid"); claimsSet.setExpirationTime(expires); List<String> aud = new ArrayList<String>(); aud.add("bar"); claimsSet.setAudience("bar"); JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).build(); SignedJWT signedJWT = new SignedJWT(header, claimsSet); JWSSigner signer = new RSASSASigner(privateKey); signedJWT.sign(signer); return signedJWT; }
private boolean verifySignature(String jwt) { try { SignedJWT signedJWT = SignedJWT.parse(jwt); if (new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime())) { JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) getPublicKey(KEYSTORE, KEYSTORE_PASSWORD, ALIAS)); return signedJWT.verify(verifier); } else { log.info("Token has expired"); } } catch (ParseException | IOException | KeyStoreException | CertificateException | NoSuchAlgorithmException | UnrecoverableKeyException | JOSEException e) { log.error("Error occurred while JWT signature verification. JWT=" + jwt, e); } return false; }
JWSAlgorithm alg = jws.getHeader().getAlgorithm(); if (jwtClaims.getIssuer() == null) { throw new AuthenticationServiceException("Assertion Token Issuer is null"); } else if (!jwtClaims.getIssuer().equals(client.getClientId())){ throw new AuthenticationServiceException("Issuers do not match, expected " + client.getClientId() + " got " + jwtClaims.getIssuer()); } else { Date now = new Date(System.currentTimeMillis() - (timeSkewAllowance * 1000)); if (now.after(jwtClaims.getExpirationTime())) { throw new AuthenticationServiceException("Assertion Token is expired: " + jwtClaims.getExpirationTime()); if (jwtClaims.getNotBeforeTime() != null) { Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000)); if (now.before(jwtClaims.getNotBeforeTime())){ throw new AuthenticationServiceException("Assertion Token not valid untill: " + jwtClaims.getNotBeforeTime());
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(); }
protected SignedJWT getJWT(String sub, Date expires, RSAPrivateKey privateKey) throws Exception { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject(sub) .issueTime(new Date(new Date().getTime())) .issuer("https://c2id.com") .claim("scope", "openid") .audience("bar") .expirationTime(expires) .build(); List<String> aud = new ArrayList<String>(); aud.add("bar"); JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).build(); SignedJWT signedJWT = new SignedJWT(header, claimsSet); JWSSigner signer = new RSASSASigner(privateKey); signedJWT.sign(signer); return signedJWT; } }
boolean valid = false; final JWTClaimsSet claimsSet = jwtToken.getJWTClaimsSet(); if (claimsSet == null) { logger.error("Claims set is missing from Knox JWT."); final Date now = new Date(); final Date expiration = claimsSet.getExpirationTime(); if (expiration == null || now.before(expiration)) { valid = true;
/** * Validates a Knox token with expiration and begin times and verifies the token with a public Knox key. * @param jwtToken Knox token * @param userName User name associated with the token * @return Whether a token is valid or not * @throws ParseException JWT Token could not be parsed. */ protected boolean isValid(SignedJWT jwtToken, String userName) throws ParseException { // Verify the user name is present if (userName == null || userName.isEmpty()) { LOG.info("Could not find user name in SSO token"); return false; } Date now = new Date(); // Verify the token has not expired Date expirationTime = jwtToken.getJWTClaimsSet().getExpirationTime(); if (expirationTime != null && now.after(expirationTime)) { LOG.info("SSO token expired: {} ", userName); return false; } // Verify the token is not before time Date notBeforeTime = jwtToken.getJWTClaimsSet().getNotBeforeTime(); if (notBeforeTime != null && now.before(notBeforeTime)) { LOG.info("SSO token not yet valid: {} ", userName); return false; } return validateSignature(jwtToken); }
JWTClaimsSet claims = new JWTClaimsSet.Builder(JWTClaimsSet.parse(writer.toString())) .audience(Lists.newArrayList(client.getClientId())) .issuer(config.getIssuer()) .issueTime(new Date()) JWSHeader header = new JWSHeader(signingAlg, null, null, null, null, null, null, null, null, null, jwtService.getDefaultSignerKeyId(), null, null); SignedJWT signed = new SignedJWT(header, claims); out.write(signed.serialize());
.claim("azp", clientId) .issuer(configBean.getIssuer()) .issueTime(new Date()) .expirationTime(token.getExpiration()) .subject(authentication.getName()) JWSHeader header = new JWSHeader(signingAlg, null, null, null, null, null, null, null, null, null, jwtService.getDefaultSignerKeyId(), null, null); SignedJWT signed = new SignedJWT(header, claims); originalAuthRequest, claims.getIssueTime(), userInfo.getSub(), 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."); } }
private boolean verifyJwt(String jwtToken, String expectedAudience) throws Exception { SignedJWT signedJwt = SignedJWT.parse(jwtToken); JWSHeader jwsHeader = signedJwt.getHeader(); Preconditions.checkNotNull(jwsHeader.getAlgorithm()); Preconditions.checkNotNull(jwsHeader.getKeyID()); JWTClaimsSet claims = signedJwt.getJWTClaimsSet(); Preconditions.checkArgument(claims.getAudience().contains(expectedAudience)); Preconditions.checkArgument(claims.getIssuer().equals(IAP_ISSUER_URL)); Date currentTime = Date.from(Instant.now(clock)); Preconditions.checkArgument(claims.getIssueTime().before(currentTime)); Preconditions.checkArgument(claims.getExpirationTime().after(currentTime)); ECPublicKey publicKey = getKey(jwsHeader.getKeyID(), jwsHeader.getAlgorithm().getName()); return signedJwt.verify(jwsVerifier);