private ValidateTokenResponse convert(final ReadOnlyJWTClaimsSet claimsSet) { final ValidateTokenResponse validateTokenResponse = new ValidateTokenResponse(); validateTokenResponse.setActive(true); if (claimsSet.getAudience() != null) { validateTokenResponse.setAud(Join.join(" ", claimsSet.getAudience())); } validateTokenResponse.setExp(claimsSet.getExpirationTime().getTime()); validateTokenResponse.setIat(claimsSet.getIssueTime().getTime()); validateTokenResponse.setIss(claimsSet.getIssuer()); validateTokenResponse.setJti(claimsSet.getJWTID()); validateTokenResponse.setNbf(claimsSet.getNotBeforeTime().getTime()); try { if (claimsSet.getStringListClaim("scope") != null) { validateTokenResponse.setScope(Join.join(" ", claimsSet.getStringListClaim("scope"))); } } catch (final ParseException e) { // ignore } return validateTokenResponse; } }
if (claims == null || claims.getAllClaims().size() == 0) { return null; .getStringClaim(AuthenticationConstants.ID_TOKEN_OBJECT_ID))) { uniqueId = claims .getStringClaim(AuthenticationConstants.ID_TOKEN_OBJECT_ID); } else if (!StringHelper.isBlank(claims .getStringClaim(AuthenticationConstants.ID_TOKEN_SUBJECT))) { uniqueId = claims .getStringClaim(AuthenticationConstants.ID_TOKEN_SUBJECT); .getStringClaim(AuthenticationConstants.ID_TOKEN_UPN))) { displayableId = claims .getStringClaim(AuthenticationConstants.ID_TOKEN_UPN); } else if (!StringHelper.isBlank(claims .getStringClaim(AuthenticationConstants.ID_TOKEN_EMAIL))) { displayableId = claims .getStringClaim(AuthenticationConstants.ID_TOKEN_EMAIL); userInfo.dispayableId = displayableId; userInfo.familyName = claims .getStringClaim(AuthenticationConstants.ID_TOKEN_FAMILY_NAME); userInfo.givenName = claims .getStringClaim(AuthenticationConstants.ID_TOKEN_GIVEN_NAME); userInfo.identityProvider = claims .getStringClaim(AuthenticationConstants.ID_TOKEN_IDENTITY_PROVIDER); .getStringClaim(AuthenticationConstants.ID_TOKEN_PASSWORD_CHANGE_URL))) { userInfo.passwordChangeUrl = claims
public Principal createPrincipal() { final Set<String> roles = new HashSet<>(); final ReadOnlyJWTClaimsSet jwtClaimsSet = getJWTClaimsSet(); final String jwtId = jwtClaimsSet.getJWTID() == null ? "" : jwtClaimsSet.getJWTID(); if (roleClaims != null) { for (String roleClaim : roleClaims) { // TODO (JRG) if we cannot parse a list, we should just read a string final Object claim = jwtClaimsSet.getClaim(roleClaim); if (claim == null) { LOGGER.info(Oauth2Codes.UNABLE_TO_READ_CLAIM, format("Claim: %s is null, skipping. JWT ID: %s, Full JWT: %s", roleClaim, jwtId, token)); continue; } if (List.class.isInstance(claim)) { roles.addAll(List.class.cast(claim)); } if (String.class.isInstance(claim)) { roles.addAll(Arrays.asList(String.class.cast(claim).split(" *, *"))); } } } if (handler != null) { handler.info("bearer-profile", "Creating principal with roles " + roles); } return new TribestreamPrincipal(getUsername(), new ArrayList<>(roles)); }
final ReadOnlyJWTClaimsSet jwtClaimsSet = getJWTClaimsSet(); extractUsernameAndClientId(jwtClaimsSet); final String jwtId = jwtClaimsSet.getJWTID() == null ? "" : jwtClaimsSet.getJWTID(); final String tokenType; tokenType = jwtClaimsSet.getStringClaim("token-type"); } catch (final ParseException e) { throw new UnableToGetTokenTypeException(format("Invalid JWT, unable to get token-type claim. JWT ID: %s, Full JWT: %s", jwtId, token), profile.getName()); final long expirationTime = jwtClaimsSet.getExpirationTime().getTime(); if (currentTime > (expirationTime + expTolerance.getTime(MILLISECONDS))) { throw new TokenExpiredException("Token expired", profile.getName(), new Date(), new Date(expirationTime), expTolerance); final long notBeforeTime = jwtClaimsSet.getNotBeforeTime().getTime(); if (currentTime < (notBeforeTime - nbfTolerance.getTime(MILLISECONDS))) { throw new TokenNotYetValidException("Token is not yet valid", profile.getName(), new Date(), new Date(notBeforeTime), expTolerance);
final long notBeforeTime = claims.getNotBeforeTime().getTime(); if (now.getTime() < notBeforeTime) { throw new ValidationResponseException(OAuth2Validator.ValidationResponse.NOT_BEFORE_FAILED); final long expirationTime = claims.getExpirationTime().getTime(); if (now.getTime() > expirationTime) { throw new ValidationResponseException(OAuth2Validator.ValidationResponse.EXPIRES_FAILED); final JSONObject internal = JSONObjectUtils.parseJSONObject(String.valueOf(claims.getClaim(Claims.TAG_INTERNAL.getName()))); final long diff = now.getTime() - claims.getIssueTime().getTime();
/** * Validate that the expiration time of the JWT token has not been violated. * If it has then throw an AuthenticationException. Override this method in * subclasses in order to customize the expiration validation behavior. * * @param jwtToken the token that contains the expiration date to validate * @return valid true if the token has not expired; false otherwise */ protected boolean validateExpiration(SignedJWT jwtToken) { boolean valid = false; try { Date expires = jwtToken.getJWTClaimsSet().getExpirationTime(); if (expires == null || new Date().before(expires)) { LOG.debug("JWT token expiration date has been " + "successfully validated"); valid = true; } else { LOG.warn("JWT expiration date validation failed."); } } catch (ParseException pe) { LOG.warn("JWT expiration date validation failed.", pe); } return valid; } }
@Override public String getUsername(final ReadOnlyJWTClaimsSet claims) { final Object result = get(claims.getAllClaims(), new StringTokenizer(userClaim, ".")); String username = null; if (String.class.isInstance(result)) { username = (String) result; } else if (result != null) { username = String.valueOf(result); } if (username != null && username.length() > 0) { return username; } return "unknown_user"; }
public void validateClientMatchesRefreshToken(final AccessTokenRequest request) { final Account client = request.getClient(); if (client == null) return; final String grantType = request.getGrantType(); final String refreshToken = request.getRefreshToken(); if (StringUtils.isBlank(refreshToken) && !Constants.GRANT_TYPE_REFRESH_TOKEN.equals(grantType)) return; try { final ReadOnlyJWTClaimsSet claimSet = jwt.getClaimSet(null, refreshToken, false, (Key) null, null); final JSONObject object = (JSONObject) claimSet.getClaim("tag-internal"); final String clientId = (String) object.get("client-id"); if (StringUtils.isBlank(clientId)) return; if (StringUtils.isBlank(client.getName())) return; if (!clientId.equals(client.getName())) { throw new ValidationResponseException(OAuth2Validator.ValidationResponse.CLIENT_NOT_MATCHING); } } catch (final HttpResponseException e) { LOG.finest(Oauth2Codes.UPARSABLE_REFRESH_TOKEN, String.format("Unparsable refresh token %s.", refreshToken), e); throw new ValidationResponseException(OAuth2Validator.ValidationResponse.REVOKE_INVALID_JWT); } }
String userName = jwsObject.getJWTClaimsSet().getStringClaim(SIGNED_JWT_AUTH_USERNAME); String tenantDomain = MultitenantUtils.getTenantDomain(userName); userName = MultitenantUtils.getTenantAwareUsername(userName);
final SignedJWT signedPreviousRT = SignedJWT.parse(previousRT); final ReadOnlyJWTClaimsSet previousCS = signedPreviousRT.getJWTClaimsSet(); final String tagInternalPayload = String.valueOf(previousCS.getClaim(Claims.TAG_INTERNAL.getName())); final JSONObject tagInternal = JSONObjectUtils.parseJSONObject(tagInternalPayload); long diff = refreshClaimsSet.getIssueTime().getTime() - previousCS.getIssueTime().getTime(); refreshTimeToLive = prev.subtract(new LongDuration(diff, TimeUnit.MILLISECONDS));
try { List<String> tokenAudienceList = jwtToken.getJWTClaimsSet() .getAudience();
private void extractUsernameAndClientId(ReadOnlyJWTClaimsSet claimsSet){ JSONObject tagInternal = (JSONObject) claimsSet.getCustomClaims().get("tag-internal"); if(tagInternal != null){ Object clientId = tagInternal.get("client-id"); Object username = tagInternal.get("username"); RequestContext context = null; if(RequestFacade.class.isInstance(request)) { final RequestFacade tomcatFacade = RequestFacade.class.cast(request); final Request tomcatRequest = ((Request) Reflections.get(tomcatFacade, "request")); context = RequestContext.fromRequest(tomcatRequest); } else { context = RequestContext.fromRequest((Request) request); } RequestContext.AuthenticationInfo bearer = context.getAuthenticationInfo("bearer"); if(bearer != null){ if (username != null) { bearer.setUsername(username.toString()); } if (clientId != null) { bearer.setClientId(clientId.toString()); } } } }
/** * Validate that the expiration time of the JWT token has not been violated. * If it has then throw an AuthenticationException. Override this method in * subclasses in order to customize the expiration validation behavior. * * @param jwtToken the token that contains the expiration date to validate * @return valid true if the token has not expired; false otherwise */ protected boolean validateExpiration(SignedJWT jwtToken) { boolean valid = false; try { Date expires = jwtToken.getJWTClaimsSet().getExpirationTime(); if (expires == null || new Date().before(expires)) { LOG.debug("JWT token expiration date has been " + "successfully validated"); valid = true; } else { LOG.warn("JWT expiration date validation failed."); } } catch (ParseException pe) { LOG.warn("JWT expiration date validation failed.", pe); } return valid; } }
private void enrichSubject(final Subject subject, final ReadOnlyJWTClaimsSet claims) { claims.getAllClaims().forEach((k, v) -> subject.getPrincipals().add(new KeyValuePrincipal(k, v, "claim"))); }
null); final String tokenType = String.valueOf(claims.getClaim(Claims.TOKEN_TYPE.getName())); if (!tokenTypes.contains(tokenType)) { throw new ValidationResponseException(OAuth2Validator.ValidationResponse.TOKEN_TYPE_INVALID);
try { List<String> tokenAudienceList = jwtToken.getJWTClaimsSet() .getAudience();
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; }
String resolveJwt(final ReadOnlyJWTClaimsSet claimsSet, final String key) { final Object result = get(claimsSet.getAllClaims(), new StringTokenizer(key, ".")); final String value = String.class.isInstance(result) ? String.class.cast(result) : String.valueOf(result); EnvironmentEventLogger.lookupJWT(key, value); return value; }
final JSONObject tagInternal = (JSONObject) jwt.getJWTClaimsSet().getClaim("tag-internal"); final String innerToken = (String) tagInternal.get("inner-jwt"); return SignedJWT.parse(innerToken);
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", e); } return false; }