Refine search
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;
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()); if (idClaims.getExpirationTime() == null) { throw new AuthenticationServiceException("Id Token does not have required expiration claim"); } else { Date now = new Date(System.currentTimeMillis() - (timeSkewAllowance * 1000)); if (now.after(idClaims.getExpirationTime())) { throw new AuthenticationServiceException("Id Token is expired: " + idClaims.getExpirationTime()); if (idClaims.getNotBeforeTime() != null) { Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000)); if (now.before(idClaims.getNotBeforeTime())){ throw new AuthenticationServiceException("Id Token not valid untill: " + idClaims.getNotBeforeTime()); if (idClaims.getIssueTime() == null) { throw new AuthenticationServiceException("Id Token does not have required issued-at claim"); } else { if (now.before(idClaims.getIssueTime())) { throw new AuthenticationServiceException("Id Token was issued in the future: " + idClaims.getIssueTime()); if (idClaims.getAudience() == null) { throw new AuthenticationServiceException("Id token audience is null"); } else if (!idClaims.getAudience().contains(clientConfig.getClientId())) { throw new AuthenticationServiceException("Audience does not match, expected " + clientConfig.getClientId() + " got " + idClaims.getAudience());
JWTClaimsSet claimSet = newClient.getSoftwareStatement().getJWTClaimsSet(); for (String claim : claimSet.getClaims().keySet()) { switch (claim) { case SOFTWARE_STATEMENT: throw new ValidationException("invalid_client_metadata", "Software statement can't include another software statement", HttpStatus.BAD_REQUEST); case CLAIMS_REDIRECT_URIS: newClient.setClaimsRedirectUris(Sets.newHashSet(claimSet.getStringListClaim(claim))); break; case CLIENT_SECRET_EXPIRES_AT: throw new ValidationException("invalid_client_metadata", "Software statement can't include a client registration access token", HttpStatus.BAD_REQUEST); case REQUEST_URIS: newClient.setRequestUris(Sets.newHashSet(claimSet.getStringListClaim(claim))); break; case POST_LOGOUT_REDIRECT_URIS: newClient.setPostLogoutRedirectUris(Sets.newHashSet(claimSet.getStringListClaim(claim))); break; case INITIATE_LOGIN_URI: newClient.setInitiateLoginUri(claimSet.getStringClaim(claim)); break; case DEFAULT_ACR_VALUES: newClient.setDefaultACRvalues(Sets.newHashSet(claimSet.getStringListClaim(claim))); break; case REQUIRE_AUTH_TIME: newClient.setRequireAuthTime(claimSet.getBooleanClaim(claim)); break; case DEFAULT_MAX_AGE: newClient.setDefaultMaxAge(claimSet.getIntegerClaim(claim)); break;
@Override public Collection<? extends GrantedAuthority> mapAuthorities(JWT idToken, UserInfo userInfo) { Set<GrantedAuthority> out = new HashSet<>(); try { JWTClaimsSet claims = idToken.getJWTClaimsSet(); SubjectIssuerGrantedAuthority authority = new SubjectIssuerGrantedAuthority(claims.getSubject(), claims.getIssuer()); out.add(authority); if (admins.contains(authority)) { out.add(ROLE_ADMIN); } // everybody's a user by default out.add(ROLE_USER); } catch (ParseException e) { logger.error("Unable to parse ID Token inside of authorities mapper (huh?)"); } return out; }
@Override public OAuth2Request createOAuth2Request(ClientDetails client, TokenRequest tokenRequest, JWT assertion) { try { JWTClaimsSet claims = assertion.getJWTClaimsSet(); Set<String> scope = OAuth2Utils.parseParameterList(claims.getStringClaim("scope")); Set<String> resources = Sets.newHashSet(claims.getAudience()); return new OAuth2Request(tokenRequest.getRequestParameters(), client.getClientId(), client.getAuthorities(), true, scope, resources, null, null, null); } catch (ParseException e) { return null; } }
idTokenClaims = idToken.getJWTClaimsSet(); String clientId = Iterables.getOnlyElement(idTokenClaims.getAudience()); String subject = idTokenClaims.getSubject();
private OAuth2AccessTokenEntity fetchValidRegistrationToken(OAuth2Authentication auth, ClientDetailsEntity client) { OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails(); OAuth2AccessTokenEntity token = tokenService.readAccessToken(details.getTokenValue()); if (config.getRegTokenLifeTime() != null) { try { // Re-issue the token if it has been issued before [currentTime - validity] Date validToDate = new Date(System.currentTimeMillis() - config.getRegTokenLifeTime() * 1000); if(token.getJwt().getJWTClaimsSet().getIssueTime().before(validToDate)) { logger.info("Rotating the registration access token for " + client.getClientId()); tokenService.revokeAccessToken(token); OAuth2AccessTokenEntity newToken = connectTokenService.createResourceAccessToken(client); tokenService.saveAccessToken(newToken); return newToken; } else { // it's not expired, keep going return token; } } catch (ParseException e) { logger.error("Couldn't parse a known-valid token?", e); return token; } } else { // tokens don't expire, just return it return token; } }
/** * 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); }
private boolean verifyExpiration(JWT jwtToken) throws IOException { try { Date expire = jwtToken.getJWTClaimsSet().getExpirationTime(); if (expire != null && new Date().after(expire)) { return false; } Date notBefore = jwtToken.getJWTClaimsSet().getNotBeforeTime(); if (notBefore != null && new Date().before(notBefore)) { return false; } } catch (ParseException e) { throw new IOException("Failed to get JWT claims set", e); } return true; }
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()); if (jwtClaims.getExpirationTime() == null) { throw new AuthenticationServiceException("Assertion Token does not have required expiration claim"); } 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()); if (jwtClaims.getIssueTime() != null) { Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000)); if (now.before(jwtClaims.getIssueTime())) { throw new AuthenticationServiceException("Assertion Token was issued in the future: " + jwtClaims.getIssueTime()); if (jwtClaims.getAudience() == null) { throw new AuthenticationServiceException("Assertion token audience is null"); } else if (!(jwtClaims.getAudience().contains(config.getIssuer()) || jwtClaims.getAudience().contains(config.getIssuer() + "token"))) { throw new AuthenticationServiceException("Audience does not match, expected " + config.getIssuer() + " or " + (config.getIssuer() + "token") + " got " + jwtClaims.getAudience());
.claim("azp", clientId) .issuer(configBean.getIssuer()) .issueTime(new Date()) .expirationTime(token.getExpiration()) .subject(authentication.getName()) jwtService.getDefaultSignerKeyId(), null, null); SignedJWT signed = new SignedJWT(header, claims); originalAuthRequest, claims.getIssueTime(), userInfo.getSub(), token);
@Override public void verify(final JWTClaimsSet claimsSet, final C context) throws BadJWTException { final Date now = new Date(); final Date exp = claimsSet.getExpirationTime(); if (exp != null) { if (! DateUtils.isAfter(exp, now, maxClockSkew)) { throw EXPIRED_JWT_EXCEPTION; } } final Date nbf = claimsSet.getNotBeforeTime(); if (nbf != null) { if (! DateUtils.isBefore(nbf, now, maxClockSkew)) { throw JWT_BEFORE_USE_EXCEPTION; } } } }
protected Payload createPayload(String aud, String subject, Long expirationMillis, Map<String, Object> claimMap) { JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder(); builder //.issueTime(new Date()) .expirationTime(new Date(System.currentTimeMillis() + expirationMillis)) .audience(aud) .subject(subject) .claim(LEMON_IAT, System.currentTimeMillis()); claimMap.forEach(builder::claim); JWTClaimsSet claims = builder.build(); return new Payload(claims.toJSONObject()); }
@Override public boolean verify(final JWSHeader header, final byte[] signingInput, final Base64URL signature) throws JOSEException { boolean value = super.verify(header, signingInput, signature); long time = System.currentTimeMillis(); return value && claimsSet.getNotBeforeTime().getTime() <= time && time < claimsSet.getExpirationTime().getTime(); } }
@Override public JWTClaimsSet parseToken(String token, String audience) { JWTClaimsSet claims = parseToken(token); LecUtils.ensureCredentials(audience != null && claims.getAudience().contains(audience), "com.naturalprogrammer.spring.wrong.audience"); long expirationTime = claims.getExpirationTime().getTime(); long currentTime = System.currentTimeMillis(); log.debug("Parsing JWT. Expiration time = " + expirationTime + ". Current time = " + currentTime); LecUtils.ensureCredentials(expirationTime >= currentTime, "com.naturalprogrammer.spring.expiredToken"); return claims; }
private boolean verifyJwt(String jwtToken, String expectedAudience) throws Exception { SignedJWT signedJwt = SignedJWT.parse(jwtToken); JWSHeader jwsHeader = signedJwt.getHeader(); 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)); Preconditions.checkNotNull(claims.getSubject()); Preconditions.checkNotNull(claims.getClaim("email"));
/** * Gets the specified claim (registered or custom) as * {@link java.lang.String}. * * @param name The name of the claim. Must not be {@code null}. * * @return The value of the claim, {@code null} if not specified. * * @throws ParseException If the claim value is not of the required * type. */ public String getStringClaim(final String name) throws ParseException { Object value = getClaim(name); if (value == null || value instanceof String) { return (String)value; } else { throw new ParseException("The \"" + name + "\" claim is not a String", 0); } }
/** * Create an unauthenticated token with the given subject and jwt * @param subject * @param jwt */ public JWTBearerAssertionAuthenticationToken(JWT jwt) { super(null); try { // save the subject of the JWT in case the credentials get erased later this.subject = jwt.getJWTClaimsSet().getSubject(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.jwt = jwt; setAuthenticated(false); }
/** * Gets the specified claim (registered or custom) as a * {@link java.net.URI}. * * @param name The name of the claim. Must not be {@code null}. * * @return The value of the claim, {@code null} if not specified. * * @throws ParseException If the claim couldn't be parsed to a URI. */ public URI getURIClaim(final String name) throws ParseException { String uriString = getStringClaim(name); if (uriString == null) { return null; } try { return new URI(uriString); } catch (URISyntaxException e) { throw new ParseException("The \"" + name + "\" claim is not a URI: " + e.getMessage(), 0); } }
@Override public IDTokenClaimsSet validate(final JWT idToken, final Nonce expectedNonce) throws BadJOSEException, JOSEException { try { if (originalIssuer.contains("%7Btenantid%7D")) { Object tid = idToken.getJWTClaimsSet().getClaim("tid"); if (tid == null) { throw new BadJWTException("ID token does not contain the 'tid' claim"); } base = new IDTokenValidator(new Issuer(originalIssuer.replace("%7Btenantid%7D", tid.toString())), base.getClientID(), base.getJWSKeySelector(), base.getJWEKeySelector()); base.setMaxClockSkew(getMaxClockSkew()); } } catch (ParseException e) { throw new BadJWTException(e.getMessage(), e); } return base.validate(idToken, expectedNonce); } }