Verifies a Gitkit token string.

    Args:
      jwt: string, the token to be checked

    Returns:
      GitkitUser, if the token is valid. None otherwise.
481711
def VerifyGitkitToken(self, jwt):
    
    certs = self.rpc_helper.GetPublicCert()
    crypt.MAX_TOKEN_LIFETIME_SECS = 30 * 86400  # 30 days
    parsed = None
    for aud in filter(lambda x: x is not None, [self.project_id, self.client_id]):
      try:
        parsed = crypt.verify_signed_jwt_with_certs(jwt, certs, aud)
      except crypt.AppIdentityError as e:
        if "Wrong recipient" not in e.message:
          return None
      if parsed:
        return GitkitUser.FromToken(parsed)
    return None
607260
public JsonObject validateTokenToJson(String token) throws GitkitClientException {
    if (token == null) {
      return null;
    }
    try {
      return tokenHelper.verifyAndDeserialize(token).getPayloadAsJsonObject();
    } catch (SignatureException e) {
      throw new GitkitClientException(e);
    }
  }
510417
public GitkitUser updateUser(GitkitUser user)
      throws GitkitClientException, GitkitServerException {
    try {
      return jsonToUser(rpcHelper.updateAccount(user));
    } catch (JSONException e) {
      throw new GitkitServerException(e);
    }
  }
21534
def jwt_decode_token(token):
    
    try:
        return decode(
            token,
            current_app.config['ACCOUNTS_JWT_SECRET_KEY'],
            algorithms=[
                current_app.config['ACCOUNTS_JWT_ALOGORITHM']
            ]
        )
    except DecodeError as exc:
        raise_from(JWTDecodeError(), exc)
    except ExpiredSignatureError as exc:
        raise_from(JWTExpiredToken(), exc)
51587
def get_unverified_header(self, jwt):
        
        headers = self._load(jwt)[2]
        self._validate_headers(headers)

        return headers
682783
def get_token_payload(token)

        # Attempt to decode without verifying. May raise DecodeError.
        decoded = JWT.decode token, nil, false
        payload = decoded[0]

        # At this point, we know that the token is not expired and
        # well formatted. Find out if the payload is well defined.
        if payload.nil?
          # :nocov:
          logger.error("Token payload is nil: #{token}")
          raise UNAUTHORIZED_ERROR, "Invalid token"
          # :nocov:
        end

        return payload

      rescue JWT::DecodeError => e
        logger.error("Token decode error: #{e.message}")
        raise UNAUTHORIZED_ERROR, "Invalid token"
      end
1017754
def verify_token(token)
        logger.debug("Verifying token: #{token}")

        # First get the payload of the token. This will also verify whether
        # or not the token is welformed.
        payload = get_token_payload(token)

        # Next, the payload should define user UUID and session UUID.
        user_uuid = payload["user_uuid"]
        session_uuid = payload["session_uuid"]
        if user_uuid.nil? || session_uuid.nil?
          logger.error("User or session is not specified")
          raise UNAUTHORIZED_ERROR, "Invalid token"
        end
        logger.debug("Token well defined: #{token}")

        # But, the user UUID and session UUID better be valid too. That is,
        # they must be real user and session, and the session must belong to
        # the user.
        auth_user = User.find_by_uuid(user_uuid)
        if auth_user.nil?
          # :nocov:
          logger.error("Specified user doesn't exist #{user_uuid}")
          raise UNAUTHORIZED_ERROR, "Invalid token"
          # :nocov:
        end
        auth_session = Session.find_by_uuid(session_uuid)
        if auth_session.nil? || auth_session.user != auth_user
          logger.error("Specified session doesn't exist #{session_uuid}")
          raise UNAUTHORIZED_ERROR, "Invalid token"
        end

        # Finally, decode the token using the secret. Also check expiration
        # here too.
        JWT.decode token, auth_session.secret, true
        logger.debug("Token well formatted and verified. Set cache.")

        # Return the corresponding session
        return auth_session

      rescue JWT::DecodeError => e
        logger.error(e.message)
        raise UNAUTHORIZED_ERROR, "Invalid token"
      end
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;
    }
669541
def verify_sig(signed_request, secret, issuer=None, algorithms=None,
               expected_aud=None):
    
    if not issuer:
        issuer = _get_issuer(signed_request=signed_request)
    signed_request = _to_bytes(signed_request)
    app_req = _get_json(signed_request)

    # Check signature.
    try:
        jwt.decode(signed_request, secret, verify=True,
                   algorithms=algorithms, audience=expected_aud)
    except jwt.ExpiredSignatureError, exc:
        _re_raise_as(RequestExpired, '%s' % exc, issuer=issuer)
    except jwt.InvalidTokenError, exc:
        _re_raise_as(InvalidJWT,
                     'Signature verification failed: %s' % exc,
                     issuer=issuer)
    return app_req
