基于HS256算法验证
@throws InvalidTokenException 如果签名的格式不正确
12553
private static boolean verifySignature(String content, String secret, String signature) throws InvalidTokenException{
        try {
            SecretKey secretKey = new SecretKeySpec(secret.getBytes(), ALG_HMACSHA256);
            Mac mac = Mac.getInstance(ALG_HMACSHA256);
            mac.init(secretKey);
            byte[] bytes = mac.doFinal(content.getBytes());
            String base64 = base64UrlEncode(bytes);
            return  Strings.equals(base64,signature);
        } catch (Exception e) {
            throw new RuntimeException("Verify signature error", e);
        }
    }
277074
@FFDCIgnore(Exception.class)
    protected void initSigningKey(BuilderImpl jwtBuilder, JwtConfig jwtConfig) throws JwtTokenException {
        String keyType = Constants.SIGNING_KEY_X509;
        try {
            if (jwtConfig.isJwkEnabled() && SIGNATURE_ALG_RS256.equals(signatureAlgorithm)) {
                keyType = Constants.SIGNING_KEY_JWK;
                if (tc.isDebugEnabled()) {
                    Tr.debug(tc, "Signing key type is " + keyType);
                }
                JSONWebKey jwk = jwtConfig.getJSONWebKey();
                if (jwk == null) {
                    if (tc.isDebugEnabled()) {
                        Tr.debug(tc, "Did not succcessfully build a JWK");
                    }
                    _signingKey = null;
                    _keyId = null;
                } else {
                    _signingKey = jwk.getPrivateKey();
                    _keyId = jwk.getKeyID();
                }
            } else {
                if (SIGNATURE_ALG_HS256.equals(signatureAlgorithm)) {
                    keyType = Constants.SIGNING_KEY_SECRET;
                    if (tc.isDebugEnabled()) {
                        Tr.debug(tc, "Signing key type is " + keyType);
                    }
                    String sharedKey = jwtBuilder.getSharedKey();
                    if (JwtUtils.isNullEmpty(sharedKey)) {
                        sharedKey = jwtConfig.getSharedKey();
                    }
                    if (!JwtUtils.isNullEmpty(sharedKey)) {
                        _signingKey = new HmacKey(sharedKey.getBytes("UTF-8"));
                    } else {
                        _signingKey = null;
                    }

                } else if (SIGNATURE_ALG_RS256.equals(signatureAlgorithm)) {
                    _signingKey = jwtBuilder.getKey();
                    if (tc.isDebugEnabled()) {
                        Tr.debug(tc, "Signing key type is " + keyType);
                    }
                    if (_signingKey == null) {
                        String keyAlias = null;
                        String keyStoreRef = null;
                        keyAlias = jwtConfig.getKeyAlias();
                        keyStoreRef = jwtConfig.getKeyStoreRef();
                        _signingKey = JwtUtils.getPrivateKey(keyAlias, keyStoreRef);
                        _keyId = buildKidFromPublicKey(JwtUtils.getPublicKey(keyAlias, keyStoreRef));
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Key alias: " + keyAlias + ", Keystore: " + keyStoreRef+ ", kid: " + _keyId);
                        }
                    }

                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "RSAPrivateKey: " + (_signingKey instanceof RSAPrivateKey));
                    }
                    if (_signingKey != null && !(_signingKey instanceof RSAPrivateKey)) {
                        // error handling
                        // String errorMsg = Tr.formatMessage(tc, "SIGNING_KEY_NOT_RSA", new Object[] { signatureAlgorithm });
                        // Object[] objs = new Object[] { signatureAlgorithm, errorMsg };
                        // noKeyException = JWTTokenException.newInstance(false, "JWT_BAD_SIGNING_KEY", objs);
                        _signingKey = null; // we will catch this later in jwtSigner
                        _keyId = null;
                    }
                }
            }
        } catch (Exception e) {
            // UnsupportedEncodingException e (won't happen)
            // if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            // Tr.debug(tc, "Exception obtaining the signing key: " + e);
            // }
            // error messages
            // JWT_BAD_SIGNING_KEY=CWWKS1455E: A signing key was not available. The signature algorithm is [{0}]. {1}

            Object[] objs = new Object[] { signatureAlgorithm, jwtConfig.isJwkEnabled(), e.getLocalizedMessage() }; // let JWTTokenException handle the exception
            JwtTokenException jte = JwtTokenException.newInstance(false, "JWT_NO_SIGNING_KEY_WITH_ERROR", objs);
            jte.initCause(e);
            throw jte;
        }
        if (_signingKey == null) {
            Object[] objs = new Object[] { signatureAlgorithm, jwtConfig.isJwkEnabled(), "" }; // let JWTTokenException handle the exception
            throw JwtTokenException.newInstance(true, "JWT_NO_SIGNING_KEY_WITH_ERROR", objs);
        }
    }
