/*
(non-Javadoc)

@see com.ibm.ws.security.jwt.internal.Builder#claimFrom(java.lang.String, java.lang.String)
501746
@Override
    public Builder claimFrom(String jsonOrJwt, String claim) throws InvalidClaimException, InvalidTokenException {
        if (JwtUtils.isNullEmpty(claim)) {
            String err = Tr.formatMessage(tc, "JWT_INVALID_CLAIM_ERR", new Object[] { claim });
            throw new InvalidClaimException(err);
        }
        if (isValidToken(jsonOrJwt)) {
            String decoded = jsonOrJwt;
            if (JwtUtils.isBase64Encoded(jsonOrJwt)) {
                decoded = JwtUtils.decodeFromBase64String(jsonOrJwt);
            }
            boolean isJson = JwtUtils.isJson(decoded);

            if (!isJson) {
                String jwtPayload = JwtUtils.getPayload(jsonOrJwt);
                decoded = JwtUtils.decodeFromBase64String(jwtPayload);
            }

            // } else {
            // // either decoded payload from jwt or encoded/decoded json string
            // if (JwtUtils.isBase64Encoded(jsonOrJwt)) {
            // decoded = JwtUtils.decodeFromBase64String(jsonOrJwt);
            // }
            // }

            if (decoded != null) {
                Object claimValue = null;
                try {
                    if ((claimValue = JwtUtils.claimFromJsonObject(decoded, claim)) != null) {
                        claims.put(claim, claimValue);
                    }
                } catch (JoseException e) {
                    String err = Tr.formatMessage(tc, "JWT_INVALID_TOKEN_ERR");
                    throw new InvalidTokenException(err);
                }
            }
        }

        return this;
    }
504619
public IoTClaimed claimThing(Collection<Tag> metaTags) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
        return claimThing(metaTags, true);
    }
1312157
protected ProcessedClaim createProcessedClaim(final Claim requestClaim, final ClaimsParameters parameters) {
        val claim = new ProcessedClaim();
        claim.setClaimType(createProcessedClaimType(requestClaim, parameters));
        claim.setIssuer(this.issuer);
        claim.setOriginalIssuer(this.issuer);
        claim.setValues(requestClaim.getValues());
        return claim;
    }
652121
@Override
    public Builder jwtId(boolean create) {
        if (create) {
            String jti = JwtUtils.getRandom(16);
            claims.put(Claims.ID, jti);
        } else {
            claims.remove(Claims.ID);
        }

        return this;
    }
35005
public SignedJWT verifyToken(String jwtString) throws ParseException {
        try {
            SignedJWT jwt = SignedJWT.parse(jwtString);
            if (jwt.verify(new MACVerifier(this.jwtSharedSecret))) {
                return jwt;
            }
            return null;
        } catch (JOSEException e) {
            throw new RuntimeException("Error verifying JSON Web Token", e);
        }
    }
87609
void validateSignatureAlgorithmWithKey(JwtConsumerConfig config, Key key) throws InvalidClaimException {
		String signatureAlgorithm = config.getSignatureAlgorithm();
		if (key == null && signatureAlgorithm != null && !signatureAlgorithm.equalsIgnoreCase("none")) {
			String msg = Tr.formatMessage(tc, "JWT_MISSING_KEY", new Object[] { signatureAlgorithm });
			throw new InvalidClaimException(msg);
		}
	}
799934
public String getJwtTokenUsingBuilder(String testName, LibertyServer server, String builderId, List<NameValuePair> extraClaims) throws Exception {

        String jwtBuilderUrl = SecurityFatHttpUtils.getServerUrlBase(server) + "/jwtbuilder/build";

        List<NameValuePair> requestParams = setRequestParms(builderId, extraClaims);

        WebClient webClient = new WebClient();
        Page response = invokeUrlWithParameters(testName, webClient, jwtBuilderUrl, requestParams);
        Log.info(thisClass, testName, "JWT builder app response: " + WebResponseUtils.getResponseText(response));

        Cookie jwtCookie = webClient.getCookieManager().getCookie("JWT");
        Log.info(thisClass, testName, "Built JWT cookie: " + jwtCookie);
        Log.info(thisClass, testName, "Cookie value: " + jwtCookie.getValue());
        return jwtCookie.getValue();

    }
974478
public static SignedJWT generateJWToken(User user, App app) {
		if (app != null) {
			try {
				Date now = new Date();
				JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder();
				String userSecret = "";
				claimsSet.issueTime(now);
				claimsSet.expirationTime(new Date(now.getTime() + (app.getTokenValiditySec() * 1000)));
				claimsSet.notBeforeTime(now);
				claimsSet.claim("refresh", getNextRefresh(app.getTokenValiditySec()));
				claimsSet.claim(Config._APPID, app.getId());
				if (user != null) {
					claimsSet.subject(user.getId());
					userSecret = user.getTokenSecret();
				}
				JWSSigner signer = new MACSigner(app.getSecret() + userSecret);
				SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet.build());
				signedJWT.sign(signer);
				return signedJWT;
			} catch (JOSEException e) {
				logger.warn("Unable to sign JWT: {}.", e.getMessage());
			}
		}
		return null;
	}
930800
private void writeTaskClaim(Tenant tenant, String claimID, long claimStamp) {
        DBTransaction dbTran = DBService.instance(tenant).startTransaction();
        dbTran.addColumn(TaskManagerService.TASKS_STORE_NAME, claimID, m_hostClaimID, claimStamp);
        DBService.instance(tenant).commit(dbTran);
    }
1103973
@Override
    public boolean claimPeerLeaseForRecovery(String recoveryIdentityToRecover, String myRecoveryIdentity, LeaseInfo leaseInfo) throws Exception {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "claimPeerLeaseForRecovery", new Object[] { recoveryIdentityToRecover, myRecoveryIdentity, this });
        // What we need to do is to extract the log location for peer servers and put them somewhere to be used in TxRecoveryAgentImp.initiateRecovery.
        boolean claimedLease = false;

        FileChannel fChannel = null;
        // At this point we are ready to acquire a lock on the lease file prior to attempting to read it.
        try {
            // If we are about to recover a peer lease file, then do a check to be sure that no other server instance
            // has "recently" recovered it.
            boolean attemptClaim = true;
            // Read the appropriate lease file (equivalent to a record in the DB table)
            final File leaseFile = new File(_serverInstallLeaseLogDir + String.valueOf(File.separatorChar) + recoveryIdentityToRecover);

            // Get the timestamp when the lease file was last touched.
            final long newleaseTime = AccessController.doPrivileged(new PrivilegedAction<Long>() {
                @Override
                public Long run() {
                    return leaseFile.lastModified();
                }
            });

            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "recoveryId: " + recoveryIdentityToRecover + ", new leaseTime: " + newleaseTime);
            }

            PeerLeaseData pld = new PeerLeaseData(recoveryIdentityToRecover, newleaseTime, _leaseTimeout);
            if (newleaseTime == 0 || !pld.isExpired()) {
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "The lease file has not expired, or does not exist do not attempt recovery");
                attemptClaim = false;
            }

            // Attempt to claim the lease file
            if (attemptClaim) {
                if (lockPeerLease(recoveryIdentityToRecover)) {
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Attempt to read lease file");

                    fChannel = _peerLeaseLock.getFileChannel();
                    if (fChannel != null) {
                        long fileSize = fChannel.size();
                        ByteBuffer buffer = ByteBuffer.allocate((int) fileSize);
                        fChannel.read(buffer);

                        buffer.flip();

                        // Read first (and only) line in file
                        String line = new String(buffer.array());

                        if (tc.isDebugEnabled())
                            Tr.debug(tc, "We have retrieved " + line);

                        // Set the string into the LeaseInfo object
                        leaseInfo.setLeaseDetail(line);
                        claimedLease = true;
                    } else {
                        if (tc.isDebugEnabled())
                            Tr.debug(tc, "Lease Lock's channel was null");
                    }

                } else {
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Failed to lock or read lease file");
                }
            }
        } catch (IOException e) {
            // We're not expecting this to happen. Log the event
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Caught an IOException - " + e);
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "claimPeerLeaseForRecovery", claimedLease);
        return claimedLease;
    }
1283651
public void claimName(String name) {
    checkName(name);
    if (names.add(name, 1) != 0) {
      names.remove(name);
      // give a slightly better error message in this case
      if (reserved.contains(name)) {
        throw new IllegalArgumentException("Tried to claim a reserved name: " + name);
      }
      throw new IllegalArgumentException("Name: " + name + " was already claimed!");
    }
  }
1208275
public static String generateToken(final Integer apiKey, final String apiSecret)
            throws OpenTokException {

        //This is the default expire time we use for rest endpoints.
        final long defaultExpireTime = System.currentTimeMillis() / 1000L
                + TimeUnit.MINUTES.toSeconds(3);
        final JwtClaims claims = new JwtClaims();
        claims.setIssuer(apiKey.toString());
        claims.setStringClaim(ISSUER_TYPE, PROJECT_ISSUER_TYPE);
        claims.setGeneratedJwtId(); // JTI a unique identifier for the JWT.

        return getToken(claims, defaultExpireTime, apiSecret);
    }
120371
void validateIatAndExp(JwtClaims jwtClaims, long clockSkewInMilliseconds) throws InvalidClaimException {
		if (jwtClaims == null) {
			if (tc.isDebugEnabled()) {
				Tr.debug(tc, "Missing JwtClaims object");
			}
			return;
		}
		NumericDate issueAtClaim = getIssuedAtClaim(jwtClaims);
		NumericDate expirationClaim = getExpirationClaim(jwtClaims);

		debugCurrentTimes(clockSkewInMilliseconds, issueAtClaim, expirationClaim);

		validateIssuedAtClaim(issueAtClaim, expirationClaim, clockSkewInMilliseconds);
		validateExpirationClaim(expirationClaim, clockSkewInMilliseconds);

	}
270989
@FFDCIgnore({ MalformedClaimException.class })
    private void convertToList(String claimName, JwtClaims claimsSet) {
        List<String> list = null;
        try {
            list = claimsSet.getStringListClaimValue(claimName);
        } catch (MalformedClaimException e) {
            try {
                String value = claimsSet.getStringClaimValue(claimName);
                if (value != null) {
                    list = new ArrayList<String>();
                    list.add(value);
                    claimsSet.setClaim(claimName, list);
                }
            } catch (MalformedClaimException e1) {
                if (tc.isDebugEnabled()) {
                    Tr.debug(tc, "The value for the claim [" + claimName + "] could not be convered to a string list: " + e1.getLocalizedMessage());
                }
            }
        }
    }
1028673
public String generate(final Map<String, Object> claims) {
        // claims builder
        final JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();

        // add claims
        for (final Map.Entry<String, Object> entry : claims.entrySet()) {
            builder.claim(entry.getKey(), entry.getValue());
        }
        if (this.expirationTime != null) {
            builder.expirationTime(this.expirationTime);
        }
        return internalGenerate(builder.build());
    }
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;
	}
353723
@Override
    public Builder claimFrom(JwtToken jwt) throws InvalidTokenException {
        if (jwt != null && !jwt.getClaims().isEmpty()) {
            claims.putAll(jwt.getClaims());
            // copyClaimsMap(jwt.getClaims());
        } else {
            String err = Tr.formatMessage(tc, "JWT_INVALID_TOKEN_ERR");// "JWT_INVALID_TOKEN_ERR";
            throw new InvalidTokenException(err);
        }
        return this;
    }