/*
(non-Javadoc)

@see com.ibm.ws.security.jwt.internal.Builder#claim(java.lang.String, java.lang.Object)
489918
@Override
    public Builder claim(String name, Object value) throws InvalidClaimException {
        if (isValidClaim(name, value)) {
            if (name.equals(Claims.AUDIENCE)) {
                if (value instanceof ArrayList) {
                    this.audience((ArrayList) value);
                } else if (value instanceof String) {
                    String[] auds = ((String) value).split(" ");
                    ArrayList<String> audList = new ArrayList<String>();
                    for (String aud : auds) {
                        if (!aud.isEmpty()) {
                            audList.add(aud.trim());
                        }
                    }
                    if (!audList.isEmpty()) {
                        this.audience(audList);
                    }
                } else {
                    String msg = Tr.formatMessage(tc, "JWT_INVALID_CLAIM_VALUE_TYPE", new Object[] { Claims.AUDIENCE });
                    throw new InvalidClaimException(msg);
                }
            } else if (name.equals(Claims.EXPIRATION)) {
                if (value instanceof Long) {
                    this.expirationTime((Long) value);
                } else if (value instanceof Integer) {
                    this.expirationTime(((Integer) value).longValue());
                } else {
                    String msg = Tr.formatMessage(tc, "JWT_INVALID_CLAIM_VALUE_TYPE", new Object[] { Claims.EXPIRATION });
                    throw new InvalidClaimException(msg);
                }
            } else if (name.equals(Claims.ISSUED_AT)) {
                if (value instanceof Long) {
                    this.issueTime((Long) value);
                } else if (value instanceof Integer) {
                    this.expirationTime(((Integer) value).longValue());
                } else {
                    String msg = Tr.formatMessage(tc, "JWT_INVALID_CLAIM_VALUE_TYPE", new Object[] { Claims.ISSUED_AT });
                    throw new InvalidClaimException(msg);
                }
            } else if (name.equals(Claims.NOT_BEFORE)) {
                if (value instanceof Long) {
                    this.notBefore((Long) value);
                } else if (value instanceof Integer) {
                    this.expirationTime(((Integer) value).longValue());
                } else {
                    String msg = Tr.formatMessage(tc, "JWT_INVALID_CLAIM_VALUE_TYPE", new Object[] { Claims.NOT_BEFORE });
                    throw new InvalidClaimException(msg);
                }
            } else if (name.equals(Claims.ISSUER) || name.equals(Claims.SUBJECT)) {
                if (value instanceof String) {
                    if (name.equals(Claims.ISSUER)) {
                        this.issuer((String) value);
                    } else {
                        this.subject((String) value);
                    }
                } else {
                    String msg = Tr.formatMessage(tc, "JWT_INVALID_CLAIM_VALUE_TYPE", new Object[] { name });
                    throw new InvalidClaimException(msg);
                }
            } else {
                claims.put(name, value);
            }
        }
        return this;
    }
895415
@Override
    public JwtToken buildJwt() throws JwtException, InvalidBuilderException {
        // Create JWT here
        // TODO check for default claims?
        JwtConfig config = getConfig(configId);
        JwtToken jwt = new TokenImpl(this, config);

        return jwt;
    }
874182
boolean validateIssuer(String consumerConfigId, String issuers, String tokenIssuer) throws InvalidClaimException {
		boolean isIssuer = false;
		if (issuers == null || issuers.isEmpty()) {
			String msg = Tr.formatMessage(tc, "JWT_TRUSTED_ISSUERS_NULL",
					new Object[] { tokenIssuer, consumerConfigId });
			throw new InvalidClaimException(msg);
		}

		StringTokenizer st = new StringTokenizer(issuers, ",");
		while (st.hasMoreTokens()) {
			String iss = st.nextToken().trim();
			if (tc.isDebugEnabled()) {
				Tr.debug(tc, "Trusted issuer: " + iss);
			}
			if (Constants.ALL_ISSUERS.equals(iss) || (tokenIssuer != null && tokenIssuer.equals(iss))) {
				isIssuer = true;
				break;
			}
		}

		if (!isIssuer) {
			String msg = Tr.formatMessage(tc, "JWT_ISSUER_NOT_TRUSTED",
					new Object[] { tokenIssuer, consumerConfigId, issuers });
			throw new InvalidClaimException(msg);
		}
		return isIssuer;
	}
841390
public void addTypeToClaimProducer(@Observes ProcessBeanAttributes pba) {
        if (pba.getAnnotated().isAnnotationPresent(Claim.class)) {
            Claim claim = pba.getAnnotated().getAnnotation(Claim.class);
            if (claim.value().length() == 0 && claim.standard() == Claims.UNKNOWN) {
                log.debugf("addTypeToClaimProducer: %s\n", pba.getAnnotated());
                BeanAttributes delegate = pba.getBeanAttributes();
                String name = delegate.getName();
                if (delegate.getTypes().contains(Optional.class)) {
                    if (providerOptionalTypes.size() == 0) {
                        providerOptionalTypes.add(Optional.class);
                    }
                    pba.setBeanAttributes(new ClaimProviderBeanAttributes(delegate, providerOptionalTypes, providerQualifiers));
                // This is
                } else if (name != null && name.startsWith("RawClaimTypeProducer#")) {
                    if (rawTypes.size() == 0) {
                        rawTypes.add(Object.class);
                    }
                    pba.setBeanAttributes(new ClaimProviderBeanAttributes(delegate, rawTypes, rawTypeQualifiers));
                    log.debugf("Setup RawClaimTypeProducer BeanAttributes");
                }
            }
        }
    }
321671
public static boolean isValidJWToken(String secret, SignedJWT jwt) {
		try {
			if (secret != null && jwt != null) {
				JWSVerifier verifier = new MACVerifier(secret);
				if (jwt.verify(verifier)) {
					Date referenceTime = new Date();
					JWTClaimsSet claims = jwt.getJWTClaimsSet();

					Date expirationTime = claims.getExpirationTime();
					Date notBeforeTime = claims.getNotBeforeTime();
					boolean expired = expirationTime == null || expirationTime.before(referenceTime);
					boolean notYetValid = notBeforeTime == null || notBeforeTime.after(referenceTime);

					return !(expired || notYetValid);
				}
			}
		} catch (JOSEException e) {
			logger.warn(null, e);
		} catch (ParseException ex) {
			logger.warn(null, ex);
		}
		return false;
	}
1360839
public String createTokenString(String builderConfigId) {
		try {
			return createTokenString(builderConfigId, WSSubject.getRunAsSubject(), null, null);

			// JwtBuilder builder = JwtBuilder.create(builderConfigId);
			//
			// // all the "normal" stuff like issuer, aud, etc. is handled
			// // by the builder, we only need to add the mp-jwt things
			// // that the builder is not already aware of.
			// String user = getUserName();
			// builder.subject(user);
			// builder.claim(USER_CLAIM, user);
			//
			// ArrayList<String> groups = getGroups();
			// if (isValidList(groups)) {
			// builder.claim(GROUP_CLAIM, groups);
			// }
			//
			// return builder.buildJwt().compact();

		} catch (Exception e) {
			// ffdc
			return null;
		}

	}
938367
public static Optional<Principal> withWebIdClaim(final Claims claims) {
        final String webid = claims.get(WEBID, String.class);
        if (webid == null) return empty();
        LOGGER.debug("Using JWT claim with webid: {}", webid);
        return of(new OAuthPrincipal(webid));
    }
7245
public BackchannelAuthenticationCompleteRequest setClaims(Map<String, Object> claims)
    {
        if (claims == null || claims.size() == 0)
        {
            this.claims = null;
        }
        else
        {
            setClaims(Utils.toJson(claims));
        }

        return this;
    }
1306156
private void checkJwtClaims(JwtClaims jwtClaims) {
    Optional<NumericDate> expiration = getDateClaim(ReservedClaimNames.EXPIRATION_TIME, jwtClaims);
    if (!expiration.isPresent()) {
      throw new UnauthenticatedException("Missing expiration field");
    }
    Optional<NumericDate> notBefore = getDateClaim(ReservedClaimNames.NOT_BEFORE, jwtClaims);

    NumericDate currentTime = NumericDate.fromMilliseconds(clock.currentTimeMillis());
    if (expiration.get().isBefore(currentTime)) {
      throw new UnauthenticatedException("The auth token has already expired");
    }

    if (notBefore.isPresent() && notBefore.get().isAfter(currentTime)) {
      String message = "Current time is earlier than the \"nbf\" time";
      throw new UnauthenticatedException(message);
    }
  }
47635
async def add_claims(self, payload, user, *args, **kwargs):
        
        delta = timedelta(seconds=self.config.expiration_delta())
        exp = datetime.utcnow() + delta
        additional = {"exp": exp}

        for option in ["iss", "iat", "nbf", "aud"]:
            setting = "claim_{}".format(option.lower())
            if setting in self.config:  # noqa
                attr = self.config.get(setting)
                if attr:
                    self.claims.append(option)
                    method_name = "build_claim_{}".format(option)
                    method = getattr(utils, method_name)
                    additional.update({option: method(attr, self.config)})

        payload.update(additional)

        if self._custom_claims:
            custom_claims = {}
            for claim in self._custom_claims:
                custom_claims[claim.get_key()] = await utils.call(
                    claim.setup, payload, user
                )
            payload.update(custom_claims)

        return payload
566812
public boolean contains(JwtToken token) {
        if (token == null) {
            return false;
        }
        Claims claims = token.getClaims();
        if (claims == null) {
            return false;
        }
        String key = claims.getJwtId();
        if (key == null) {
            return false;
        }
        key = getCacheKey(token);
        long currentTimeMilliseconds = (new Date()).getTime();
        synchronized (primaryTable) {
            Long exp = (Long) primaryTable.get(key); // milliseconds
            if (exp != null) {
                if (exp.longValue() > currentTimeMilliseconds) { // not expired yet // milliseconds
                    return true;
                } else {
                    primaryTable.remove(key);
                }
            }
            // cache the jwt
            long tokenExp = claims.getExpiration() * 1000; // milliseconds
            if (tokenExp == 0) { // in case it's not set, let's give it one hour
                tokenExp = currentTimeMilliseconds + 60 * 60 * 1000; // 1 hour
            }
            primaryTable.put(key, Long.valueOf(tokenExp));
        }

        return false;
    }
264753
private void handleClaims(String jwt) {
        try {
            if (claimsUtils == null) {
                claimsUtils = new ClaimsUtils();
            }
            this.claimsSet = claimsUtils.getJwtClaims(jwt);
        } catch (JoseException e) {
            Tr.error(tc, "ERROR_GETTING_CLAIMS_FROM_JWT_STRING", new Object[] { e.getLocalizedMessage() });
        }
    }
123234
@Override
    public Builder notBefore(long time_from) throws InvalidClaimException {

        if (time_from > 0) {
            claims.put(Claims.NOT_BEFORE, time_from);
        } else {
            String err = Tr.formatMessage(tc, "JWT_INVALID_TIME_CLAIM_ERR", new Object[] { Claims.NOT_BEFORE });
            throw new InvalidClaimException(err);
        }
        return this;
    }
1269638
@Override
    public Builder issuer(String issuerUrl) throws InvalidClaimException {
        if (issuerUrl != null && !issuerUrl.isEmpty()) {
            claims.put(Claims.ISSUER, issuerUrl);
        } else {
            String err = Tr.formatMessage(tc, "JWT_INVALID_CLAIM_VALUE_ERR", new Object[] { Claims.ISSUER, issuerUrl });
            throw new InvalidClaimException(err);
        }
        return this;
    }
715907
public JwtClaims getJwtClaims(String jwt) throws JoseException {
        String methodName = "getJwtClaims";
        if (tc.isDebugEnabled()) {
            Tr.entry(tc, methodName, jwt);
        }
        JwtClaims jwtclaims = new JwtClaims();
        String payload = getJwtPayload(jwt);
        if (payload != null) {
            jwtclaims = getClaimsFromJwtPayload(jwt, payload);
        }
        if (tc.isDebugEnabled()) {
            Tr.exit(tc, methodName, jwtclaims);
        }
        return jwtclaims;
    }
1114224
private JsonValue getAsJsonValue(String claimName) {
        JsonReader reader = Json.createReader(new StringReader(jsonWebToken.toString()));
        JsonObject jsonObject = reader.readObject();
        return jsonObject.get(claimName);
    }
668189
async function preclaim (name, options = {}) {
  const opt = R.merge(this.Ae.defaults, options)
  const _salt = salt()
  const height = await this.height()
  const hash = await commitmentHash(name, _salt)

  const preclaimTx = await this.namePreclaimTx(R.merge(opt, {
    accountId: await this.address(),
    commitmentId: hash
  }))

  const result = await this.send(preclaimTx, opt)

  return Object.freeze({
    ...result,
    height,
    claim: options => this.aensClaim(name, _salt, (height + 1), options),
    salt: _salt,
    commitmentId: hash
  })
}