864575
final public void wimexpr() throws ParseException, AttributeNotSupportedException {
        switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
            case SLASH_SLASH:
                jj_consume_token(SLASH_SLASH);
                jj_consume_token(ENTITIES);
                if (jj_2_1(2147483647)) {
                    predefinedLocPredicate();
                } else {
                    switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
                        case 4:
                            locOrEntityTypeExpr();
                            break;
                        default:
                            jj_la1[0] = jj_gen;
                            jj_consume_token(-1);
                            throw new ParseException();
                    }
                }
                break;
            case 2:
            case 7:
                if (jj_2_2(2147483647)) {
                    predefinedPredicate();
                } else {
                    switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
                        case 7:
                            orEntityTypeExpr();
                            break;
                        default:
                            jj_la1[1] = jj_gen;
                            jj_consume_token(-1);
                            throw new ParseException();
                    }
                }
                break;
            default:
                jj_la1[2] = jj_gen;
                jj_consume_token(-1);
                throw new ParseException();
        }
    }
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);
		}
	}
296123
public function checkToken($request_token)
    {
        $token_manager = $this->container->get('security.csrf.token_manager');
        $token = new CsrfToken('file_manager', $request_token);
        $valid = $token_manager->isTokenValid($token);

        if (!$valid) {
            throw new InvalidCsrfTokenException();
        }
    }
276458
@Override
	public Map<String, String> convert(String token) {
		Map<String, String> headers;

		int headerEndIndex = token.indexOf('.');
		if (headerEndIndex == -1) {
			throw new InvalidTokenException("Invalid JWT. Missing JOSE Header.");
		}

		byte[] decodedHeader;

		try {
			decodedHeader = Codecs.b64UrlDecode(token.substring(0, headerEndIndex));
		} catch (IllegalArgumentException ex) {
			throw new InvalidTokenException("Invalid JWT. Malformed JOSE Header.", ex);
		}

		JsonParser parser = null;

		try {
			parser = this.factory.createParser(decodedHeader);
			headers = new HashMap<String, String>();
			if (parser.nextToken() == JsonToken.START_OBJECT) {
				while (parser.nextToken() == JsonToken.FIELD_NAME) {
					String headerName = parser.getCurrentName();
					parser.nextToken();
					String headerValue = parser.getValueAsString();
					headers.put(headerName, headerValue);
				}
			}

		} catch (IOException ex) {
			throw new InvalidTokenException("An I/O error occurred while reading the JWT: " + ex.getMessage(), ex);
		} finally {
			try {
				if (parser != null) parser.close();
			} catch (IOException ex) { }
		}

		return headers;
	}
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;
    }
399256
public JWTTokenValidationFailedException errorCommon(boolean bTrError, TraceComponent tc, String msgCode, Object[] objects) throws JWTTokenValidationFailedException {
        if (bTrError && !bInboundSupported) {
            Tr.error(tcCommon, msgCode, objects);
        }
        if (TYPE_ID_TOKEN.equals(this.getTokenType())) {
            return IDTokenValidationFailedException.format(tc, msgCode, objects);
        } else {
            return JWTTokenValidationFailedException.format(tc, msgCode, objects);
        }
    }
742700
@Override
    public Builder claimFrom(JwtToken jwt, String claimName) throws InvalidClaimException, InvalidTokenException {
        isValidToken(jwt);
        if (JwtUtils.isNullEmpty(claimName)) {
            String err = Tr.formatMessage(tc, "JWT_INVALID_CLAIM_ERR", new Object[] { claimName });
            throw new InvalidClaimException(err);
        }
        if (jwt.getClaims().get(claimName) != null) {
            claims.put(claimName, jwt.getClaims().get(claimName));
        }
        // else {
        // String err = Tr.formatMessage(tc, "JWT_INVALID_CLAIM_VALUE_ERR", new
        // Object[] { claimName, "null" });
        // throw new InvalidClaimException(err);
        // }
        return this;
    }
1287308
final public function check() : bool
    {
        if(empty($this->getTimestamp())){
            throw new InvalidTimestampException('请设置参数:' . $this->input_timestamp);
        }
        if(date("Y-m-d H:i:s", strtotime($this->getTimestamp())) != $this->getTimestamp()){
            throw new InvalidTimestampException('参数格式错误:' . $this->input_timestamp);
        }
        if(strtotime($this->getTimestamp()) < time() - $this->lifetime){
            throw new InvalidTimestampException('生成的请求参数已经超过有效期');
        }
        return true;
    }
27189
@Override
    public Builder signWith(String algorithm, Key key) throws KeyException {

        if (algorithm == null || algorithm.isEmpty() || !algorithm.equals(Constants.SIGNATURE_ALG_RS256)) {
            String err = Tr.formatMessage(tc, "JWT_INVALID_ALGORITHM_ERR", new Object[] { algorithm, Constants.SIGNATURE_ALG_RS256 });
            throw new KeyException(err);
        }
        if (key == null || !(key instanceof RSAPrivateKey)) {
            String err = Tr.formatMessage(tc, "JWT_INVALID_KEY_ERR", new Object[] { algorithm, key });
            throw new KeyException(err);
        }
        alg = algorithm;
        privateKey = key;
        return this;
    }