1327044
def verify_token(self, token, **kwargs):
        """"""
        nonce = kwargs.get('nonce')

        token = force_bytes(token)
        if self.OIDC_RP_SIGN_ALGO.startswith('RS'):
            if self.OIDC_RP_IDP_SIGN_KEY is not None:
                key = self.OIDC_RP_IDP_SIGN_KEY
            else:
                key = self.retrieve_matching_jwk(token)
        else:
            key = self.OIDC_RP_CLIENT_SECRET

        payload_data = self.get_payload_data(token, key)

        # The 'token' will always be a byte string since it's
        # the result of base64.urlsafe_b64decode().
        # The payload is always the result of base64.urlsafe_b64decode().
        # In Python 3 and 2, that's always a byte string.
        # In Python3.6, the json.loads() function can accept a byte string
        # as it will automagically decode it to a unicode string before
        # deserializing https://bugs.python.org/issue17909
        payload = json.loads(payload_data.decode('utf-8'))
        token_nonce = payload.get('nonce')

        if self.get_settings('OIDC_USE_NONCE', True) and nonce != token_nonce:
            msg = 'JWT Nonce verification failed.'
            raise SuspiciousOperation(msg)
        return payload
144705
def get_user_by_action_token(action, token):
    
    data = utils.unsign_url_safe(token,
                                 secret_key=get_jwt_secret(),
                                 salt=action)
    if data is None:
        raise exceptions.AuthError("Invalid Token")
    return get_user_by_id(int(data))
360868
def _verify_jws(self, payload, key):
        """"""
        jws = JWS.from_compact(payload)

        try:
            alg = jws.signature.combined.alg.name
        except KeyError:
            msg = 'No alg value found in header'
            raise SuspiciousOperation(msg)

        if alg != self.OIDC_RP_SIGN_ALGO:
            msg = "The provider algorithm {!r} does not match the client's " \
                  "OIDC_RP_SIGN_ALGO.".format(alg)
            raise SuspiciousOperation(msg)

        if isinstance(key, six.string_types):
            # Use smart_bytes here since the key string comes from settings.
            jwk = JWK.load(smart_bytes(key))
        else:
            # The key is a json returned from the IDP JWKS endpoint.
            jwk = JWK.from_json(key)

        if not jws.verify(jwk):
            msg = 'JWS token verification failed.'
            raise SuspiciousOperation(msg)

        return jws.payload
160972
def verify(self, token, verifying_key_or_keys, num_required=None):
        
        if not isinstance(verifying_key_or_keys, (list, str, unicode)):
            raise ValueError("Invalid verifying key(s): expected list or string")

        if isinstance(verifying_key_or_keys, list):
            return self._verify_multi(token, verifying_key_or_keys, num_required=num_required)

        else:
            return self._verify_single(token, str(verifying_key_or_keys))
638934
def verifyJWT(self, token):
        
        logging.debug("verify token: {0}".format(token))
        #1. 拆分解析
        if isinstance(token, (str, unicode)):
            if token.count(".") == 2:
                token = self.analysisJWT(token)
            else:
                raise InvalidTokenError("invalid token")
        else:
            raise TypeError("token is in string or Unicode format")

        #2. 验证header
        if self._header == token["header"]:
            payload = token["payload"]
        else:
            raise InvalidTokenError("header missmatch")

        #3. 验证payload
        for i in self._payloadkey:
            if i in ("exp", "iat"): continue
            #logging.debug("verify payload key: {0}: {1}".format(i, payload.get(i) == self._payload.get(i)))
            if payload.get(i) != self._payload.get(i):
                raise InvalidTokenError("payload contains standard declaration keys")
        if self.get_current_timestamp() > payload["exp"]:
            raise TokenExpiredError("token expired")

        #4. 验证签名
        #头部编码
        first_part  = base64.urlsafe_b64encode(json.dumps(token["header"], sort_keys=True, separators=(',', ':')))
        #载荷消息体编码
        second_part = base64.urlsafe_b64encode(json.dumps(token["payload"], sort_keys=True, separators=(',', ':')))
        #签名以上两部分: 把header、playload的base64url编码加密后再次base64编码.
        third_part  = self.signatureJWT("{0}.{1}".format(first_part, second_part))
        #此处......
        if token["signature"] == third_part:
            logging.info("verify token pass")
            return True
        else:
            raise SignatureBadError("invalid signature")
908030
def verify
      certificate = firebase_id_token_certificates.find(@kid)
      if certificate
        payload = decode_jwt_payload(@jwt_token, certificate.public_key)
        authorize payload
      end
    end
58172
def verify_jwt_in_request():
    
    if request.method not in config.exempt_methods:
        jwt_data = _decode_jwt_from_request(request_type='access')
        ctx_stack.top.jwt = jwt_data
        verify_token_claims(jwt_data)
        _load_user(jwt_data[config.identity_claim_key])
706236
def decode_token(self, token):
        """"""
        key = current_app.secret_key
        if key is None:
            if current_app.debug:
                current_app.logger.debug("app.secret_key not set")
            return None
        try:
            return jwt.decode(
                token, key,
                algorithms=[self.config["algorithm"]],
                options={'require_exp': True}
            )
        except jwt.InvalidTokenError:
            return None