6652
protected function validateIdToken($idToken) {
        $segments = explode('.', $idToken);
        if (count($segments) != 3) {
            throw new InvalidIdTokenException('Invalid Token');
        }
        $header = json_decode($this->decodeBase64Url($segments[0]), true);
        if (empty($header)) {
            throw new InvalidIdTokenException('Invalid Token');
        }
        $payload = json_decode($this->decodeBase64Url($segments[1]), true);
        if (empty($payload)) {
            throw new InvalidIdTokenException('Invalid Token');
        }
        $signature = $this->decodeBase64Url($segments[2]);

        $signingInput = implode('.', array($segments[0], $segments[1]));
        $kid = isset($header['kid']) ? $header['kid'] : null;
        switch ($header['alg']) {
            case 'RS256':
            case 'RS384':
            case 'RS512':
                // 署名検証用に公開鍵を取得する
                $publicKey = $this->getPublicKey($kid);

                $algo = 'sha' . substr($header['alg'], 2);
                if (openssl_verify($signingInput, $signature, $publicKey, $algo) != 1) {
                    openssl_free_key($publicKey);
                    throw new InvalidIdTokenException('Signature Mismatch');
                }
                openssl_free_key($publicKey);
                break;
            default:
                throw new InvalidIdTokenException('Unsupported Algorithm: ' . $header['alg']);
        }

        // Check Issuer
        if ($payload['iss'] != 'minecraft.jp') {
            throw new InvalidIdTokenException('Invalid Issuer.');
        }

        // Check Client Id
        if ($payload['aud'] != $this->getClientId()) {
            throw new InvalidIdTokenException('Client ID Mismatch.');
        }

        // Check expired
        $now = time();
        if ($payload['exp'] < $now || $payload['iat'] < $now - 600) {
            throw new InvalidIdTokenException('ID Token expired.');
        }

        // Check nonce
        if ($payload['nonce'] != $this->sessionStorage->read('nonce')) {
            throw new InvalidIdTokenException('Nonce Mismatch.');
        }

        $this->sessionStorage->remove('nonce');

        return $payload;
    }
1202389
public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException {
        try {
            String[] array = new String[]{token, timestamp, nonce, encrypt};
            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < 4; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();

            return getSHA1HexString(str);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.ComputeSignatureError);
        }
    }
1314102
@FFDCIgnore({ IDTokenValidationFailedException.class })
    @Override
    public boolean verify(long clockSkew, Object key)
            throws IDTokenValidationFailedException {
        boolean verified = false;
        try {
            if (super.verify(clockSkew, key)) {
                payload.putAll(super.getPayload());
                addToPayload();
                // verify accesstoken hash if it exists
                if (payload.getAccessTokenHash() != null) {
                    String athash = payload.getAccessTokenHash();
                    if (this.ath == null) {
                        // internal error
                        Tr.error(tc, "OIDC_IDTOKEN_VERIFY_ATHASH_ERR", new Object[] { getClientId(), this.ath, athash });
                        throw IDTokenValidationFailedException.format("OIDC_IDTOKEN_VERIFY_ATHASH_ERR", getClientId(), this.ath, athash);
                    }
                    if (verifyAccessTokenHash(athash)) {
                        verified = true;
                    } else {
                        Tr.error(tc, "OIDC_IDTOKEN_VERIFY_ATHASH_ERR", new Object[] { getClientId(), this.ath, athash });
                        throw IDTokenValidationFailedException.format("OIDC_IDTOKEN_VERIFY_ATHASH_ERR", getClientId(), this.ath, athash);
                    }
                } else {
                    verified = true;
                }
            }
        } catch (IDTokenValidationFailedException e) {
            // Tr.error has been handled
            throw e;
        }
        return verified;
    }
1284960
private byte[] getSha256(byte[] data) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        return digest.digest(data);
    }
1372896
protected function cleanToken() {
    if ($token_name = $this->getToken()) {
      // Remove the token and arguments and return the path.
      $path = substr($this->path, strlen($token_name));
      return preg_replace('/<.*>/', '', $path);
    }
    $message = sprintf('No token could be found in "%s". Available tokens are: %s.', $this->path, implode(', ', array_keys($this->supportedTokens)));
    throw new ClassLoaderException($message);
  }
189701
public boolean validateToken(final String token) {
        try {
            final JwtParser jwtParser = Jwts.parser().setSigningKey(key);
            jwtParser.parse(token);
            this.subject = jwtParser.parseClaimsJws(token).getBody().getSubject();
            this.expiration = jwtParser.parseClaimsJws(token).getBody().getExpiration();
            return true;
        } catch (SignatureException e) {
            LOGGER.info(SecurityMarkers.SECURITY_FAILURE, "Received token that did not pass signature verification");
        } catch (ExpiredJwtException e) {
            LOGGER.debug(SecurityMarkers.SECURITY_FAILURE, "Received expired token");
        } catch (MalformedJwtException e) {
            LOGGER.debug(SecurityMarkers.SECURITY_FAILURE, "Received malformed token");
            LOGGER.debug(SecurityMarkers.SECURITY_FAILURE, e.getMessage());
        } catch (UnsupportedJwtException | IllegalArgumentException e) {
            LOGGER.error(SecurityMarkers.SECURITY_FAILURE, e.getMessage());
        }
        return false;
    }